我正在尝试使用PHP将数据输入数据库。
这是我的代码:
<?php
$username = 'username'; //username for database
$password = 'password'; //password for database
$hostname = 'localhost'; //host
$db_name = 'db_testdrubin'; //name of database
$db_selected = mysqli_connect($hostname, $username, $password, $db_name)//specify database
or die ("unable to connect");
if(isset ($_POST['submit'])){
$ID = ($_POST['ID']);
$fname = ($_POST['fname']);
$lname = ($_POST['lname']);
$address = ($_POST['address']);
$city = ($_POST['city']);
$state = ($_POST['state']);
$zip = ($_POST['zip']);
$phone = ($_POST['phone']);
$email = ($_POST['email']);
$books = ($_POST['books[]']);
$comments = ($_POST['comments']);
}
else{
echo'<p>not submitted</p>';
}
//up until this point the code works fine
$query = 'INSERT INTO Student VALUES ($ID, $fname, $lname, $address, $city, $state, $zip, $phone, $email, $books, $comments)';
$success = $db_selected->query($query);
if($success){
$count = $db_selected->affectd_rows;
echo '<p>$count were added</p>';
}
else{
echo '<p>error</p>';
}
?>
我知道正在从html表单中正确读取信息,因为我已经通过打印单个变量进行了检查。我提交表单时没有收到任何错误消息,只是来自if / else语句的“error”echo语句,并且没有数据输入到数据库中。
我也试过这个:
if (!mysql_query($db_selected, $query)){
echo '<p>error</p>';
}
具有相同的结果。
答案 0 :(得分:1)
更改此
$query = 'INSERT INTO Student VALUES ($ID, $fname, $lname, $address, $city, $state, $zip, $phone, $email, $books, $comments)';
到
$query = "INSERT INTO Student VALUES ($ID, '$fname', '$lname', '$address', '$city', '$state', $zip, $phone, '$email', '$books', '$comments')";
我的意思是说它的字符串是否就像&#39; $ string&#39;并使用
$db_selected->real_escape_string($stringval);
并使用
echo $db_selected->error;
检查你得到的错误。
答案 1 :(得分:0)
$ins="insert into Student (`id`,`fname`,`lname`,`address`,`city`,`state`,`zip`,`phone`,`email`,`books`,`comments`)values
('".$ID."','".$fname."','".$lname."','".$address."','".$city."','".$state."','".$zip."','".$phone."','".$email."','".$books."','".$comments."')";
mysql_query($ins);