PHP MYSQL 查询快捷方式?
如果我使用 where 子句对表进行 PHP MYSQL 选择,该子句仅返回 1 个结果,是否有更简单的方法来执行此操作:
$result = mysql_query("select * FROM cart WHERE ID='".$cartID."'") or die(mysql_error());
$cartrec = mysql_fetch_array($result);
是否需要 $cartrec = mysql_fetch_array($result);
或者我可以这样做: $cartrec = mysql_query("select * FROM cart WHERE ID='".$cartID."'") or die(mysql_error());
还是有更好的语法可以使用?
If I am doing a PHP MYSQL select of a table using the where clause that will return only 1 result, is there a simpler way to do this:
$result = mysql_query("select * FROM cart WHERE ID='".$cartID."'") or die(mysql_error());
$cartrec = mysql_fetch_array($result);
Is the $cartrec = mysql_fetch_array($result);
needed or could I just do:$cartrec = mysql_query("select * FROM cart WHERE ID='".$cartID."'") or die(mysql_error());
or is there a better syntax to use?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
mysql_query
根据您的查询获取一个结果集(实际上,一个资源引用结果集)。这是与您的查询匹配的记录集。mysql_fetch_array
从结果集中获取第一条记录,并将其作为数组返回。因此,在调用 mysql_fetch_array 之前,您还没有获得可用格式的数据。
旁注:考虑使用PDO
mysql_query
gets a result set (actually, a resource that refers to a result set) based on your query. This is the set of records that match your query.mysql_fetch_array
gets the first record from a result set, and returns it as an array.So, up until you've called
mysql_fetch_array
, you haven't gotten the data in a usable format.Side note: Consider using PDO
需要获取数组,mysql_query 获取结果集(资源),然后 mysql_fetch_array 获取结果集中的元素。
顺便说一句,请小心 SQL 注入: http://en.wikipedia.org/wiki/SQL_injection< /a>
编辑:可能比您需要的更高级,但研究 PDO 可能值得: http://php.net/manual/en/book.pdo.php
The fetch array is required, the mysql_query gets a result set (ressource), then mysql_fetch_array get's the element in the result set.
As a side note, be careful of SQL injections: http://en.wikipedia.org/wiki/SQL_injection
EDIT: Might be a bit more advanced that what you need, but it might be worth while looking into PDO: http://php.net/manual/en/book.pdo.php
是的,否则您得到的是资源指针而不是结果集(数组)。
是的,MySQLi
Yes, otherwise you get a resource pointer not an result set (array).
Yes, MySQLi
不,但是人们为这个用例编写自己的函数是很常见的。它通常命名为 fetch_one($sqlString) 或 fetch_first($sqlString)
No, but its pretty common for people to write their own function for this use case. It's usually named something like fetch_one($sqlString) or fetch_first($sqlString)
你可以使用这个,但是如果数据库结构要改变,就会有问题
你可能想看看这个 http://www.php.net/manual/en/function.mysql-fetch-row.php
You could use this, but if the database structure were to change, it would be problematic
You may want to look at this http://www.php.net/manual/en/function.mysql-fetch-row.php