請問這兩行代碼有什麼區別?我試了一下都可以運行成功。
$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." ')";
這個寫法