我正在努力将数据从表单插入到数据库中。我设法建立连接(至少没有得到任何错误),但是当插入值我面临错误时,我不确定表中的行/列是否应该在''或者不是,我看到了一些带引号和不带的例子,以及变量也应该有这些例子。
连接数据库(connect.php):
<?php
define("DB_SERVER","localhost");
define("DB_USER","root");
define("DB_PASS","");
define("DB_NAME","Bookshop");
$connection = mysql_connect(DB_SERVER, DB_USER, DB_PASS);
if(!$connection){
die("error: unable to connect to database " . mysql_error());
}
$select_db = mysql_select_db(DB_NAME, $connection);
if(!$select_db){
die("error: unable to connect to database " . mysql_error());
}
?>
包括连接:
<?php
include ("connect.php"); // connects to database
?>
并从表单中插入数据:
$query = "INSERT INTO customer
(CUST_ID, CUST_NAME, CUST_SURNAME, HOUSE_NO, STREET, POSTCODE, PHONE_NO, EMAIL, OGIN, PASSWORD)
VALUES
('10101', '$forename', '$surname', '$address1', '$address2', '$postcode',
'$phone_no', '$email', '$login', '$password')";
mysql_query($query, $connection);
if(!mysql_query($query, $connection)){
echo "Error!!!!";
}
mysql_close($connection);
答案 0 :(得分:1)
看来你是新手..从mysqli或pdo扩展开始。访问W3schools.com获取详细的解释,并附上示例。下面是如何使用mysqli连接并在数据库中插入行
的示例 <?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john@example.com')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
并为您的查询...
我不确定表中的行/列是否应该在&#39; &#39;或不, 我看过一些带引号和没有的例子,和 如果变量也应该具有那些。
就插入查询而言, 1)。用`back ticks包装列名。 2)。用单引号包装你的变量没有错误
有关单引号和双引号用法的更多信息,
单引号不会在双引号
时查找变量案例1:
$value = 10;
$sql = 'SELECT * FROM `table_name` WHERE `column_name` = $value';
echo $sql;
输出
SELECT * FROM `table_name` WHERE `column_name` = $value
这里,如果您看到单引号不在其中查找变量。无论单引号内是什么,它都被视为一个字符串并返回原样。
案例2:
$value = 10;
$sql = "SELECT * FROM `table_name` WHERE `column_name` = $value";
echo $sql;
输出
SELECT * FROM `table_name` WHERE `column_name` = 10
此处由于查询在双引号内,因此读取该变量。但被认为是int。
案例3:
$value = 10;
$sql = "SELECT * FROM `table_name` WHERE `column_name` = '$value'";
echo $sql;
输出
SELECT * FROM `table_name` WHERE `column_name` = '10'
此处由于查询在双引号内,因此读取该变量。但被认为是字符串,因为它用单引号封装。