PDO statement error php mysql [duplicate] - php

This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 7 years ago.
i am trying to fetch product list from mysql table. I am trying the following code but it is not working. Any suggestions please.
Fatal error: Call to undefined method mysqli_stmt::rowCount()
Code
$query = "SELECT id, name, price FROM female_products ORDER BY name";
$stmt = $con->prepare( $query );
$stmt->execute();
$num = $stmt->rowCount();
if($num>0)
{
//my work here
}
Config.php
$db_username = 'root';
$db_password = '';
$db_name = 'ecommerce';
$db_host = 'localhost';
try {
$con = new mysqli($db_host, $db_username, $db_password,$db_name);
}catch(PDOException $exception){
echo "Connection error: " . $exception->getMessage();
}

Assuming you want a real PDO solution, rather then a mysqli one:
try {
$aOptions = array( PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC);
// play around with options
$dbh = new PDO('mysql:host='.DBHOST.';dbname='.DBNAME.';charset=utf8', ''.DBUSER.'', ''.DBPWD.'',$aOptions);
}
catch(PDOException $e) {
echo $e->getMessage();
// do something smarter then just echo error!
}
$sql = "SELECT id, name, price FROM female_products ORDER BY name";
$stmt = $dbh->query($sql);
$aArray = $stmt->fetchAll();
if(count($aArray) > 0){
// do something
}
else{
// empty result
}
I personally think PDO is a much easier style then mysqli.
Options: you certainly gonna play with it soon, so it is handy to use an array for it.
You have used prepare,but yo do not make use of a prepared statement yet??
If this code works, try to find out hoe prepared statements work: one of the best defenses against SQL attacks!!
For configuration i used constants, so you need to define theme in your config. Constants, because they will never change during execution of your script!

Related

Function fetch() when I want to check [duplicate]

This question already has answers here:
Why does this PDO statement silently fail?
(2 answers)
Closed 2 years ago.
I receive this error:
Fatal error: Call to a member function fetch() on boolean in
C:\xampp\htdocs\repo\generator\model\database.php on line 34
When I run this code:
class database
{
private $user = 'root';
private $pass = '';
public $pdo;
public function connect() {
try {
$this->pdo = new PDO('mysql:host=localhost; dbname=generatordatabase', $this->user, $this->pass);
echo 'Połączenie nawiązane!';
}
catch(PDOException $e) {
echo 'Połączenie nie mogło zostać utworzone: ' . $e->getMessage();
}
}
public function createTable() {
$q = $this->pdo -> query('SELECT * FROM article');
while($row = $q->fetch()) {
echo $row['id'].' ';
}
$q->closeCursor();
}
}
?>
As per the PHP manual for PDO::query
PDO::query() returns a PDOStatement object, or FALSE on failure.
It looks like your query is failing (on line 33) and thus returning a BOOLEAN (false), likely because at that point in execution, PDO has not connected to a database that contains a table called article. In the connect() method I see that it tries to connect to a db called 'generatordatabase'; ensure this connection is being made prior to calling createTable(), otherwise ensure that it contains a table called 'article'.
I would recommend adding some more code examples, for instance the code that calls this class/method before the error is triggered.
Some error handling will help you avoid issues like this:
$q = $this->pdo->query('SELECT * FROM article');
//error case
if(!$q)
{
die("Execute query error, because: ". print_r($this->pdo->errorInfo(),true) );
}
//success case
else{
//continue flow
}
I'm not sure wheatear this is exactly the error I struggled with, but my error was due to my $con variable, I used a single $con for 2 SQL statements, for example:
$con = new mysqli($host,$username,$password,$database);
$sql = "SELECT name FROM users WHERE email = '$email'";
$stm = $con->prepare($sql);
$stm->execute();
and
$sql1 = "INSERT INTO posts
VALUES('$email','$body')";
$stm1 = $con->prepare($sql1);
if ($stm1->execute()) {
I should have done:
$con = new mysqli($host,$username,$password,$database);
$sql = "SELECT name FROM users WHERE email = '$email'";
$stm = $con->prepare($sql);
$stm->execute();
and
$con1 = new mysqli($host,$username,$password,$database);
$sql1 = "INSERT INTO posts
VALUES('$email','$body')";
$stm1 = $con1->prepare($sql1);
$stm1->execute()

Call to a member function query() only on localhost [duplicate]

This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
Call to a member function on a non-object [duplicate]
(8 answers)
Closed 8 years ago.
I'm getting this error only when I try connect to my localhost, but if i test on my web host, everything is running perfect.
The error i get is pointing on my $query = $dbh->query("SELECT * FROM video");
<?php
$query = $dbh->query("SELECT video_img FROM video");
while($r = $query->fetch(PDO::FETCH_OBJ)) {
echo $r->video_title;
}
?>
db connection
<?php
$user = "root";
$pass = "";
try {
$dbh = new PDO('mysql:host=localhost;dbname=streaming', $user, $pass);
foreach($dbh->query('SELECT * from video') as $row) {
//print_r($row);
}
$dbh = null;
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
?>
Any tips :)?
Thanks
Looking at the codes you posted, $dbh doesn't make sense since no PDO connection has be initialized:
Second, you are selecting column video_img, then accessing/fetching $r->video_title. This doesn't make sense also:
$dbh = new PDO('mysql:host=localhost;dbname=DATABASE_NAME', 'username', 'password');
$query = $dbh->query("SELECT video_img FROM video");
while($r = $query->fetch(PDO::FETCH_OBJ)) {
echo $r->video_img;
}

MySQL MATCH, AGAINST not works with PDO

I have this simple code to make search results depending on relevance:
$stmt = $db->query('SELECT * FROM `apps` WHERE MATCH(appName, appSeller) AGAINST("angry")');
$appCount = $stmt->rowCount();
echo $appCount;
And it's not showing any results!
Thanks in advance for your help,
Marcell
Stackoverflow's usability is below zero.
Because there is no way to make a half-screen banner shown to everyone posting a question under PDO tag:
Enable ERRMODE_EXCEPTION when connecting to PDO before asking a question.
Because it is pointless to ask without an error message, yet error message most likely will render a question unnecessary.
$dsn = 'mysql:host=localhost;dbname=test;charset=utf8';
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
);
$pdo = new PDO($dsn,'root','', $opt);
Try
'SELECT * FROM `apps` WHERE MATCH(appName, appSeller) AGAINST("angry")'
in phpmyadmin and see if it really returns anything.
try this
<?php
// Connection data (server_address, database, name, poassword)
$hostdb = 'localhost';
$namedb = 'tests';
$userdb = 'username';
$passdb = 'password';
try {
// Connect and create the PDO object
$db = new PDO("mysql:host=$hostdb; dbname=$namedb", $userdb, $passdb);
$db->exec("SET CHARACTER SET utf8"); // Sets encoding UTF-8
// Define and perform the SQL SELECT query
$sql = "SELECT * FROM `apps` WHERE MATCH(appName, appSeller) AGAINST("angry")";
$stmt = $db->query($sql);
// If the SQL query is succesfully performed ($stmt not false)
if($stmt !== false) {
$cols = $stmt->columnCount(); // Number of returned columns
echo 'Number of returned columns: '. $cols. '<br />';
// Parse the result set
foreach($stmt as $row) {
echo $row['id']. ' - '. $row['name']. ' - '. $row['category']. ' - '. $row['link']. '<br />';
}
}
$db = null; // Disconnect
}
print_r($sth->errorInfo());
}
?>
enclose your code in try and catch blocks, then you should get a clue to where your going wrong in your SQL syntax:
try {
// your code
} catch ( PDOException £e ) {
echo $e->getMessage();
exit();
}

PDO Query Fatal error: Call to a member function setFetchMode() on a non-object [duplicate]

This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
Closed 8 years ago.
I have been trying to pull all infomation where $user is equal to subscriberID in my sql database. I am using the PDO method of inserting data and wish to use the query function also.
i am getting the following error message back from my try condition.
Fatal error: Call to a member function setFetchMode() on a non-object
I have considered maybe the problem has been caused by the method i use to pull the data as im fairly new to PDO.(i include a top.php that establishes the link to the database)
Thank you for your suggestions
<?php
include "top.php";
try{
$user = $_SESSION['login'];
echo "Welcome <strong>$user</strong> to your saved holidays";
//$getSavedHolidays = $db->query("SELECT * FROM saved_holidays WHERE subscriberID='$user'");
//preparing a PDO statment for accessing saved holidays when the logged in user matchs the subscriberID
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$getSavedHolidays = $db->prepare("SELECT * FROM saved_holidays WHERE subscriberID=:user");
//uses a bind valu as this makes the statment more secure
$getSavedHolidays->bindValue(":user", $_SESSION['login']);
$getsavedHolidays->setFetchMode(PDO::FETCH_ASSOC);
$getSavedHolidays->execute();
foreach ($Result as $row)
{
echo "<p><a href'".$row['link']."'>".$row['title']."</a><br \>" .
$row['description'] . "<br \>" .
$row['pubDate'] ."<br \></p>";
}
}
catch (PDOException $e)
{
print_r($e->errorInfo);
die();
}
?>
You should be preparing your statement. It has a nice added bonus of being more secure, plus it will solve your problem.
$user = $_SESSION['login'];
try {
$db = new PDO("mysql:host=localhost;dbname=database", "user", "pass");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$getSavedHolidays = $db->prepare("SELECT * FROM saved_holidays WHERE subscriberID=:user");
$getSavedHolidays->bindValue(":user", $_SESSION['login']);
$getSavedHolidays->setFetchMode(PDO::FETCH_ASSOC);
$getSavedHolidays->execute();
$Result = $getSavedHolidays->fetchAll();
foreach ($Result as $row) {/*...*/}
}
catch (PDOException $e) {
print_r($e->errorInfo);
die();
}
EDIT
You have an error in the code you've pasted above:
$$getSavedHolidays = $db->prepare("SELECT * FROM saved_holidays WHERE subscriberID=:user");
Should be
$getSavedHolidays = $db->prepare("SELECT * FROM saved_holidays WHERE subscriberID=:user");
there is explicit syntax error. mussing closing single quote:
$getSavedHolidays = $db->query("SELECT * FROM saved_holidays WHERE subscriberID='$user'");
and by the way, since you're using PDO it's more safe to use bindValue function to pass values to SQL request.

How to handle PDO exceptions [duplicate]

This question already has answers here:
Why does this PDO statement silently fail?
(2 answers)
Closed 7 years ago.
I'm trying to work with PDO class on php but I have some trouble to find the right way to handle errors, I've wrote this code:
<?php
// $connection alreay created on a class which works with similar UPDATE statements
// I've simply added here trim() and PDO::PARAM... data type
$id = 33;
$name = "Mario Bros.";
$url = "http://nintendo.com";
$country = "jp";
try {
$sql = "UPDATE table_users SET name = :name, url = :url, country = :country WHERE user_id = :user_id";
$statement = $connection->prepare ($sql);
$statement->bindParam (':user_id', trim($id), PDO::PARAM_INT);
$statement->bindParam (':name', trim($name), PDO::PARAM_STR);
$statement->bindParam (':url', trim($url), PDO::PARAM_STR);
$statement->bindParam (':country', trim($country), PDO::PARAM_STR, 2);
$status = $statement->execute ();
} catch (PDOException $e) {
print $e->getMessage ();
}
print $status; // it returns a null value, and no errors are reported
?>
this portion of code doesn't report errors, but it simply doesn't work, the var $status at the bottom, return a null value.
can someone help me to find where I'm wrong?
PDO won't throw exceptions unless you tell it to. Have you run:
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
on the PDO object?
You can add the attribute one time while you connect you mysql.
function connect($dsn, $user, $password){
try {
$dbh = new PDO($dsn, $user, $password, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING));
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
exit;
}
}
Thanks

Categories