PDA

View Full Version : PHP: member function prepare() on a non-object



Sarinja
04 Jun 2011, 11:57 AM
Skill Level: I am somewhere between a novice and a non-expert in PHP.
Desires: Code this for myself.
Problem: Searching by first name, last name or company. When performing search, fails on "prepare." I've done research and it says to check the include for the $con to make sure it is defined. It is. Research says to check that the definition for $con is INSIDE any if loop. It is. Still, script fails.

Examples:

connect.php:


$hostname = "localhost";
$dbuser = "root";
$dbpassword = "";
$database = "idrive";

$con = mysql_connect($hostname, $dbuser, $dbpassword);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}

mysql_select_db($database);


The problem file (slightly edited for length):


<?php
session_start();
if (($_SESSION["is_admin"] = 1) && isset($_POST['field']))
{
include_once('../connect.php');

if ($_POST['field'] == "last_name")
{
$stmt = $con->prepare("SELECT first_name, last_name FROM drivers WHERE last_name=?");
}
elseif ($_POST['field'] == "first_name")
{
$stmt = $con->prepare("SELECT first_name, last_name FROM drivers WHERE first_name=?");
}
elseif ($_POST['field'] == "company")
{
$stmt = $con->prepare("SELECT first_name, last_name FROM drivers WHERE company=?");
}

$stmt->bind_param('s', $_POST['keyword']);
$stmt->execute();
$stmt->store_result();
if ($stmt->num-rows > 0)
{
$stmt->bind_result($first_name, $last_name);
while ($stmt->fetch())
{
echo "<p>".$info['first_name']." ".$info['last_name']."</p>";
}
}
else
{
echo "We have no drivers in the database to view.";
}
}
else
{
echo "Why is it redirecting to the index page?";
}
?>


connect.php works for all other insert, update and query pages of this site. Here, it does not work. I've checked and rechecked it but am willing to admit that maybe I missed something?

Please advise.