Error with WordPress query using $wpdb get_results [duplicate] - php

This question already has answers here:
Fatal error: Uncaught Error: Call to undefined function mysql_connect()
(9 answers)
Closed 4 years ago.
I have added a post in my WordPress database with the title "titleofpost". I try to use in PHP 7 $wpdb get_results, but I get the following error:
Fatal error: Uncaught Error: Call to undefined function mysql_error().
What is wrong? Any help is appreciated.
I use the code below:
global $wpdb;
$leadTitle="titleofpost";
$sql = "SELECT * FROM $wpdb->posts WHERE post_title LIKE '%$leadTitle%'";
$post_if = $wpdb->get_results($sql) or die(mysql_error()); //here dies

thy this
global $wpdb;
$leadTitle="titleofpost";
$sql = "SELECT * FROM $wpdb->posts WHERE post_title LIKE '%$leadTitle%'";
$post_if = $wpdb->get_results($sql) or die(mysqli_error()); //here dies
mysql_* functions have been removed in PHP 7.
You probably have PHP 7 in XAMPP. You now have two alternatives: MySQLi and PDO.
Additionally, here is a nice wiki page about PDO.
Handling errors with PDO
PDO has multiple ways of handling errors.
There are three error modes for PDO.
The first is PDO::ERRMODE_SILENT. This acts much like the mysql_* functions in that after calling a PDO method you need to check PDO::errorCode or PDO::errorInfo to see if it was successful.
The second error mode is PDO::ERRMODE_WARNING. This is much the same except an E_WARNING message is also thrown.
The final error mode is PDO::ERRMODE_EXCEPTION. This one throws a PDOException when an error occurs. This is the method I recommend and will be using it for further examples.
// You can set the error mode using the fourth options parameter on the constructor
$dbh = new PDO($dsn, $user, $password, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
// or you can use the setAttribute method to set the error mode on an existing connection
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//METHOD 2
try {
$dbh = new PDO($dsn, $user, $password, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
} catch (PDOException $e) {
log_error("Failed to connect to database", $e->getMessage(), $e->getCode(), array('exception' => $e));
}
//METHOD 3
try {
$dbh->query("INVALID SQL");
} catch (PDOException $e) {
log_error("Failed to run query", $e->getMessage(), $e->getCode(), array('exception' => $e));
}

According to this, then mysql_error() is deprecated since PHP 5.5.0. Perhaps try error_log() instead (and then look in the php error log).
It's probably this part of your code that causes the error: or die(mysql_error());

Related

Why I'm not able to create a new database in MySQL using PDO? Is it necessary to have a database already present before creating a new one using PDO? [duplicate]

This question already has answers here:
Pdo connection without database name?
(4 answers)
Closed 5 years ago.
I've installed the latest available version of XAMPP Package on my machine running on Windows 10 Home Single Language Edition.
I'm learning PHP and MySQL.
So, first of all in order to create a new database I wrote following code :
<?php
$servername = "localhost";
$username = "root";
$password = "";
try {
$conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "CREATE DATABASE myDBPDO";
// use exec() because no results are returned
$conn->exec($sql);
echo "Database created successfully<br>";
}
catch(PDOException $e) {
echo $sql . "<br>" . $e->getMessage();//Getting 'Notice : Undefined variable : sql' for this line
}
$conn = null;
?>
The database didn't get created and I received following error in output after running above file in a web browser :
Notice: Undefined variable: sql in prog_1.php on line 16
SQLSTATE[HY000] [1049] Unknown database 'mydb'
Can someone please help me by correcting my code, so that I can further start studying the database concepts in actual manner?
Is it necessary to have a database already present when accessing the same using PDO?
P.S. : The database titled 'mydb' is currently not present in MySQL RDBMS.
You're setting the DB name in your DSN connection string, and it looks like mydb doesn't exists.
Just remove that part from the DSN string and try again.
Your $conn = new PDO() fails because there isn't a database called myDB (SQLSTATE[HY000] [1049]). Because that line fails your try catch statement will evaluate to the catch part before it declares the $sql variable. So when you try to access the $sql variable in the catch part it does not exist and will throw an Undefined variable error.
You'll have to move the $sql above the $conn = new PDO() line to fix the undefined variable error. To fix the missing database error you'll have to create a database called myDB.
try {
$sql = "CREATE DATABASE myDBPDO"; // moved it here
$conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
// (...)
} catch(PDOException $e) {
echo $sql . "<br>" . $e->getMessage(); // no undefined variable
}
To connect to the database without selecting a specific database you'll have to change your new PDO() DSN to this:
$conn = new PDO("mysql:host=$servername", $username, $password);
For more information please check this answer.

Unexpected results in PDO Transactions

My problem is kinda simple or it maybe a silly mistake from my side. But I don't know I am just getting unexpected results while using PDO in php.
Code goes like this,
try
{
$_pdo = get_pdo_instance();
$_pdo->beginTransaction();
//query 1
$_pdo->query("some query"); // I have error in query 3 but this query 1 is still executed.
//query 2
$_pdo->query("some query"); // only executes when there are no errors.
//query 3
$_pdo->query("some wrong query"); // let's say I have an error in this sql
$_pdo->commit();
}
catch(Exception $ex)
{
$_pdo->rollback();
}
I am explaining the problem now,
In given example I have some sql error in query 3, so none the queries should run as they all belongs to single transaction.
But in my case query 1 always run even if there are errors in that try block.
Maybe its something simple but I have no idea why this is happening.
Edit:
Function definition,
function get_pdo_instance()
{
try
{
$conn = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME, DB_USER, DB_PASS);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
die('ERROR: ' . $e->getMessage());
}
return $conn;
}
Exceptions are used only for PHP errors. In the code above, you're trying to catch a MySQL error. When PHP reads your try block, everything looks fine, and it therefore has no exception to catch.
You can do error checking with PDO and MySQL like:
if(!$_pdo->query("some query")) {
// Do something
}
See the documentation for PDO Error Handling. You need to turn exception raising on.
try {
$_pdo = get_pdo_instance();
$_pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$_pdo->beginTransaction();
$_pdo->query("some query");
$_pdo->query("some query");
$_pdo->query("some wrong query");
$_pdo->commit();
}
catch(Exception $ex) {
$_pdo->rollback();
}
Here is my solution,
I was catching Exception, instead in this case I had to do catch PDOException.
I guess that solved my problem, but I haven't tested this thing completely. I will post updates if any.

PDO PHP Uncaught exception

I have currently switched to using PDO but am having trouble in handling the exceptions. The connection is correct and queries work perfectly, but when I put in a deliberate mistake the error is not handled as I would expect.
I have changed the name of the table in my query to a table that does not exist. From the code seen below, I would expect the page to print out 'Database Error' but instead get the horrible orange error saying...
'Uncaught exception 'PDOException' with message 'SQLSTATE[42S02]: Base table or view not found: 1146 Table 'test.post' doesn't exist' in C:\wamp\www\website\functions.php on line 46'
Here is the code when connecting the database...
$hostname = 'localhost';
$username = '';
$password = '';
try{
$dbh = new PDO("mysql:host=$hostname;dbname=test", $username, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
print ("Database Error");
}
Am I making a mistake or is there a different way to handle PDO errors?
After connecting, you need to set the error handling:
$dbh = new PDO("mysql:host=$hostname;dbname=test", $username, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
Edit: Note that the exception gets caught at the place it is thrown, so you need to put a try catch block around the query, the one you use when connecting only catches exceptions there (if any, see #Crontab's comment).

Fatal error: Call to a member function bindParam() [duplicate]

This question already has answers here:
Why does this PDO statement silently fail?
(2 answers)
Closed 3 months ago.
I am learning to work with PHP and have a simple problem.
<?php
ini_set('display_errors', 'On');
error_reporting(E_ALL);
$db = new PDO('sqlite:/usr/users2/mieic2009/ei09072/public_html/TP1/Delicious /Database.db');
$a = $_GET['linkRef'];
$b = $_GET['tagToAdd'];
$checkIdLink = $db->prepare('SELECT idLink FROM Links WHERE nome_L = :link_n;');
$checkIdLink->bindParam(':link_n', $a, PDO::PARAM_STR);
$checkIdLink->execute();
$linkID = $checkIdLink->fetch();
$insertLink = $db->prepare('INSERT INTO Tags (nome_T, idLink) VALUES (:addTag, :link_id)');
$insertLink->bindParam(':addTag', $b, PDO::PARAM_STR);
$insertLink->bindParam(':link_id', $linkID, PDO::PARAM_INT);
$insertLink->execute();
echo 'Tag added to the specified link!';
?>
This code should add a Tag to an existing link in a database, however I am getting this error
Fatal error: Call to a member function bindParam() on a non-object in
/usr/users2/mieic2009/ei09072/public_html/TP1/Delicious/addTag.php on
line 9
I have checked over and over and can't seem to find what's wrong with this code, I googled for this error but unfortunately the answer I found weren't helpful enough. Any help would be appreciated, this is probably a simple rookie mistake.
I would check that the $db->prepare() function executed successfully. It will return false if it did not. So you could be trying to call bindParam() on a variable that equals false
http://www.php.net/manual/en/pdo.prepare.php
Also you should put the PDO object declaration in try/catch to be sure it was successful as well, as in the first example on this page:
try {
$dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
Try print_r($db->errorInfo());
Probably the prepare failed so you can't use it.

How to execute mysql script with variables using PHP::PDO?

I am unable to execut long script the pdo throws an exception:
SQLSTATE[HY000]: General error
If I submit script which does not contain variables it runs w/o problem.
The same script runs on phpmyadmin interface.
Here is my code snippet:
try {
$dsn = "mysql:host=" . DB_SERVER . ";dbname=" . DB_DEFAULT;
$db = new PDO($dsn, DB_USER, DB_PASS);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$q = $db->query($query);
if (!$q) {
echo $db->errorInfo();
} else {
$rows = $q->fetchAll(PDO::FETCH_ASSOC);
}
} catch (PDOException $e) {
var_dump($e);
}
Here is some test which does not execute by PDO:
SET #ra_LMC:=80.9;
SELECT #ra_LMC;
How I should execut with pdo the multi line scripts?
Thanks
Arman.
PDO does not allow the execution of multiple statements in one query() request.
But your #ra_LMC variable should be visible in the current connection, so you can put your second line (SELECT) into a new query() call.
To read a whole script, you have to parse the file and run each statement with a call to query().
PDO can only execute one statement at a time. You can ether run the SET and SELECT as 2 separate statements. Or you can set the variable using FROM.
SELECT #ra_LMC FROM (SELECT #ra_LMC:=80.9) q

Categories