请问这两行代码有什么区别?我试了一下都可以运行成功。
$query = "insert into books values (' ".$isbn." ', ' ".$author." ', ' ".$title." ', ' ".$price." ')";
$query = "insert into books values (' $isbn ', ' $author ', ' $title', ' $price ')";`
完整代码from PHP和MySQL Web开发(原书第4版):
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<h1>Book-O-Rama Book Entry Result</h1>
<?php
//create short variable names
$isbn=$_POST['isbn'];
$author=$_POST['author'];
$title=$_POST['title'];
$price=$_POST['price'];
if (!$isbn || !$author || !$title || !$price){
echo "You have not entered all the required details. <br />". "Please go back and try again";
exit;
}
if (!get_magic_quotes_gpc()){
$isbn = addslashes($isbn);
$author = addslashes($author);
$title = addslashes($title);
$price = doubleval($price);
}
@ $db = new mysqli('localhost', 'root', '123', 'mydb');
if (mysqli_connect_errno()){
echo "Error: Could not connect to database. Please try again later.";
exit;
}
$query = "insert into books values (' ".$isbn." ', ' ".$author." ', ' ".$title." ', ' ".$price." ')";
$result = $db->query($query);
if ($result) {
echo $db->affected_rows. "book inserted into database.";
} else {
echo "An error has occurred. The item was not added.";
}
$db->close();
?>
</body>
</html>
2种都可以,在php中,双引号也会解析变量的
$query = "insert into books values (' $isbn ', ' $author ', ' $title', ' $price ')";
这个在php是比较特殊的一点,但为了比较好的习惯,一般会采用
$query = "insert into books values (' ".$isbn." ', ' ".$author." ', ' ".$title." ', ' ".$price." ')";
这个写法
没有使用框架?
$query = "insert into books values (' ".$isbn." ', ' ".$author." ', ' ".$title." ', ' ".$price." ')";
这里面的点是PHP的字符串连接符,但别一种写法我还真不知道。
推荐第一种写法,第二种写法真的可以插入有效的数据?表示怀疑,就算可以也最好别用。
根据这个网页http://www.webdeveloper.com/forum/showthread.php?173976-Attemp-to-connect-to-DB-failed-Help!:
There is no reason to use the 'mysql improved functions' to accomplish this, just use the standard mysql_connect, mysql_select_db, and mysql_query() functions to accomplish it. Also, when using an INSERT INTO query, it's good practice to specifically name the fields.
PHP Code:
$query = "INSERT INTO books (isbn, author, title, price) VALUES ('$isbn', '$author', '$title', '$price')";
说明第二种写法也是对的。请问第一种写法为什么这样写?
这2种方法都可以,但是第一种快一点也好点,推荐使用低一点
两种都可以,因为"会解释$变量。
效果一样的 但如果是数组的话 就用第一种方法 如果是单独一个变量就用第二种方法吧
第一种是拼接字符串的形式,
第二种把变量嵌入字符串。