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
https://forums.phpfreaks.com/topic/295060-inserting-list-in-sql-function/
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.

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.

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.