php - 学习 SELECT FROM WHERE 预处理语句

标签 php mysql

有人可以将下面的代码重写为准备好的语句吗?

result = mysqli_query($con,"SELECT * FROM note_system WHERE note = '$cnote'") 
or die("Error: ".mysqli_error($con));

while($row = mysqli_fetch_array($result))
{
$nid = $row['id']; 

}

我正在尝试学习准备好的语句,但无法从我在搜索时发现的许多示例中理解它是如何工作的。我希望如果我看到一些我熟悉的代码被重写为准备好的语句,它可能会为我点击。请不要使用 PDO,以我目前的知识水平,这对我来说太困惑了。谢谢。

最佳答案

你好 ButterDog 让我一步一步地引导你完成 PDO。

步骤 1)

创建一个名为 connect.php 的文件(或任何你想要的)。每个需要数据库交互的 php 文件都需要这个文件。

让我们开始也请注意我的意见:

?php

//We set up our database configuration
$username="xxxxx"; // Mysql username
$password="xxxxx"; // Mysql password


// Connect to server via PHP Data Object
$dbh = new PDO("mysql:host=xxxxx;dbname=xxxxx", $username, $password); // Construct the PDO variable using $dbh
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // Set attributes for error reporting very IMPORTANT!
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, FALSE); // Set this to false so you can allow the actual PDO driver to do all the work, further adding abstraction to your data interactions.
?>

第 2 步)需要 connect.php 请看一下:

require ('....../........./...../connect.php'); // Require the connect script that made your PDO variable $dbh

步骤 3)

要启动数据库交互,只需执行以下操作,另请阅读代码注释。目前我们不用担心数组!了解 PDO 的全部内容,然后担心如何让它更容易使用!随着重复,“漫长的道路”会带来对代码的更多理解。一开始就不要偷工减料,一旦你明白自己在做什么,就不要偷工减料!

$query = $dbh->prepare("SELECT * FROM note_system WHERE note = :cnote"); // This will call the variable $dbh in the required file setting up your database connection and also preparing the query!

$query->bindParam(':cnote', $cnote); // This is the bread and butter of PDO named binding, this is one of the biggest selling points of PDO! Please remember that now this step will take what ever variable ($cnote) and relate that to (:cnote)

$query->execute(); // This will then take what ever $query is execute aka run a query against the database

$row = $query->fetch(PDO::FETCH_ASSOC); // Use a simple fetch and store the variables in a array

echo $row['yourvalue']; // This will take the variable above (which is a array) and call on 'yourvalue' and then echo it.

这就是 PDO. 的全部内容希望对您有所帮助!

另请查看 this .这对我帮助很大!

我也用 this作为引用(有时)-该网站看起来很糟糕,但那里有关于 PDO 的质量信息。我也用 this我发誓这是最后一个链接!因此,在此之后有任何问题都可以提出,但希望这可以变成 PDO 的一些引用指南。 (希望大声笑)

关于php - 学习 SELECT FROM WHERE 预处理语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16072212/

相关文章:

php - 使用mysql处理大数据

php - 如何将 Facebook 页面帖子作为博客帖子拉入 WordPress?

php - SQL JOIN ON 表名等于字段值

php - 两个不同查询之间的速度

mysql - 每人如何使用MYSQL LIMIT

php - SQL : selecting customers that haven't had an entry in past 2 weeks

php - 从 sibling 中检索数据到匹配的节点

mysql - 使用mysql2-promise和node创建多个新的Mysql数据库连接

php - 如何将 "../"添加到 PHP echo img src

php - 如何设置表的优先级?