Jump to content

Inserting list in SQL function


jason360

Recommended Posts

Hello,  I am trying to insert this string into my data base but it is failing and I am getting my die message. Anyone see why this is not working?  I am connected to my database too.

$string="Toyota,
Volkswagen, 
Samsung, 
Ford,
HewlettPackard";

$string=explode(',',$string);
foreach($string as $val)
    {
    $val=strtolower($val);
    mysql_query('INSERT INTO companies (brands) VALUES ("'.$val[0].'")') or die ('fail insert');
    }
Link to comment
Share on other sites

why not have it show the actual mysql_error() instead of a 'fail insert', which tells you basically nothing?

 

Also, the mysql extension is deprecated and will be removed from a future version of PHP. Best to use PDO or MySQLi if you want your code to run on future versions of php.

Link to comment
Share on other sites

In addition to CroNix, look in to PDO transactions.  If you have a situation where you're making multiple inserts or updates, it best to use transactions to batch process your queries.  Using your example:

$queue = array(
  "INSERT INTO companies (brands) VALUES('Toyota')",
  "INSERT INTO companies (brands) VALUES ('Volkswagen')"
); //keep adding your inserts

try {
  $dbh = new PDO(DB_HOST, DB_UNAME, DB_UPWORD, array(PDO::ATTR_PERSISTENT => true));
} catch (Exception $e) {
  die("Unable to connect: ".$e->getMessage());
}

try {
  $dbh->beginTransaction();
  foreach ($queue as $query) {
    $dbh->exec($query);
  }
  $dbh->commit();
} catch (Exection $e) {
  $dbh->rollBack();
  echo "Query execution failed".$e->getMessage();
}

It seems like more lines of code and more complicated, but it is safer, better and more efficient.

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.