简体   繁体   English

PHP + MySQL查询->此SQL有什么问题(简短)

[英]PHP + MySQL query -> What's wrong with this SQL (short)

I have finally graduated from MS Access to MySQL. 我终于从MS Access到MySQL毕业了。 Unfortunately, I can't even get a query right. 不幸的是,我什至无法正确查询。 Can someone please tell me what's wrong? 有人可以告诉我怎么了吗? I keep getting the 'invalid query' message that I specified in the php. 我不断收到我在php中指定的“无效查询”消息。

<?php
@ $db = mysql_connect('localhost', 'root', 'root', 'newdatabase');
if (!$db) {
    die ('Failed to connect to the database.');
}


$query = "SELECT first FROM demographics";
$result = mysql_query($query);

if (!$result) {
    die('invalid query');
}

while ($row = mysql_fetch_assoc($result)) {
    echo $row['first'];
}

?>

Also, the book I am reading tells me to use: 另外,我正在阅读的书告诉我使用:

new mysqli('localhost', 'root', 'root', 'newdatabase')

to connect as opposed to the 连接而不是

mysql_connect

I used in the above code. 我在上面的代码中使用过。 I haven't been able to connect to the db with new mysqli . 我无法使用新的mysqli连接到数据库。 Does it matter which one I use? 我使用哪一个无关紧要?

The fourth parameter to mysql_connect() is not the database name. mysql_connect()的第四个参数不是数据库名称。 It is a boolean specifying whether or not to establish an additional new connection or use an existing one. 它是一个布尔值,用于指定是建立其他新连接还是使用现有连接。 Most often, it is omitted. 通常,它被省略。 Use mysql_select_db() to choose the database. 使用mysql_select_db()选择数据库。 Since you have not selected a database in your code, your query is likely failing. 由于您尚未在代码中选择数据库,因此查询很可能失败。

$db = mysql_connect('localhost', 'root', 'root');
if (!$db) echo mysql_error();
else mysql_select_db("database");

Note I have removed the @ from the mysql_connect() call. 注意我已经从mysql_connect()调用中删除了@ @ suppresses errors, and was probably preventing you from seeing what was going wrong with your connection. @抑制错误,并且可能阻止了您查看连接出了什么问题。

When testing the success or failure of a query, don't die() . 测试查询的成功或失败时,请不要die() Instead echo out mysql_error() while developing your application. 相反,在开发应用程序时回显mysql_error() In production, you can replace the echo by writing to error_log() instead. 在生产中,可以更换echo通过写error_log()来代替。

if (!$result) {
  echo mysql_error();
}

As for using MySQLi instead of the basic mysql_* functions, MySQLi can be used in an object oriented fashion and also offers prepared statements, which can be both more efficient to use and more secure. 至于使用MySQLi代替基本的mysql_*函数,MySQLi可以以面向对象的方式使用,并且还提供了准备好的语句,这既可以更有效地使用,也可以更安全。 As mentioned in comments above, PDO is often recommended as the most flexible API for interacting with an RDBMS from PHP. 如上面的评论所述,通常建议将PDO作为与PHP中的RDBMS进行交互的最灵活的API。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM