PHP:在mysql查询后获取记录

时间:2016-01-16 10:24:49

标签: php mysql mysqli

这是一个基本问题,但我发现它非常令人困惑。之前我曾经使用while循环绑定结果并获取它们。我在sql语句中使用*,因此有疑问。这是代码:

$mysql = new mysqli("localhost", "user", "password", "database");
$sql = "SELECT * FROM mytable WHERE id = ?";
$stmt = $mysql->prepare($sql);
$prm = $_POST['txt'];
$stmt->bind_param("i",$prm);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows > 0) {

}

表中有大约20列,因此我想避免在sql中包含所有列名。 如何回显每条记录的所有列?

3 个答案:

答案 0 :(得分:1)

对于bind_result,您必须将查询编写为

 $sql = "SELECT column1,column2 FROM mytable WHERE id = ?";
    $stmt = $mysql->prepare($sql);
    $prm = $_POST['txt'];
    $stmt->bind_param("i", $prm);
    $stmt->execute();
/*bind your result*/
    $stmt->bind_result($col1, $col2);
    if ($stmt->num_rows > 0) {
/* fetch values */
        while ($stmt->fetch()) {
            printf("%s %s\n", $col1, $col2);
        }
    }

阅读http://php.net/manual/en/mysqli-stmt.bind-result.php

<强>更新

使用fetch_array(MYSQLI_ASSOC)

$sql = "SELECT * FROM mytable WHERE id = ?";
    $stmt = $mysql->prepare($sql);
    $prm = $_POST['txt'];
    $stmt->bind_param("i", $prm);
    $stmt->execute();
/*bind your result*/

    if ($stmt->num_rows > 0) {
/* fetch values */
        while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
           printf ("%s (%s)\n", $row["row1"], $row["row2"]);
        }
    }

答案 1 :(得分:1)

        $mysql = new mysqli("localhost", "user", "password", "database");
        $sql = "SELECT * FROM mytable WHERE id = ?";
        $stmt = $mysql->prepare($sql);
        $prm = $_POST['txt'];
        $stmt->bind_param("i",$prm);
        $stmt->execute();
        $result = $stmt->store_result(); //store_result() 

        if ($result->num_rows > 0) { //Uses the stored result and counts the rows.

        while($data = $result->fetch_assoc()){ 
                //And here, the answer-object is turned into an array-(object)
                // which can be worked with nicely.
                //It loops trough all entries in the array.
        }

        }

答案 2 :(得分:1)

使用get_result() 代替 store_result(),然后使用结果对象的->num_rows属性来检查它是否返回任何行,例如这样:

$mysql = new mysqli("localhost", "user", "password", "database");
$sql = "SELECT * FROM mytable WHERE id = ?";
$stmt = $mysql->prepare($sql);
$prm = $_POST['txt'];
$stmt->bind_param("i",$prm);
$stmt->execute();

$result = $stmt->get_result();
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()){

        // your code

    }
}