PDO - Fatal error: Call to a member function prepare() on null - php

I searched similar issues here but could not fix my problem.
I'm trying to add a search function to my website, but for some reason the search results are not displayed. In my error_log I get this error:
PHP Fatal error: Call to a member function prepare() on null in /home/..../search.php on line 9
which is this line:
$query = $pdo->prepare("SELECT * FROM subs WHERE sub_title LIKE '%$search%' LIMIT 0, 10");
Here is my search.php code:
<?php
require_once('includes/config.php');
include("includes/header.php");
// Search from MySQL database table
$search = $_POST['search'];
$query = $pdo->prepare("SELECT * FROM subs WHERE sub_title LIKE '%$search%' LIMIT 0, 10");
$query->bindValue(1, "%$search%", PDO::PARAM_STR);
$query->execute();
// Display search result
if(!$query->rowCount() == 0) {
echo "Search found:<br>";
echo "<table>";
echo "<tr><td>Title</td><td>Category></td><td>Language</td><td>Time</td><td>Download</td></tr>";
while($results = $query->fetch()) {
echo "<tr><td>";
echo $results['sub_title'];
echo "</td><td>";
echo $results['category'];
echo "</td><td>";
echo $results['sub_lang'];
echo "</td><td>";
echo $results['timestamp'];
echo "</td><td>";
echo $results['sub_data'];
echo "</td></tr>";
}
echo "</table>";
} else {
echo "Nothing found";
}
?>
Here is my config.php
<?php
$username = '------';
$password = '------';
try {
$conn = new PDO('mysql:host=localhost;dbname=-----', $username, $password, array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
));
}
catch(PDOException $e) {
echo "Failed to connect to database!" . "<br><br>";
echo $e->getMessage();
}
?>
and here is my search form which is in the header.php
<form class="form-inline" action="search.php" method="POST">
<input class="form-control" name="search" id="search" type="text" placeholder="Search">
</form>

you're using: $query = $pdo->prepare
It should be:
$query = $conn->prepare()
Because I am a lazy coder I made a new class to save a bit of time:
class DBCommon
{
private $conn;
/** #var Common */
public $common;
public function __construct()
{
$database = new Database();
$db = $database->dbConnection();
$this->conn = $db;
}
public function runQuery($sql)
{
$stmt = $this->conn->prepare($sql);
return $stmt;
}
}

Related

Uncaught Error: Call to a member function prepare() (PDO, php)

I'm trying to get data from a table using a public function in PHP, but I get this error:
Uncaught Error: Call to a member function prepare() (PDO, php)
I'm searching for 2, 3 hours... But no result is similar or I did not understand.
<?php
class Config {
public static $SQL;
private function __construct() {
$host_name = "localhost";
$base_user = "root";
$base_pass = "";
$base_name = "home_page";
try {
self::$SQL = new PDO("mysql:host=$host_name;dbname=$base_name", $base_user, $base_pass);
self::$SQL->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
} catch(PDOException $e) {
die("Something went wrong, database connection closed. Reason: ". $e->getMessage());
}
}
public static function GetData($table, $data, $id) {
$wc = Config::$SQL->prepare('SELECT `'.$data.'` FROM `'.$table.'` WHERE `ID` = ?');
$wc->execute(array($id));
$r_data = $wc->fetch();
return $r_data[$data];
}
}
?>
And I use this in my base file:
<h1><?php echo Config::GetData("page_details", "Moto", 1) ?></h1>
The error is from this line:
$wc = self::$SQL->prepare('SELECT `'.$data.'` FROM `'.$table.'` WHERE `ID` = ?');
Is there any particular reason why you want to use STATICeverywhere? The common approach is using public, dynamic methods and properties. I rewrote your sample with suggested naming convention in PHPs OOP, it works:
<?php
class Config
{
/** #var PDO $conn */
private $conn = null;
public function __construct()
{
$host_name = "localhost";
$base_user = "root";
$base_pass = "";
$base_name = "home_page";
try {
$this->conn = new PDO("mysql:host=$host_name;dbname=$base_name", $base_user, $base_pass);
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully"; // <- this is unnnesesary
} catch (PDOException $e) {
die("Something went wrong, database connection closed. Reason: " . $e->getMessage());
}
}
public function findById($table, $data, $id)
{
$stmt = $this->conn->prepare('SELECT `' . $data . '` FROM `' . $table . '` WHERE `uid` = ?');
$stmt->execute(array($id));
return $stmt->fetch(PDO::FETCH_ASSOC);
}
}
// just for test
$cfg = new Config();
print_r($cfg->findById('foo', '*', 1));
or in your case
<?php echo $cfg->findById("page_details", "Moto", 1)['Moto'] ?>

Why function __construct is not working in PHP?

Can someone explain
Why this did not works ?
<?php
class category
{
function __construct()
{
$con = new mysqli("localhost", "root", "", "whatever");
}
function show_all()
{
$sql = "SELECT id_kategori, nama_kategori FROM kategori";
$stmt = $con->prepare($sql);
$stmt->execute();
$stmt->bind_result($id, $cat);
while($stmt->fetch())
{
echo "<td>$id</td>";
echo "<td>$cat</td>";
echo "<td>Update</td>";
echo "<td>Delete</td>";
};
$stmt->close();
}
}
?>
But this works ?
<?php
class category
{
function show_all()
{
$con = new mysqli("localhost", "root", "", "whatever");
$sql = "SELECT id_kategori, nama_kategori FROM kategori";
$stmt = $con->prepare($sql);
$stmt->execute();
$stmt->bind_result($id, $cat);
while($stmt->fetch())
{
echo "<td>$id</td>";
echo "<td>$cat</td>";
echo "<td>Update</td>";
echo "<td>Delete</td>";
};
$stmt->close();
}
}
?>
Without construct, it works, with construct it's don't.
Can somebody show me, tell me, teach me how to include sql connection in a construct the right way ? I'm still new and learning by the way.
This is because of scoping. The $con variable should be defined to be used in the class exclusively rather than just locally inside the __construct.
When you define $con inside the __construct you are scoping this to be locally used inside the function __construct rather than in the class itself
Consider the following code
<?php
class category
{
private $con;
function __construct()
{
$this->con = new mysqli("localhost", "root", "", "whatever");
}
function show_all()
{
$sql = "SELECT id_kategori, nama_kategori FROM kategori";
$stmt = $this->con->prepare($sql);
$stmt->execute();
$stmt->bind_result($id, $cat);
while($stmt->fetch())
{
echo "<td>$id</td>";
echo "<td>$cat</td>";
echo "<td>Update</td>";
echo "<td>Delete</td>";
};
$stmt->close();
}
}
?>
$con is not a variable accessible in the class above: Try this:
<?php
class category
{
private $con = NULL;
function __construct()
{
$this->con = new mysqli("localhost", "root", "", "whatever");
}
function show_all()
{
$sql = "SELECT id_kategori, nama_kategori FROM kategori";
$stmt = $this->con->prepare($sql);
$stmt->execute();
$stmt->bind_result($id, $cat);
while($stmt->fetch())
{
echo "<td>$id</td>";
echo "<td>$cat</td>";
echo "<td>Update</td>";
echo "<td>Delete</td>";
};
$stmt->close();
}
}
?>
and look at documentation here:
http://php.net/manual/en/language.oop5.php
and look up php scope:
http://php.net/manual/en/language.variables.scope.php
Also if you are having questions always add this to your code:
This would have told you the variable is undefined:
error_reporting(E_ALL);
ini_set('display_errors', '1');

get record using if statment & pdo query in function php

i have problem with function pdo, when it will take 1 record from the database, the result is null;
connect.php
<?php
class dbConn{
protected static $db;
private function __construct() {
try {
self::$db = new PDO( 'mysql:host=localhost;dbname=item', 'root', '' );
self::$db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
}
catch (PDOException $e) {
echo "Connection Error " . $e->getMessage();
}
}
public static function getConnection() {
if (!self::$db) {
new dbConn();
}
return self::$db;
}
}
?>
function.php
<?php
include 'connect.php';
class ajax_table {
function detailitem($table){
$db = dbConn::getConnection();
$sql = "select * from ".$table."" or die(mysql_error());
$q = $db->query($sql) or die("failed!");
$res = $q->fetch(PDO::FETCH_ASSOC);
return $res;
//else echo "No records found";
}
}
?>
and to display
displayitem.php
<?php
$url = $_GET['url'];
$url=$url.'.html';
include 'connect.php';
include 'function.php';
$db = dbConn::getConnection();
$obj = new ajax_table();
$records = $obj->detailitem('product WHERE url = "$url"');
if($records){
echo $records['name'];
echo '<br>';
echo $records['type'];
}else{
echo 'no result';
} ?>
database is not empty, but result display
no error, and also does not display anything
If you see correctly on the following line :
$records = $obj->detailitem('product WHERE url = "$url"');
It passes the string as "$url" , not the value of $url variable.
So change it to :
$records = $obj->detailitem('product WHERE url = \''.$url.'\'');

Data does not display from PDO and MySQL

Sorry if the title is vague, was unsure how to word it.
Currently, I'm trying to just do a simple piece of php that runs a query and displays all the data in the database, but no data is displaying the page is just completely blank.
Here is the code:
<?php
$username = "user";
$password = "pass";
try {
$conn = new PDO('mysql:host=localhost;dbname=database', $username, $password);
$stmt = $conn->prepare('SELECT * FROM contacts');
$stmt->execute(array('id' => $id));
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
if ( count($result) ) {
foreach ($result as $query_row)
{
extract($query_row);
echo '<tr>';
echo '<td>'.$fname.'</td>';
echo '<td>'.$lname.'</td>';
echo '<td>'.$title.'</td>';
echo '<td>'.$deparment.'</td>';
echo '<td>'.$email.'</td>';
echo '<td>'.$cell.'</td>';
echo '<td>'.$handle.'</td>';
echo '<td>'.$steam.'</td>';
echo '<td>'.$skype.'</td>';
echo '</tr>';
}
}
} else {
echo "No rows returned.";
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
?>
I've never worked with PDO before so I've been following a guide/reading different SO questions trying to get a grasp on it. One line that I think may be screwing up is this line:
$stmt->execute(array('id' => $id));
I don't understand what that line is doing and if an I can get an explanation that would be great. I believe I understand the logic behind the rest of the code though.
This should solve your problem (it worked on my server).
Plus, I added the <table> and </table> tags and placed in their respective locations.
<?php
$username = "user";
$password = "pass";
try {
// uncomment for testing purposes as noted by jeroen
// $conn = new PDO('mysql:host=localhost;dbname=database', $username, $password, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
$conn = new PDO('mysql:host=localhost;dbname=database', $username, $password);
$stmt = $conn->prepare('SELECT * FROM contacts');
$stmt->execute(array('id' => $id));
// $stmt->execute(); // as noted by Mike Brant
}
catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo "<table>";
if ( count($result) ) {
foreach ($result as $query_row)
{
extract($query_row);
echo '<tr>';
echo '<td>'.$fname.'</td>';
echo '<td>'.$lname.'</td>';
echo '<td>'.$title.'</td>';
echo '<td>'.$deparment.'</td>';
echo '<td>'.$email.'</td>';
echo '<td>'.$cell.'</td>';
echo '<td>'.$handle.'</td>';
echo '<td>'.$steam.'</td>';
echo '<td>'.$skype.'</td>';
echo '</tr>';
}
}
echo "</table>";
?>

Search form with PDO

The below code now works but how can I make it so if no results are found it echos a message instead of blank.
I think I've managed to create a search query for my database. Its only a very basic search but it doesn't seem to work for some reason. Any advice would be appreciated im still new to pdo (very new! be kind!).
Also no user submitted data is inserted into the database so I think i can rule out xss assuming its SQL inject free? Which from what I understand PDO is? plus im using a stand alone DB user with no write access.
Have replace data with xxx for security
file is called search.php
*updated to reflect changes suggested
*2nd update to reflect help provided
*3rd update
<html>
<head>
</head>
<body>
<form name="frmSearch" method="post" action="search.php">
<table width="599" border="1">
<tr>
<th>Keyword
<input name="var1" type="text" id="var1">
<input type="submit" value="Search"></th>
</tr>
</table>
</form>
<?php
$nameofdb = 'xxxxxx';
$dbusername = 'xxxxxxxxxxxxxx';
$dbpassword = 'xxxxxxxxxxxxx';
// Connect to MySQL via PDO
try {
$dbh = new PDO("mysql:dbname=$nameofdb;host=localhost", $dbusername, $dbpassword);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
$var1 = str_replace(array('%','_'),'',$_POST['var1']);
if (!$var1)
{
exit('Invalid form value: '.$var1);
}
$query = "SELECT * FROM xxxxx WHERE xxxxxx LIKE :search OR xxxxx LIKE :search";
$stmt = $dbh->prepare($query);
$stmt->bindValue(':search', '%' . $var1 . '%', PDO::PARAM_INT);
$stmt->execute();
/* Fetch all of the remaining rows in the result set */
print("Fetch all of the remaining rows in the result set:\n");
$result = $stmt->fetchAll();
foreach( $result as $row ) {
echo $row["id"];
echo $row["title"];
}
?>
</body>
</html>
The problem is in the form. the method is GET but in your php you expect $_POST
So this line:
<form name="frmSearch" method="get" action="search.php">
should be:
<form name="frmSearch" method="post" action="search.php">
UPDATE
Change your code to this:
// Connect to MySQL via PDO
$dbh = new PDO("mysql:dbname=$nameofdb;host=localhost", $dbusername, $dbpassword);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$var1 = $_POST['var1'];
$query = "SELECT * FROM xxxxx WHERE xxxx LIKE :search OR xxxxx LIKE :search";
$stmt = $dbh->prepare($query);
$stmt->bindValue(':search', '%' . $var1 . '%',);
$stmt->execute();
To check if there are no line and give a message you can do it like this:
$result = $stmt->fetchAll();
if ($result) {
foreach( $result as $row ) {
echo $row["id"];
echo $row["title"];
}
} else {
echo 'There is nothing to show';
}
i wrote this method and use in every project i working on it . try it :)
public function searchForQueryString($queryString)
{
$query = "SELECT * FROM `xxxx` WHERE (`xxxxxxx` like :queryString or `xxxxx` like :queryString) ";
$sth = $this->prepare($query);
$queryString = '%' . $queryString . '%';
$sth->bindParam('queryString', $queryString, PDO::PARAM_STR);
$sth->execute();
$result = $sth->fetchAll(PDO::FETCH_OBJ);
if(empty($result) or $result == false)
return array();
else
return $result;
}
I modified Amir's code and it works:
protected $pdo;
public function __construct($pdo)
{
$this->pdo = $pdo;
}
public function selectSearch($table, $search)
{
$statement = $this->pdo->prepare("select * from {$table} WHERE post_tags LIKE '%$search%'");
$statement->execute();
$result = $statement->fetchAll();
if(empty($result) or $result == false){
echo "<h1> No Result</h1>";
return array();
} else{
return $result;
}}
if(isset($_POST['submit'])){
$search = $_POST['search'];
$data = $query->selectSearch('posts', $search);
}

Categories