3

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
0xCursor
  • 2,242
  • 4
  • 15
  • 33
stefanosn
  • 3,264
  • 10
  • 53
  • 79

2 Answers2

1

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));
}
Mr-Programs
  • 767
  • 4
  • 20
0

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

Zeth
  • 2,273
  • 4
  • 43
  • 91