如何在mysqli预处理语句中打印获取的值?

时间:2016-03-14 11:40:42

标签: php mysqli prepared-statement

我的HTML格式:

<form action="" method="post" > 
<tr> 
<td><select name="bs_edu">
<option value="" selected="selected">Select Basic Education</option>   
<option value="BA">B.A</option>
<option value="BARCH">B.ARCH</option>
<option value="BCA">BCA</option>
<option value="BBA">BBA</option> 
</select>
<td><input type="text" name="desg"/> </td>
<td><input type="email" name="email"/></td>
</tr>
</form>

我的查询:

<?php
    $stmt = $con->prepare("SELECT * FROM user_tbl WHERE bs_edu = ? AND desg = ? AND exp = ? AND pr_sal = ? AND plc = ? AND email = ?  ");
    $stmt->bind_param('ssssss', $_POST['bs_edu'], $_POST['desg'], $_POST['exp'], $_POST['prsal'], $_POST['place'], $_POST['email']);
    $stmt->execute();
    $result = $stmt->get_result();
    if ($result->num_rows > "0")
    {
        while($row = $result->fetch_assoc());
        {
            echo 'first name: ' .$row['fname'];  
        }
    }
    $stmt->close(); 
?>

我知道这是显示数据的错误方法。通过本手册http://php.net/manual/en/mysqli-stmt.fetch.php n真的运气不好,展示如何显示获取的数据..这里有任何帮助..谢谢

1 个答案:

答案 0 :(得分:1)

以下分号表示循环停止,是语句字符的结尾。

while($row = $result->fetch_assoc());
                                    ^ end of statement

删除它。

while($row = $result->fetch_assoc())

你不会得到关于它的错误,因为它被认为是有效的语法。

引用的零也被解释为字符串,因此您需要将其删除。

if ($result->num_rows > 0)

关于get_result()的旁注。

手册http://php.net/manual/en/mysqli-stmt.get-result.php声明:

仅限MySQL本机驱动程序

仅适用于mysqlnd

从此回答中提取的示例https://stackoverflow.com/a/24985955/

if ($stmt = $mysqli->prepare("SELECT id, community, map, image FROM `googleMaps`")) {
    $stmt->execute();
    $stmt->bind_result($id, $community, $map, $image);
    while ($stmt->fetch()) {
            printf("%s %s\n", $title);
    }
    $stmt->close();
}

补充说明。

<form>不能是<table>的孩子,因为我怀疑您可能会在未显示的代码中隐藏<table></table>个标签。

您也没有与POST阵列匹配的表单元素。

在打开PHP标记后立即将错误报告添加到文件的顶部 例如
<?php error_reporting(E_ALL); ini_set('display_errors', 1);然后代码的其余部分,看它是否产生任何结果,  以及or die(mysqli_error($con))mysqli_query()

或者另一种方法是改变:

$stmt->execute();

为:

if(!$stmt->execute()){
   trigger_error("There was an error.... ".$con->error, E_USER_WARNING);
}

编辑:

借鉴这个答案https://stackoverflow.com/a/22899155/

$stmt = $con->prepare("SELECT * FROM user_tbl ... ");

$result = $stmt->execute(); 
$stmt->store_result();

if ($stmt->num_rows > 1) {

  while($row = $result->fetch_assoc()){ 

  echo 'First name: ' .$row['fname'];

  }

}else{

   echo "0 records found";
}

另外,您似乎也在同一个文件中使用HTML表单和PHP / MySQL。

您需要对POST阵列使用isset()!empty()

您还没有提交提交按钮,如果您使用的话,则不知道。

与我已经说过的关于缺少具有匹配名称属性的表单元素的内容相同:

  • $_POST['exp']
  • $_POST['prsal']
  • $_POST['place']