简体   繁体   中英

Error with a prepared statement with named placeholders in PHP with mySQL

I am getting these errors on my webpage with this code

Notice: Undefined variable: dbh in /home/danu2_cj3/public_html/lists.php on line 14

Fatal error: Call to a member function prepare() on a non-object in /home/danu2_cj3/public_html/lists.php on line 14

This is the php code i am using and line 14 is the 4th line in this code

<?php
/* Execute a prepared statement by binding PHP variables */
$member = $_SESSION['SESS_MEMBER_ID'];
$sth = $dbh->prepare('SELECT name
    FROM lists
    WHERE member_id = :member_id ');
$sth->bindValue(':member_id', $member, PDO::PARAM_INT);
$sth->execute();
?>

I am trying to show an array of a bunch of rows where one of the fields in those rows is supposed to match the member_id for the person logged into the session

here is the whole code for the page (top.php and bottom.php are just layout pages)

<?php include ('top.php')?>
<h1>My Profile </h1>
<a href="lists.php">My Lists</a> | <a href="logout.php">Logout</a></br>
</br>
Please select list to view/delete
<?php include ("connect.php")?>
<?php
/* Execute a prepared statement by binding PHP variables */
$member = $_SESSION['SESS_MEMBER_ID'];
$sth = $dbh->prepare('SELECT name
    FROM lists
    WHERE member_id = :member_id ');
$sth->bindValue(':member_id', $member, PDO::PARAM_INT);
$sth->execute();
?>

<?php include ('bottom.php')?>

Here is my connect.php file

<?php
$username = "mydb";
$password = "mydb";
$hostname = "host"; 

//connection to the database
$dbh = mysql_connect($hostname, $username, $password) 
 or die("Unable to connect to database");

//select a database to work with
$selected = mysql_select_db("mydb",$dbh) 
  or die("Could not select database");
?>

You should probably add connection to database or check if it is correctly set in connect.php

try 
{
    $dbh = new PDO($dsn, $user, $password);
} 
catch (PDOException $e) 
{
    echo 'Connection failed: ' . $e->getMessage();
}

DOCUMENTATION HERE

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