duanbichou4942 2014-01-02 01:05
浏览 55
已采纳

PHP For循环构建插入字符串

I'm trying to insert several values into a database.

First I add these values to array (function/other code omitted):

$name = (isset($_POST['name']) ? ($_POST['name']) : "name");
$email = (isset($_POST['email']) ? ($_POST['email']) : "email"); 
$username = $mysqli->real_escape_string($_POST['username']);
$password = $mysqli->real_escape_string(md5($_POST['password']));

Like so:

$formvars = array();
array_push($formvars, $name, $email, $username, $password); 

Then call function to insert:

    $sql = array(); 
        for ($i = 0; $i < count($formvars);$i++) {
            $sql[] = $formvars[$i];
        }

        print_r(implode(',', $sql));

        $qry = 'INSERT INTO chinesegame (name, email, username, password) VALUES '. implode(',' , $sql);

        if(!$mysqli->query($qry))
        {
            echo "Error inserting data to the table 
query:$qry";
            return false;
        }        

    return true;

My DB structure is as such:

enter image description here

It's giving me an insert error:

Error inserting data to the table query:INSERT INTO chinesegame (name, email, username, password) Dan,dthusky@gmail.com,danman,827ccb0eea8a706c4c34a16891f84e7b

Can I not build an insert string like that?

  • 写回答

2条回答 默认 最新

  • douyun8885 2014-01-02 01:12
    关注

    You forgot your "VALUES" keyword. and parenthesis help too. You also need all of the values to be in quotes, here is the correct version:

    $qry = 'INSERT INTO chinesegame (name, email, username, password) VALUES ("'. implode('","' , $sql). '")';
    

    Also, mysqli->query takes a connection variable first which has the connection information to the database, it should look like this:

    $connection = mysqli_connect("localhost","my_user","my_password","my_db");
    if(!$mysqli->query($connection, $qry))
    

    Also, for the record,

        $sql = array(); 
        for ($i = 0; $i < count($formvars);$i++) {
            $sql[] = $formvars[$i];
        }
    

    could be replaced with

    $sql = $formvars;
    

    there is no reason to loop through the whole thing getting them one at a time.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化