Link to home
Start Free TrialLog in
Avatar of doctorbill
doctorbillFlag for United Kingdom of Great Britain and Northern Ireland

asked on

Using $wpdb to execute queries in mysqli

This code is working perfectly (Thanks Julian)
I was just wondering how I could use the $wpdb class as an alternative to run the code



<style>
#myDiv {
  border: thin solid blue;
}
</style>

<script>
function myFunction() {
  document.getElementById("myDiv").style.borderColor = "red";
}
</script>

<?php
$servername = "localhost";
$username = "xxxx";
$password = "xxxx^";
$dbname = "xxxx";
$search= $_POST['xxx'];

//Create Connection
$conn = new mysqli($servername, $username, $password, $dbname);
//Check connection
if ($conn->connect_error) {
   die("Connection failed: " . $conn->connect_error);
}
// $sql = "SELECT id, image FROM MV0vqu9WQ_nextend2_image_storage WHERE( ( id >= 3 ) AND ( id <= 20 ) )";
$sql = "SELECT id, image FROM MV0vqu9WQ_nextend2_image_storage WHERE( id IN (3,4,5) )";
$result = $conn->query($sql);

if($result->num_rows > 0) {
  //output data of each row
  while($row = $result->fetch_assoc())  {
$imagePath = str_replace('$upload$', 'https://www.alibema.com/wp-content/uploads/', $row['image']);
   echo <<< HTML
    <div id="myDiv"><img src="{$imagePath}" ><button type="button" onclick="myFunction()">Change color of the four borders</button></div>
 HTML;
   echo "<hr>";
  echo "Image ID : ". $row['id'];
  }
} else {
   echo "0 results";
}
$conn->close();
?>

Open in new window

Avatar of doctorbill
doctorbill
Flag of United Kingdom of Great Britain and Northern Ireland image

ASKER

Looks like this has sorted it:

<?php
function test_query() {
    // Global in the database
    global $wpdb, $table_prefix;
    // Set up the table name, ensuring you've got the right table prefix
    $table = $table_prefix . 'nextend2_image_storage';
    // For demo purposes, set up a variable
    $imageid = 1;
    // For TESTING ONLY, turn on errors to be sure you see if something goes wrong
    $wpdb->show_errors();
    // Use $wpdb->prepare when you need to accept arguments
    // Assign the query to a string so you can output it for testing
    $query = $wpdb->prepare( "SELECT id, image FROM {$table} WHERE id = %d", $imageid );
    // For TESTING ONLY, output the $query so you can inspect for problems
    var_dump( $query );
    // Get the results
    $results = $wpdb->get_results( $query );
    // Output the results
    foreach( $results AS $row ) {
        // Don't use ARRAY_A - just access as an object
        echo '<p>' . $row->id . '</p>';
        echo '<p>' . $row->image . '</p>';
    }
}

// Run your function
test_query();

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of doctorbill
doctorbill
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial