如何在PHP中正确更新MySQL表

时间:2017-03-09 22:43:03

标签: php mysql database

我正在尝试使用PHP更新表中的一行,虽然我这不是我的第一次,但更新功能无效。

这是php代码:

<?php
header("Access-Control-Allow-Origin: *");

$server = "localhost";
$username = "username";
$password = "dbpass";
$database = "dbname";

$con = mysql_connect($server, $username, $password) or die ("Could not connect: " . mysql_error());

mysql_select_db($database, $con);

 $q=mysqli_query("UPDATE  `phonegap_login` SET  `firstname` =  'Alhia' WHERE  `reg_id` =50;");


if($q)
{
echo "success";
}
else
{
echo "failed";
}
?>

顺便说一下,如果你尝试INSERT,它会起作用:

$q=mysql_query("insert into `phonegap_login` (`reg_date`, `firstname`, `lastname`, `email`, `password`) values ('test', 'test', 'test', 'test', 'test')");

我该如何解决?插入是工作,更新行不是。 我正在使用reg_id = 50的行进行测试。

1 个答案:

答案 0 :(得分:1)

你正在混合mysqli_query和mysql_query。只使用mysqli_query。不推荐使用mysql_query

$con = mysqli_connect($server, $username, $password) or die ("Could not connect: " . mysqli_error());

mysqli_select_db($database, $con);

$q=mysqli_query("UPDATE  `phonegap_login` SET  `firstname` =  'Alhia' WHERE  `reg_id` =50;");

或者,面向对象:

$mysqli = new mysqli($server, $username, $password, $database);

if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}

$q = $mysqli->query("UPDATE  `phonegap_login` SET  `firstname` =  'Alhia' WHERE  `reg_id` =50;");

或者,PDO:

$connectionString = 'mysql:host=' . $server . ';dbname='.$database;
try {
    $db = new PDO($connectionString, $user, $pass);
} catch ( PDOException $e) {
    echo "Failed to connect to Database: (" . $e->getCode() . ") " . $e->getMessage();
}
$q = $db->query("UPDATE  `phonegap_login` SET  `firstname` =  'Alhia' WHERE  `reg_id` =50;");