Jump to content

using for each


manalnor

Recommended Posts

Hello dear friends,

 

Let say we have database table (id,text,code)

 

and text will be added from textarea

 

so i'm going to use the following

 

$text=nl2br($text);  // now per line
$sites=explode("<br />",$text); // now will seprate it

 

and code it just random number

 

srand ((float) microtime() * 10000000);
$random = rand(1, 1000000);
$code = $random;

 

now every line will be add as own entry using the following

 

foreach ($text as $value)
{
$sql = "INSERT INTO $table (text, code) VALUES ('$value', '$code')";
mysql_query($sql, $conn) or die(mysql_error());
}

 

Now each line added as own entry but the problem is all having the same random number generated

 

so how can i apply it for each for both $text and $code

 

 

example explain more

 

if we entered in textarea the following

 

hello world
i love this world

 

the above code will enter it as

 

(hello world,84777)  // 84777 is random code
(i love this world,84777)  // 84777 is the same

 

how then i can explod for both $text and $code so in each entry gets new random number

 

 

thanks.

Link to comment
Share on other sites

Do NOT run MySQL queries in loops. Use the foreach loop to create the insert record text and then run one query at the end.

 

$values = array();
foreach ($text as $value)
{
    $code = rand(1, 1000000);
    $values[] = "('$value', '$code')";
}

$sql = "INSERT INTO $table (text, code) VALUES " . implode(', ', $values);
mysql_query($sql, $conn) or die(mysql_error());

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.