简体   繁体   中英

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

straight into phpmyadmin it inserts fine. 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:

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());

** If I change

'". $code['prize']."'

to '0' I still get the same error.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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