PHP与数据库
1. 判断连接是否成功
$mysqli = new mysqli($DBHOST,$DBUSER,$DBPASS,$DBNAME);
if($mysqli->connect_error)//返回字符串则表示有错误,否则返回NULL
2. 判断查询是否成功mysqli_query返回值
出错代码:
$dbc = mysqli_connect($DBHOST,$DBUSER,$DBPWD,$DBNAME);
$q = "select * from user where u_name='yao'";
$a = mysqli_query($dbc,$q);
if(mysqli_num_rows($a) == 1){..}
报错代码:
if(mysqli_num_rows($a) == 1){..}
报错内容:Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in/usr/local/work/apache/htdocs/fo/php/checkForm.php on line10
报错原因:
mysqli_query查询失败时返回FALSE;如果查询成功,那么,对于SELECT/SHOW/DESCRIBE/EXPLAIN查询,会返回一个mysqli_result对象。而对于其它正确的查询,会返回TRUE。
解决办法:
对mysqli_query的返回值进行检查,确保不是布尔值FALSE才能作为mysqli_num_rows的参数
if($a && mysqli_num_row($a) == 1)
或者
if($result = mysqli_query($dbc,$query))
{
$n = mysqli_num_rows($result);
}
参考链接:
php手册 http://cn.php.net/manual/en/mysqli.query.php
PHP与表单
一. 表单变量的HTML书写格式
复选框的name设置比较特殊,为了方便使用PHP获取复选框的值
<input type="checkbox" id="loveFruits-apple" name="loveFruits[]" value="apple" />
<label for="loveFruits-apple">苹果</label>
<input type="checkbox" id="loveFruits-pear" name="loveFruits[]" value="pear" />
<label for="loveFruits-pear">梨</label>
二. 获取表单变量值
提交表单之后,如果需要获取checkbox的值,务必先用isset检测,这和别的表单元素不一样
假如用户没有勾选checkbox中的任一项,那么如果不检测而直接访问$_POST['loveFruits']则PHP报错
Notice: Undefined index loveFruits
<?php
if(isset($_POST['loveFruits'))
{
$aLoveFruits = $_POST['loveFruits'];
for($i=0,$iLen=count($aLoveFruits); $i<$iLen;$i++)
{
echo $aLoveFruits[$