WordPress SQL Statements

In this post you will learn about the ways to correctly run SQL statements through WordPress.

 

Using Arrays

Below you can see an example of how to run SQL statements by using arrays.

function updateFunction_byArrowDesign_usingArrays(){

global $wpdb;

$tblFullName = ‘yourTableName’;

$fieldNameAndValsArray = array(
'YourColumnName1' => ‘Your New Value’,
'YourColumnName2' => ‘Your New Value 2’
);

$idToUpdateAsArray = array(
'AutoNumber' => 4 
);
//example, if the column name of your unique id is AutoNumber and the id you wish to update is 4.

$query = $wpdb->update($tblFullName, $fieldNameAndValsArray, $idToUpdate);
if($query){
//do something

}
else{
//do something else
}//end else

}//end function

Using Prepare

You can also use prepare to run SQL statements in WordPress.

function updateFunction_byArrowDesign_usingPrepare(){

$autoID_string = ‘2,3,4’; //used to pass ids which we will use the ‘IN’ operator

//example to concatenate current value and a value you choose
$execut= $wpdb->query( $wpdb->prepare( "UPDATE yourTableName SET yourTableName.yourColName = CONCAT(yourTableName.yourColName, 'valueToAdd'), yourTableName.yourColName2 = 'Some Text' WHERE yourTableName.YourUniqueId_colName IN (" .$autoID_string . ")" ) );

if($execut==true)
{
//do something 
}//end if
Else
{
//do something else
}//end else

}//end function

Conclusion

We hope this WordPress SQL Statements was helpful and you now know more about SQL and it helps you with your own WordPress website! You can find more articles here:

 

Read another SQL post : ‘SQL for WordPress

 

Arrow Design, based in Dublin, Ireland, provides quality website design services in Dublin and beyond at affordable prices. If you would like help with implementing the above code, or any wordpress website development project, contact us. We love website design and it shows! We provide custom wordpress plugin development, website design training and lots more.

We do it all, so you don’t have to!

Related Posts

Woocommerce Account Page Hook Guide

In this article you will find a visual hook guide for the Woocommerce Account Pages, like the Login/Register page, the Downloads page or the Orders page.

Woocommerce PHP – Product Categories by Product ID

Woocommerce Single Product Page Hook Guide

In this article you will find a visual hook guide for the Woocommerce Single Product Page. This should help you to quickly and easily find the hook positions on the page.

Woocommerce PHP – Product Categories by Product ID

Woocommerce PHP – Product Categories by Product ID

In this tutorial you will learn how to check if a product is assigned to a tag, a category or a custom taxonomy. You can check if a product is is on the shop page, in the cart, in an order & more.

…We do more, so you can do less 🙂

 

Leave a message and we will be straight back to you!

Pin It on Pinterest

Share This