I have a database test with table name table with two columns user & email.
Whats wrong with my below code? Am not able to add the array $u to my db
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("test", $con);
$user = "safwan";
$email = "esafw@jdjd.com";
$u = array ( user => $user,
email => $email
);
$q = "INSERT INTO table VALUES ($u)";
mysql_query($q) OR die(mysql_error());
mysql_close($con);
?>
You have a couple of issues:
You’re trying to insert an array directly into your database. You need to be accessing the values individually.
You should use quotes around strings, that includes when they are keys in an array
You need to learn about SQL injections
You should consider migrating away from mysql_* functions since they will soon be going away.
table is a MySQL keyword and needs backticks if it’s actually the table name
$user,
’email’ => $email
);
$q = “INSERT INTO table (user, email) VALUES (‘”.mysql_real_escape_string($u[‘user’]).”‘, ‘”.mysql_real_escape_string($u[’email’]).”‘)”;
mysql_query($q) OR die(mysql_error());
mysql_close($con);
?>
Or: