对于每个循环PHP,插入SQL不插入数据

时间:2014-02-22 05:02:43

标签: php sql database

$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 $信息只是为了获取值并且它成功,但仍然没有插入任何数据。问题是,出了什么问题?我很确定我正在做正确的sql ..或者我不是吗?

4 个答案:

答案 0 :(得分:2)

看来你的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!";

答案 1 :(得分:2)

您没有执行查询!首先建立与数据库的连接。然后添加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);

答案 2 :(得分:0)

在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;
}

有关mysqli_query here

的更多信息

答案 3 :(得分:0)

执行此操作的proper way是使用prepared statement with placeholders

$sql = <<<'END'
    INSERT INTO student_info_db (
        student_number,
        student_first_name,
        student_middle_name,
        student_last_name
    ) VALUES (?, ?, ?, ?)
END;

$stmt = $dbConnection->prepare( $sql )

$stmt->bind_param( 's', $_POST['student_number'] );
$stmt->bind_param( 's', $_POST['student_first_name'] );
$stmt->bind_param( 's', $_POST['student_middle_name'] );
$stmt->bind_param( 's', $_POST['student_last_name'] );

$stmt->execute();

或者,如果你坚持使用数组作为中间阶段:

$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']
);

$keys = array_keys( $student_info );
$columns = implode( ',', $keys );
$holders = implode( ',', array_fill( 0, count($keys), '?' ) );

$sql = "INSERT INTO student_info_db ($columns) VALUES ($holders)";
$stmt = $dbConnection->prepare( $sql )

foreach ( $keys as $key ) {
    $stmt->bind_param( 's', $student_info[$key] );
}
$stmt->execute();