使用PHP连接MYSQL

时间:2017-02-13 01:13:03

标签: php mysql connection

我无法运行我的代码。

它说:

  

语法错误,意外'$ query'(T_VARIABLE)。

代码

<?php 
$hostname="localhost";
$username="";
$password="";
$dbname="thesis";
$usertable="product";
$yourfield="product_id";

msql_connect($hostname,$username,$password) or die ("<html><script>
language='Javascript'>alert('Unable to connect to     database!.'),history.go(-1)</script></html>")

$query = "SELECT * FROM $usertable";
$result = mysql_query($query);

if($result)
{
  while ($row = mysql_fetch_array($result))
  {
     $name = $row["$yourfield"];
     echo "Name: ".$name."</br>";
  }
}
?>

2 个答案:

答案 0 :(得分:0)

   msql_connect($hostname,$username,$password) or die ("<html><script>
    language='Javascript'>alert('Unable to connect to     database!.'),history.go(-1)</script></html>")

应该有分号。

替换为:

  msql_connect($hostname,$username,$password) or die ("<html><script>
    language='Javascript'>alert('Unable to connect to     database!.'),history.go(-1)</script></html>");

答案 1 :(得分:0)

<?php
$hostname = "localhost";
$username = "";
$password = "";
$dbname = "thesis";
$usertable = "product";
$yourfield = "product_id";
$mysqli = new mysqli($hostname, $username, $password, $dbname);

/* check connection */
if ($mysqli->connect_errno) {
    printf("Connect failed: %s\n", $mysqli->connect_error);
    exit();
}

/* Select queries return a resultset */
if ($result = $mysqli->query("SELECT * FROM $usertable")) {
    while ($row = mysql_fetch_array($result))
  {
     $name = $row["$yourfield"];
     echo "Name: ".$name."</br>";
  }

    /* free result set */
    $result->close();
}

$mysqli->close();

http://php.net/manual/en/mysqli.query.php