简体   繁体   English

从php foreach循环插入MySQL

[英]Insert into mySQL from php foreach loop

I know this has been asked so many times but I can't seem to figure the issue out. 我知道这个问题已经被问了很多遍了,但是我似乎无法弄清楚这个问题。 Im running the following code, but it just returns the fail. 我正在运行以下代码,但它只会返回失败。 When I run the output of 当我运行输出

$query1 --> INSERT INTO number (count,code,prize,printed) VALUES ('1','Q0stZr0g8uc4syE','','0'); $ query1-> INSERT INTO编号(count,code,prize,printed)VALUES('1','Q0stZr0g8uc4syE','','0');

straight into phpmyadmin it inserts fine. 直接插入phpmyadmin,它可以插入。 I must be doing something stupid... Any ideas? 我一定在做蠢事...有什么想法吗?

$times_to_run = 100;
$prize='';

for($i=1;$i<=$times_to_run;$i++){

    $array[] = array(
            'count' => $i,
            'code1' => randomString(),
            'prize' => $prize
    );
}

$codes = $array;

foreach ($codes as $code){

    $query1 = "INSERT INTO number (count,code,prize,printed) VALUES ('". $code['count']."','". $code['code1']."','". $code['prize']."','0');";

    $q = mysqli_query($query1) or die (mysql_error());

}

EDIT: I changed the query to use mysqli and got the full error which is: the actual error is: 编辑:我将查询更改为使用mysqli,并得到了完整的错误是:实际错误是:

Warning: mysqli_query() expects at least 2 parameters, 1 given and the line it points to is: $q = mysqli_query($query1) or die (mysql_error()); 警告:mysqli_query()需要至少2个参数,给定1个参数,它指向的行是:$ q = mysqli_query($ query1)或die(mysql_error());

** If I change **如果我改变

'". $code['prize']."' '“。$ code ['prize']。”'

to '0' I still get the same error. 到“ 0”,我仍然收到相同的错误。

To make things clear, here is the corrected version of your code: 为了清楚起见,这是代码的更正版本:

$link = mysqli_connect("localhost", "my_user", "my_password", "world");
$times_to_run = 100;
$prize='';

for($i=1;$i<=$times_to_run;$i++){

    $array[] = array(
            'count' => $i,
            'code1' => randomString(),
            'prize' => $prize
    );
}

$codes = $array;

foreach ($codes as $code){

    $query1 = "INSERT INTO number (count,code,prize,printed) VALUES ('". $code['count']."','". $code['code1']."','". $code['prize']."','0')";

    $q = mysqli_query($link, $query1) or die (mysqli_error($link));

}

I might be wrong here but I think there are spaces needed after ] and after that . 我在这里可能是错误的,但我认为]之后和之后需要空格。 Like this: 像这样:

'" . $code['count'] . "'

instead of 代替

'". $code['count']."'

Oh and just something that might be handy and good to know, mysql_query is deprecated and unsafe, unles you are using it for yourself at a local host I would suggest you take a look at mysqli_, which works basicly the same. 哦,还有一些可能会很方便并且很高兴知道的东西,mysql_query已被弃用并且不安全,除非您在本地主机上自己使用它,否则我建议您看看mysqli_,它的工作原理基本相同。

http://php.net/manual/en/function.mysql-query.php http://php.net/manual/en/function.mysql-query.php

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM