Selecting data from SQL Server Using PHP

。_饼干妹妹 提交于 2021-02-04 21:01:34

问题


I am trying to select data from a local database on my PC using PHP but i am getting this error when i run 127.0.0.1/test.php which is what the file is called.

error:

Fatal error: Uncaught Error: Call to undefined function mysql_connect() in 
C:\xampp\htdocs\test.php:11 Stack trace: #0 {main} thrown in 
C:\xampp\htdocs\test.php on line 11

Here is my PHP script:

  <?php
    $servername = "Windows local servername";
    $username = "Windows username";
    $password = "windows password";
$dbname = "dbname";

// Create connection
$conn = mysql_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn){
    die('error connecting to database');
}else{
    mysql_select_db(dbname, $conn);
}

$sql = "SELECT UserId, UserEmail, UserPassword FROM User";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        echo "id: " . $row["UserId"]. " - UserEmail: " . $row["UserEmail"]. " " . $row["UserPassword"]. "<br>";
    }
} else {
    echo "0 results";
}
$conn->close();
?>

I have looked around online but i cant figure out what is wrong here. I can run a hello world php script and it works so i am assuming its a connection issue with the database but what have i missed here? Thanks

EXTRA:

i have:


回答1:


Try to run

phpinfo() 

And look for the mysql extensions, in ubuntu you can install them by typing

sudo apt-get install php-pdo-mysql

Anyway the instruction you're trying to use was deprecated in HP 5.5.0 and deleted in PHP 7.0.0 so may be this is why its missing... depending on you PHP version, you could try with the mysqli extension instead like:

$mysqli = mysqli_connect("example.com", "user", "password", "database");
$res = mysqli_query($mysqli, "SELECT 'Please, do not use ' AS _msg FROM DUAL");
$row = mysqli_fetch_assoc($res);
echo $row['_msg'];

You could get more info on the actual way of performing this with PHP7 at http://php.net/manual/en/mysqli.quickstart.dual-interface.php for instance




回答2:


From the docs

This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used.

You'll probably want to use Microsoft's drivers for PHP for SQL Server rather than the ODBC driver in PDO.




回答3:


In place of $conn = mysql_connect($servername, $username, $password, $dbname); use $connectioninfo=array("Database"=>"dbname", "UID"=>"userid", "PWD"=>"password", );

$con = sqlsrv_connect($server,$connectioninfo);



来源:https://stackoverflow.com/questions/51812304/selecting-data-from-sql-server-using-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!