Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert php array into mysql table

Update: I forgot to mention that echo $matstring outputs '65.70', 'Coles','34 days','14' - which would appear to be the right syntax?

I'm a php/mysql newbie, and I think this is fairly basic, but having read all of the other stackoverflow questions on this topic and fiddling with different versions of my code for several hours I can't understand what I'm doing wrong. Would very much appreciate any help/suggestions.

Aim: pass data from my php array ($matrix) into a mysql table

$matrix[1]=
( [0] => 65.70 [1] => Coles [2] => 34 days [3] => 14 )

$matrix[2]=
( [0] => 62.70 [1] => Coles [2] => 13 days [3] => 14 )

$matrix[3]=
( [0] => 12.70 [1] => Safeway [2] => 43 days [3] => 14 )

Code:

$matstring=implode("','",$matrix[1]);
$matstring="'".$matstring."'";
mysql_query('INSERT INTO Australia (Price, Company, Days, Weight) VALUES ('$matstring')');
like image 704
user2037290 Avatar asked Oct 05 '22 22:10

user2037290


2 Answers

when i run this code :

$matrix = array();
$matrix[1] = array( 0 => 65.70, 1 => 'Coles', 2 => '34 days', 3 => 14 );
$matstring=implode("','",$matrix[1]);
$matstring="'".$matstring."'";
print "INSERT INTO Australia (`Price`, `Company`, `Days`, `Weight`) VALUES ($matstring)";

become result:

INSERT INTO Australia (`Price`, `Company`, `Days`, `Weight`) VALUES ('65.7','Coles','34 days','14')
like image 123
Eugen Avatar answered Oct 10 '22 03:10

Eugen


Corrected code:

$matstring=implode("','",$matrix[1]);

mysql_query("INSERT INTO Australia (Price, Company, Days, Weight) VALUES ('$matstring')");

(i.e. delete the second line from original code and put double quotes around the argument of mysql_query)

Appreciate user1847757's help - as s/he pointed out, $matstring itself was correct, but the single quotes inside of VALUES(' ') were being joined to the single quotes added to $matstring in the 2nd line of my original code, resulting in VALUES(''65.70','Coles','34 days','14'')

Thanks all for your help & suggestions

like image 40
user2037290 Avatar answered Oct 10 '22 03:10

user2037290