2017-04-12 36 views
0

我想学习如何在我的PHP中使用准备好的语句,从MySQL数据库中获取数据。目前我没有得到任何打印出来的东西。绑定参数MySQl和PHP

我需要有一个while循环经历我的数据库中的行。那是对的吗?

我在这里正确的方式,或我错过了什么?我在代码中做了一些评论,描述我在做什么。

<?php 

    $stmt = $mysqli->prepare("SELECT * FROM fantasies WHERE headline = ? AND description = ? AND place = ? ORDER BY reg_date DESC LIMIT 3"); 

       // Execute prepared statement 
       if ($stmt->execute()) { 
        $success = true; 
       } 

       // Make variables ready 
       $head = null; 
       $desc = null; 
       $plac = null; 

       // Bind result to variables 
       $stmt->bind_result($head, $desc, $plac); 

       while ($stmt->fetch()) { 

        // What should go here? 
        echo "Headline: ".$head."Description: ".$desc."Place: ".$place; 
       } 
       // Close statement 
       $stmt->close(); 

       // Close connection 
       $mysqli->close(); 

if($success) { 
    echo "Selected Succesfull"; 
} else { 
    echo "Failed: " . $stmt->error; 
    } 
} 
?> 
+0

使用[NUM_ROWS](http://php.net/ manual/enq/mysqli-result.num-rows.php)检查查询返回结果是否为 – Saty

+0

您执行两次 –

+0

感谢您的意见。我更新了我的问题 – KrMa

回答

0

在执行时它应该给你一个错误,代码:

非法参数编号:如您使用的是没有参数的约束

你需要绑定你的参数占位符

$stmt->bind_param("sss", $headline, $description, $place); //missing from your code 

其中“SSS”是具体的数据类型在这种情况下,一个字符串和$headline, $description, $place是你的变量,你用占位符代替

你的代码应该是

<?php 

$stmt = $mysqli->prepare("SELECT * FROM fantasies WHERE headline = ? AND description = ? AND place = ? ORDER BY reg_date DESC LIMIT 3"); 

//bind parameters 
$stmt->bind_param("sss", $headline, $description, $place); 

if ($stmt->execute()) { 
    $stmt->bind_result($head, $desc, $plac); 

    while ($stmt->fetch()) { 

     echo "Headline: " . $head . "desc: " . $desc . "Place: " . $plac; 
    } 
    $stmt->close(); 
} else { 

    echo "error" . $mysqli->error; 
} 

$mysqli->close(); 

?> 
+0

谢谢你的答案。我可以看到你的意思。我只是试着用你的代码。我仍然没有得到任何印刷品。它可以是我的SELECT语句吗? – KrMa

+0

是否有这些变量'$标题,$ description,$ place'? –

+0

是的,我复制了你的代码并尝试了,但它仍然没有给我任何输出。我的数据库中的列名是:'head,description,place'。其实我甚至没有收到“错误”信息。所以它看起来没有什么叫。 – KrMa