0

I am working on a PHP backend script for my WordPress site to update a database table when a user submits a form. It is throwing an error at the line with $wpdb->prepare.

Fatal error: Uncaught Error: Call to a member function prepare() on null

Here is my current test script.

<?php

if (isset($_POST['SaveNewCourse'])){
    $courses_query = "INSERT INTO SC_COURSES (COURSE_NAME, COURSE_DESC, ACTIVE, ADDED_BY_USER_ID, ADDED_DTG) VALUES ( %s, %s, 1, %d, %s )";

    $newcoursename = $_POST['AddCourseCourseName'];
    $newcoursedesc = $_POST['AddCourseCourseDesc']; 
    $newcourseuserid = $_POST['AddCourseUserID'];
    $newcoursedtg = $_POST['AddCourseDTG'];

    global $wpdb;
    $prepared_query_courses = $wpdb->prepare( $courses_query, $newcoursename, $newcoursedesc, $newcourseuserid, $newcoursedtg );

    echo $prepared_query_courses;

}

?>

I realize it is not actually trying to update the database right now, I am just trying to test it out before I make it go live, so I wanted to see what the prepared INSERT statement looked like. What do I need to change to prevent the error?

SandPiper
  • 2,816
  • 5
  • 30
  • 52
  • Wrap the prepare in a `$wpdb->query` - also var_dump `$wpdb` to see if its ok – treyBake Oct 14 '18 at 16:11
  • 2
    It looks like you are running a stand alone script, i.e. the worpdress files are not included. try https://stackoverflow.com/questions/5306612/using-wpdb-in-standalone-script – Gavin Simpson Oct 14 '18 at 16:12
  • I added: `$path = $_SERVER['DOCUMENT_ROOT'];` `include_once $path . '/wp-config.php';` `include_once $path . '/wp-load.php';` `include_once $path . '/wp-includes/wp-db.php';` `include_once $path . '/wp-includes/pluggable.php';` to the top, but that's just kicking back even more errors because the PHP script is located in my child theme folder. How do I point it to the right place? – SandPiper Oct 14 '18 at 16:27
  • something along the lines of include_once("../../../wp-load.php' ); wp-load is in the root wordpress folder, so three steps back should work from a child theme. – Gavin Simpson Oct 14 '18 at 16:33
  • If your wordpress install is in a subfolder, you must add it after server[document_root], if that makes sense. – Gavin Simpson Oct 14 '18 at 16:34
  • 1
    Ok, that solved my problem. Thank you! – SandPiper Oct 14 '18 at 16:44

0 Answers0