如何用php更新mysql列?
I'm making a website to connect to MySQL, but I've this function to update a sql column in php:
<?php
function insert_db($table, $id, $value, $id2, $value2){
$con = mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database);
if ($db_found){
mysql_query(" UPDATE ".$table." SET ".$id."='".$value."' WHERE ".$id2." = '".$value2."'); //this doesn't work!
mysql_close($con);
}
else {
print "Database not found!";
mysql_close($con);
}
}
?>
But this function doesn't work! Please help me! And is there a better way of doing this instead of "mysql_quaery()"?
我正在建立一个连接MySQL的网站,但我有这个函数来更新php中的sql列 : p>
&lt;?php
function insert_db($ table,$ id,$ value,$ id2,$ value2){
$ con = mysql_connect($ server, $ user_name,$ password);
$ db_found = mysql_select_db($ database);
if($ db_found){
mysql_query(“UPDATE”。$ table。“SET”。$ id。“='”。$ value。“'WHERE”。$ id2。“='”。$ value2。 “'); //这不起作用!
mysql_close($ con);
}
else {
print”找不到数据库!“;
mysql_close($ con);
}
}
?&gt;
code> pre>
但是这个功能不起作用!请帮助我!有没有更好的方法来代替“mysql_quaery() “? p>
div>
You can kinda answer your own question looking at the StackOverflow syntax highlights. You're missing a closing quote in the SQL statement. As for a better way, I always put my SQL into a variable first. It helps catch these kinds of things. Also, you're not sanitizing anything here in your function. I hope you're doing something elsewhere to prevent SQL injection.
I would NOT create your DB connection inside a function. You're creating a connection, executing ONE query, and then closing it. That's a lot of overhead for one function. I would pass your connection into your function and use it like that.
function insert_db($con, $table, $id, $value, $id2, $value2){
$sql = "UPDATE " . $table . "
SET " . $id . "='" . $value . "'
WHERE " . $id2 . " = '".$value2."'";
mysqli_query($con, $sql);
}
- you are missing a closing quote
"
at the end of yourmysql_query()
. - your variables
$server
,$user_name
,$password
and$database
do not exist inside your function. If you set it outside the function you have to import them withglobal $server, $user_name, $password, $database
before you can use them. - The
mysql_*
functions are becoming deprecated. Don't write new code with them, usemysqli_*
or PDO objects.