jason360 Posted March 4, 2015 Share Posted March 4, 2015 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'); } Quote Link to comment https://forums.phpfreaks.com/topic/295060-inserting-list-in-sql-function/ Share on other sites More sharing options...
CroNiX Posted March 4, 2015 Share Posted March 4, 2015 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. Quote Link to comment https://forums.phpfreaks.com/topic/295060-inserting-list-in-sql-function/#findComment-1507434 Share on other sites More sharing options...
CroNiX Posted March 4, 2015 Share Posted March 4, 2015 But your problem is you are inserting this: $val[0] when $val is no longer an array. It's a value FROM the array that you are looping through. Just use $val there. Quote Link to comment https://forums.phpfreaks.com/topic/295060-inserting-list-in-sql-function/#findComment-1507435 Share on other sites More sharing options...
rwhite35 Posted March 4, 2015 Share Posted March 4, 2015 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. Quote Link to comment https://forums.phpfreaks.com/topic/295060-inserting-list-in-sql-function/#findComment-1507436 Share on other sites More sharing options...
jason360 Posted March 4, 2015 Author Share Posted March 4, 2015 Okay...thanks for the info. Looks like I got a big job ahead of me switching to mysqli. Quote Link to comment https://forums.phpfreaks.com/topic/295060-inserting-list-in-sql-function/#findComment-1507441 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.