Mysql problems - Mysql fetch array and adding to database
Hi I have two mysql problems
a) I'm confused on why this code won't add data to my database:
$con = mysql_connect("localhost","username","password");
mysql_select_db("database", $con);
$sql="INSERT INTO Table ('adder', 'username')
VALUES('$myusername','$username1')";
mysql_query( $sql, $con ) or trigger_error( mysql_error( $con ), E_USER_ERROR );
here is the full error: "you have an error in your SQL syntax; check the manual that corresponds to your M开发者_如何学PythonySQL server version for the right syntax to use near 'Add (username
, name
, number
) VALUES('56', 'Name', 'number')' at line 1"
and before you ask, yes the data is there
b) I'm having problems with mysql_fetch_array
This is the code:
mysql_connect("$host", "$mysqlusername", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$sql = "SELECT * FROM Add WHERE adder=\"$username\"";
$result=mysql_query($sql);
$row=mysql_fetch_array($result);
if (empty($row)) {
echo "$username hasn\'t added anyone";
}
else {
while($row = mysql_fetch_array($result)){
echo "<a href=\"/".$row[username]."><".$row[username]."</a>";
}
}
The error here is: Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in....
And yes the data is there on the database aswell..
Any ideas??
Thanks for the help :) Niall
a) You really should have included the complete error, but I'm fairly certain the syntax error is that you are attempting to put the names of columns in single quotes, which is not allowed. You should instead use backticks (the key to the left of "1" on your keyboard):
$sql="INSERT INTO Table (`adder`, `username`)
VALUES('$myusername','$username1')";
b) Again, please include the full error. That warning occurs when the mysql_query
function fails, since $result
is just the value false instead of a MySQL resource. What is the value of $username
when you get that error? It's likely something is causing the query to be invalid.
You should have said "INSERT INTO TABLE `Add`(`adder`, `username`)"
and Add should be enclosed in backticks (`) because it could be a reserved word, and you shouldn't name a table like that.
精彩评论