mysql_connect不再工作,如何修复mysqli?

时间:2018-06-18 13:42:03

标签: php mysql

<?php

$getdatum = $_POST["notdienstdatum"];

mysql_connect("127.0.0.3","db","password");
mysql_select_db("db");

$dbselect = "SELECT apotheke FROM wp_notdienst WHERE datum = '$getdatum'";
$dbquery = mysql_query($dbselect);

$dbcount = mysql_num_rows($dbquery);

$dboutput = mysql_fetch_assoc($dbquery);
echo utf8_encode($dboutput["apotheke"]);

?>

如何更新代码以便使用较新版本的PHP?我已经尝试通过

建立新连接
$conn = new mysqli($servername, $username, $password);

但我有问题让mysql_query工作..

感谢您帮助我

3 个答案:

答案 0 :(得分:2)

你可以使用mysqli:

这样连接
define('DB_SERVER', 'domain');
define('DB_USER', 'db_user');
define('DB_PASS', 'password');
define('DB_NAME', 'db_name');
$mysqli = new mysqli(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
if($mysqli->connect_errno) {
  die('Database is down, try again in a minute.');  
}

如果连接失败,if语句会显示一条消息。

示例SELECT语句:

$qry = "SELECT name FROM people WHERE id = ?";
$stmt = $mysqli->prepare($qry);
$stmt->bind_param('s', $id_to_retreive);
$stmt->execute();
$result = $stmt->get_result();
while($row = mysqli_fetch_assoc($result)) {
    $row['name'] // the retreived field
}

准备好的陈述的优点在于它比记住逃避字符串更安全 - 请参阅here

答案 1 :(得分:1)

阅读MySQLi documentation并用适当的MySQLi函数替换MySQL函数。

对于代码,您提供了这是需要更改的方式

$con = mysqli_connect("127.0.0.3","username","password", "db_name");

$getdatum = mysqli_real_escape_string($con, $_POST["notdienstdatum"]);

$dbselect = "SELECT apotheke FROM wp_notdienst WHERE datum = '$getdatum'";
$dbquery = mysqli_query($con, $dbselect);

$dbcount = mysqli_num_rows($dbquery);

if($dbcount > 0)
{
    while($row =  mysqli_fetch_assoc($dbquery))
    {
        echo utf8_encode($row["apotheke"]);
    }
}
else
{
echo "0 rows!";
}

但考虑使用PDO代替它,它更安全!

答案 2 :(得分:0)

请查看php mysql_connect文档 http://php.net/manual/en/function.mysql-connect.php

它已在PHP 5.5.0中弃用,并在PHP 7.0.0中被删除。

也许你的php版本更高。

所以请使用mysqli_connect

$link = mysqli_connect("127.0.0.1", "my_user", "my_password", "my_db");