Counting rows in mySQL database using PDO & PHP - php

I know this question has been answered before, but I actually have an error when I use an the following:
try {
$conn = new PDO('mysql:host=localhost;dbname=open', $user, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
$count=$conn->prepare(" SELECT * FROM `dictionary` WHERE word = ':input' ");
$count->bindParam(":input",$input);
$count->execute();
$no=$count->rowCount();
if( $no > 0 ){
echo "no";
}
Which gives me the error:
Fatal error: Call to a member function prepare() on a non-object in... on line 18
I don't see where the error is, particularly because I based this code off an accepted answer.

try replace this
word = ':input'
by
word = :input

Related

Fatal error: Uncaught Error: Object of class PDOStatement could not be converted to string

if (isset($_POST['pf1'])) {
try {
$stmt = $conn->prepare( "UPDATE t1
SET pref1 = :pf1,
WHERE id = 1 ");
$stmt->bindParam(':pf1', $_POST['pf1']);
$stmt->execute();
echo "pf1";
} catch(PDOException $e) {
echo $stmt . "<br>" . $e->getMessage();
}
}
It gives error:
Fatal error: Uncaught Error: Object of class PDOStatement could not be converted to string
I want to update data to db. But it gives me error of PDO exception.
I don't know what's the issue is any help is appreciated.
I think this could be because it ends up in your catch.
It then says echo $stmt . "<br>" . $e->getMessage();.
You are trying to echo $stmt (being an Object of class PDOStatement). You cannot echo an Object.
Try var_dump($stmt); to check if the above is true. If that's the case, simply remove the echo of $stmt and you should be good.

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()

Fatal error: Call to a member function prepare() on a non-object in /Applications/XAMPP/xamppfiles/htdocs/connect/includes/functions.php [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Scope error - Call to a member function prepare() on a non-object
I wrote this code about 2 or 3 months ago on my windows PC. It runs.. Now I downloaded xampp on my Mac and I get the following error:
Fatal error: Call to a member function prepare() on a non-object in /Applications/XAMPP/xamppfiles/htdocs/connect/includes/functions.php on line 39
// Connect to the database
try {
$pdo = new PDO('mysql:host=localhost;dbname=mo33', 'root', '');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}catch (PDOException $e){
$error = "There was an issue connecting to the database: \n" + $e->getMessage();
include 'html/error.html.php';
exit();
}
function renderTimeline(){
try {
$sql = 'SELECT user_publications.id, user.firstname, user.lastname, user.thumbnail, article, date_added
FROM user_publications INNER JOIN user
ON user_id = user.id
ORDER BY user_publications.id DESC';
$s = $pdo->prepare($sql); ---------------------------LINE 39---------------
$result = $pdo->query($sql);
}catch(PDOException $e){
$output = 'There was an error while finding posts in the database..: ' . $e->getMessage();
include 'html/error.html.php';
exit();
}
while($row = $result->fetch()) {
$user_publications[] = array(
'id'=>$row['id'],
'name'=>$row['firstname'] + " " + $row['lastname'],
'thumbnail'=>$row['thumbnail'],
'article'=>$row['article'],
'date'=>$row['date_added']);
}
foreach ($user_publications as $post) {
renderUserPublication($post['id'], $post['name'], $post['thumbnail'], $post['article'], $post['date']);
}
return;
}
pass the object too your function like so
function renderTimeline($pdo){
and in your code
$pdo = new pdo();
renderTimeline($pdo);

PDO::FETCH_OBJECT error

I have a problem with the PDO::FETCH_OBJECT argument. I want to fetch an object and not an array, but when I try this:
try {
$conn = new PDO('mysql:host=localhost;dbname=washngo', $config['DB_USERNAME'], $config['DB_PASSWORD']);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); //Fetch errors by default ( display any errors during the development process )
$stmt = $conn->prepare('SELECT * FROM news');
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_OBJECT)) { //By default, it fetch an array. The "PDO::FETCH_OBJECT" argument allows us to fetch an object
print_r($row);
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
I get
Fatal error: Undefined class constant 'FETCH_OBJECT' in index.php on line 18.
When I try to let the fetch() by default (without PDO::FETCH_OBJECT()), it works fine.
Correct is not PDO::FETCH_OBJECT but PDO::FETCH_OBJ

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.

Categories