如何连接到数据库并从数据库中检索数据?

时间:2017-09-11 14:45:12

标签: php mysql xampp

我正在使用XAMPP。我试图在网页上转储我的db_data。错误消息是“调用未定义函数mysql_connect”。我应该导入一些文件吗?

<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = '';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);

if(! $conn ) {
  die('Could not connect: ' . mysql_error());
}
$sql = 'SELECT *
  FROM uam';

mysql_select_db('demo');
$retval = mysql_query( $sql, $conn );

if(! $retval ) {
  die('Could not get data: ' . mysql_error());
}

while($row = mysql_fetch_array($retval, MYSQL_ASSOC)) {
  echo "Tutorial ID :{$row['id']}  <br> ".
     "username: {$row['username']} <br> ".
     "email: {$row['email']} <br> ".
     "password : {$row['password']} <br> ".
     "--------------------------------<br>";
} 
echo "Fetched data successfully\n";
mysql_close($conn);
?>

或者我应该在代码中进行更改吗?

3 个答案:

答案 0 :(得分:1)

避免使用MySQL函数,现在它们已被折旧,这就是您获得的原因 未定义的错误,它在PHP 7中也不再受支持。

通过将配置更改为下面的代码来使用MySQLI功能

$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = '';
$dbname = 'dbname';

$conn = new mysqli($dbhost , $dbuser, $dbpass,  $dbname);

if(! $conn ) {
  die('Could not connect: ' . mysql_error());
}

答案 1 :(得分:-1)

发生这种情况是因为新版本的PHP不支持mysql_connect 尝试使用mysqli_connect

$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = '';
$dbname = 'demo';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);

答案 2 :(得分:-1)

     <?php
     $dbhost = 'localhost:3306';
     $dbuser = 'root';
     $dbpass = '';
     $dbname = 'TUTORIALS';
     $conn = mysqli_connect($dbhost, $dbuser, $dbpass,$dbname);

     if(! $conn ) {
        die('Could not connect: ' . mysqli_error());
     }
     echo 'Connected successfully<br>';
     $sql = 'SELECT name FROM tutorials_inf';
     $result = mysqli_query($conn, $sql);

     if (mysqli_num_rows($result) > 0) {
        while($row = mysqli_fetch_assoc($result)) {
           echo "Name: " . $row["name"]. "<br>";
        }
     } else {
        echo "0 results";
     }
     mysqli_close($conn);
  ?>