简体   繁体   中英

Retrieving and displaying data from MySql in PhP

I have ran into a problem that says:

Catchable fatal error: Object of class PDOStatement could not be converted to string in F:\\University\\xampp\\htdocs\\database.php on line 36

Connection to a database is successful it is just that I cannot retrieve a data from my database and display it on the page.

Here's my database:

http://screenshot.sh/m1Ol9a8Fp2j3a

And here is my code

    <?php
$conn = new PDO(
    'mysql:host=localhost;dbname=u1358595', 
    'root'
    );
try{
       $conn = new PDO('mysql:host=localhost;dbname=u1358595', 'root');
    echo "Connected successfully"; 
}

catch (PDOException $exception) 
{
    echo "Oh no, there was a problem" . $exception->getMessage();
}
$query = "SELECT * FROM hotel";
$results = $conn->query($query, PDO::FETCH_OBJ);
$hotel = $results->fetch();
echo "<p>".$results."</p>";
$conn=NULL;
?>

You are trying to echo a PDO Object which doesn't work. You are passing the data to $hotel and to show the data you will use hotel.

<?php
$conn = new PDO(
    'mysql:host=localhost;dbname=u1358595', 
    'root'
    );
try{
       $conn = new PDO('mysql:host=localhost;dbname=u1358595', 'root');
    echo "Connected successfully"; 
}

catch (PDOException $exception) 
{
    echo "Oh no, there was a problem" . $exception->getMessage();
}
$query = "SELECT * FROM hotel";
$results = $conn->query($query);
$hotel = $results->fetch();

echo '<pre>';
var_dump($hotel);
echo '</pre>';

$conn=NULL;
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM