开发者

output all data from db to a php page

I'm a real beginner with PHP & mysql. Just for studying and for a simple example at sc开发者_如何学JAVAhool I would like to work this simple query and possibly output all the rows (or maybe even one) to a very basic output on a php page:

<?php
$user= "root";
$host="localhost";
$password="";
$database = "PetCatalog";
$cxn = mysqli_connect($host,$user,$password,$database)
or die ("couldn’t connect to server");
$query = "SELECT * FROM Pet";
$result = mysql_query($cxn,$query) or die ("Couldn’t execute query.");
$row = mysqli_fetch_assoc($result);
echo "$result";
?>

this is the error message i've been getting:

Warning: mysql_query() expects parameter 1 to be string, object given in C:\xampplite\htdocs\myblog\query.php on line 18
Couldn’t execute query.

What should I do? Thanks!


mysql_query($query,$cxn) 

in place of

mysql_query($cxn,$query) 


You may want to also consider using the Object Oriented interface:

# create a new connection object
$DBH = new mysqli($host, $user, $pass, $dbname);

# execute your query 
$result =$DBH->query('SELECT * FROM Pet');

# iterate over the results
while($row = $result->fetch_assoc()) {
       print_r($row);
}


PHP has been around for a long time. Every few years, someone comes up with a new, preferred way of connecting to databases. In the early days, to connect to and query a MySQL database you used the MySQL database. Later on, a new MySQL library was created, Mysqli (the i stands for improved).

You're making your connection with the mysqli_connect function, a Mysqli function. However, you're then trying to use a function form the original library, mysql_query (notice there's no i). You want mysqli_query.

If you look at that page, you'll see this, listing the procedural style

mixed mysqli_query  (  mysqli $link  ,  string $query  [,  int $resultmode  ] )

This line is telling you that the function wants the database link first, and the query second. So, you have your parameters in the right order above, you're just using the wrong function.


<?php
$user= "root";
$host="localhost";
$password="";
$database = "PetCatalog";
$cxn = mysqli_connect($host,$user,$password,$database)
or die ("couldn’t connect to server");
$query = "SELECT * FROM Pet";
$result = mysql_query($query) or die ("Couldn’t execute query.");
while($row = mysqli_fetch_array($result)) {
          print_r($row);
}
?>

This should solve your problem

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜