Optimized php code insert query outside loop

I have to optimize below code, thanks in advance

HTML:

<?php include 'database.php'; $query=mysql_query("select id,brief from job_attributes") or die(mysql_error()); while($res=mysql_fetch_array($query)) { echo "" . $res['brief'] . '
'; } ?>

PHP:
if($result = mysql_query($sql)){
$last_id = mysql_insert_id();
}
$attr_id= $_POST[‘explained’];

if($attr_id)
{
foreach ($attr_id as $ai) {
mysqli_query($connect, “INSERT INTO explained_job_attributes (attr_id,user_id) VALUES (’”.mysqli_real_escape_string($connect,$ai)." ', “.$last_id.”)" );

}

}

just prepare the statement outside the loop and then bind the variable(s) and execute inside the loop. It will increase both performance and security at the same time :slight_smile:

And instead you did a code dump?

I am new to php so please anyone can modify my code and give to me…

I changed my foreach loop like this but unable to insert into database

if($attr_id) {
$str = ‘’;
$str1 = ‘’;
foreach ($attr_id as $ai) {
$str .= $ai;
$str1.= $last_id;
}
echo $str;
echo $str1;
$sql1 = ‘INSERT INTO explained_job_attributes (attr_id, user_id) VALUES ("’.mysqli_real_escape_string($connect,$str).’", “’.$str1.’”);’;
if(mysql_query($sql1)) {
echo ‘Inserted’;
}else {
echo ‘not inserted’;
}
}

it gives as not inserted

Plenty of freelancers available for hire in PHP :slight_smile:

You can’t mix mysqli and mysql, mysql_* functions are an older api which is now removed from PHP.

[hr]

You should just use your original code with the changes I mentioned
http://php.net/manual/en/mysqli.prepare.php

JimL thanks for your reply…

But still i am not able to resolve it can you please modify my code

Sponsor our Newsletter | Privacy Policy | Terms of Service