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 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?