$student_info = array(
'student_number'=>$_POST['student_number'],
'student_first_name'=>$_POST['student_first_name'],
'student_middle_name'=>$_POST['student_middle_name'],
'student_last_name'=>$_POST['student_last_name']);
foreach($student_info as $table_row=>$information){
$sql = "INSERT INTO student_info_db (`$table_row`) VALUES(`$information`)";
echo $table_row . " " . $information;
}我不太清楚它为什么不在数据库中插入任何数据。echo $table_row $information只是为了获取值并成功,但仍然不插入任何数据。问题是,出了什么问题?我很确定我做了正确的sql ..。或者我不是?
发布于 2014-02-22 05:14:21
您的sql查询字符串似乎不正确。您正在运行每个元素的查询!它每次都会将数据插入到每一列!您将有4个条目,一个学生的信息在您的桌子!
您也没有在循环中运行查询。
您应该在循环中创建查询,然后在循环之后执行查询。
您需要首先从数组中生成查询字符串。
首先,让您的查询如下:
就像这样:
$student_info = array(
'student_number'=>mysql_real_escape_string($_POST['student_number']),
'student_first_name'=>mysql_real_escape_string($_POST['student_first_name']),
'student_middle_name'=>mysql_real_escape_string($_POST['student_middle_name']),
'student_last_name'=>mysql_real_escape_string($_POST['student_last_name']));
foreach($student_info as $table_row=>$information){
$cols .= "`".$table_row."` ,";
$vals .= "'".$information . "' ,";
}
$cols = rtrim($cols,",");
$vals = rtrim($vals,",");
$sql = "INSERT INTO student_info_db (".$cols . ") VALUES(".$vals .")";使用示例数据的实时演示:https://eval.in/104428
然后,您需要运行这个$sql查询
就像这样:
if(mysqli_query($con, $sql)
echo "successfully inserted";
else
echo "something is wrong!";发布于 2014-02-23 10:11:11
您没有执行查询!首先建立与数据库的连接。然后添加用于执行查询的mysql_query($sql)。
$student_info = array(
'student_number'=>mysql_real_escape_string(htmlspecialchars($_POST['student_number'])),
'student_first_name'=>mysql_real_escape_string(htmlspecialchars($_POST['student_first_name'])),
'student_middle_name'=>mysql_real_escape_string(htmlspecialchars($_POST['student_middle_name'])),
'student_last_name'=>mysql_real_escape_string(htmlspecialchars($_POST['student_last_name'])));
//First we need to make a connection with the database
$host='localhost'; // Host Name.
$db_user= 'root'; //User Name
$db_password= 'nopass';
$db= 'product_record'; // Database Name.
$conn=mysql_connect($host,$db_user,$db_password) or die (mysql_error());
mysql_select_db($db) or die (mysql_error());
$column = "";
$value = "";
foreach($student_info as $table_row=>$information){
if($column != ""){
$column .= ",";
$value .= ",";
}
$column .= $table_row;
$value .= "'".$information."'";
}
$sql = "INSERT INTO student_info_db (".$column.") VALUES(".$value.")";
mysql_query($sql);
mysql_close($conn);发布于 2014-02-22 05:07:20
在foreach循环中,运行查询。就像这样:
$student_info = array(
'student_number'=>$student_number,
'student_first_name'=>$student_first_name,
'student_middle_name'=>$student_middle_name,
'student_last_name'=>$student_last_name);
foreach($student_info as $table_row=>$information)
{
$sql = "INSERT INTO student_info_db (`$table_row`) VALUES('".mysqli_real_escape_string($connection, $information)."')";
mysqli_run($connection, $sql);
echo $table_row . " " . $information;
}关于在此查询的更多信息
https://stackoverflow.com/questions/21949944
复制相似问题