PHP class providing empty object - php

My index.php page had this code that defaults the user to the homepage.
<?php
require_once ( "config.php" );
$action = isset( $_GET['action'] ) ? $_GET['action'] : "";
switch ( $action ) {
case 'seeAll':
seeAll();
break;
case 'viewResource':
viewResource();
break;
default:
homepage();
}
function homepage() {
$results = array();
$learnData = Resource::getHomePageTiles( 'learn' );
$practiceData = Resource::getHomePageTiles( 'practice' );
$elseData = Resource::getHomePageTiles( 'else' );
$results['learn'] = $learnData;
$results['practice'] = $practiceData;
$results['else'] = $elseData;
$results['pageTitle'] = "Couch To Code";
require_once ( "templates/homepage.php" );
}
Which calls the getHomePageTiles method of my Resource class.
Here is the code for the Resource class and getHomePageTiles method.
class Resource {
public $id = null;
public $title = null;
public $summary= null;
public $url = null;
public $content = null;
public $category = null;
public $is_free = null; //????
public $is_featured = null;
public $is_favorite = null;
public $date_created = null;
public function __construct( $data ) {
if ( isset ( $data['id'] ) ) $this->id = (int) $data['id'];
if ( isset ( $data['title'] ) ) $this->title = $data['title'];
if ( isset ( $data['summary'] ) ) $this->summary = $data['summary'];
if ( isset ( $data['url'] ) ) $this->url = $data['url'];
if ( isset ( $data['content'] ) ) $this->content = $data['content'];
if ( isset ( $data['category'] ) ) $this->category = $data['category'];
if ( isset ( $data['is_free'] ) ) $this->is_free = (int) $data['is_free'];
if ( isset ( $data['is_featured'] ) ) $this->is_featured = (int) $data['is_featured'];
if ( isset ( $data['is_favorite'] ) ) $this->is_favorite = (int) $data['is_favorite'];
if ( isset ( $data['date_created'] ) ) $this->date_created = date("Y-m-d H:i:s");
}
public static function getHomePageTiles( $type ) {
global $DB_HOST;
global $DB_NAME;
global $DB_USERNAME;
global $DB_PASSWORD;
$conn = new mysqli( $DB_HOST, $DB_USERNAME, $DB_PASSWORD, $DB_NAME );
if (mysqli_connect_errno()) {
printf("Connection to the database failed: %s/n", $mysqli -> connect_error);
exit();
}
$sql = "SELECT * FROM resources WHERE category = ? ORDER BY position ASC LIMIT 4;";
if ($st = $conn->prepare( $sql )) {
$st->bind_param( "s", $type );
$st->execute();
$list = array();
while ( $row = $st->fetch() ) {
$resource = new Resource( $row );
$list[] = $resource;
}
$conn = null;
return $list;
} else {
printf("Errormessage: %s\n", $conn->error);
}
}
My Homepage.php file has the following code in it
<?php
foreach ( $results['learn'] as $learnTile ) {
print_r($learnTile);
?>
<div class="col-md-3 col-xs-6 featured">
<a href=".?action=viewResource&resourceId= <?php echo($learnTile->id)?> ">
<img src="#" class="thumbnail img-responsive">
</a>
</div>
<?php } ?>
The code is pulling the correct number of Resource objects, but something is going wring, because my link (in homepage.php) is not pulling in the id from the Resource object.
So, to debug i've printed out ($learnTile) and am getting empty objects/arrays.
Resource Object ( [id] => [title] => [summary] => [url] => [content] => [category] => [is_free] => [is_featured] => [is_favorite] => [date_created] => ) Resource Object ( [id] => [title] => [summary] => [url] => [content] ...
Where am I going wrong? is my constructor not working? Clearly the Resource objects are pulling the null values from the original property definitions to null.
I've been stumped on this one for several days so any help / guidance is appreciated. Thanks!

There is never an array inside the $row. See the manual: php.net/manual/en/mysqli-stmt.fetch.php it returns a boolean only. You should bind your result when using prepare.

Related

How do I Paginate my CMS

I've been following the Build a CMS in an Afternoon tutorial at http://www.elated.com/articles/cms-in-an-afternoon-php-mysql/ .
The CMS works great but the only thing it's lacking is pagination. The article archive displays the list of all of the articles that are in the database, but I want to be able to separate these into pages. I've attempted it a few times but can never seem to get it to work. Clicking on a next page link usually brings me back to the homepage.
I will apreciate your help
Code:
config.php
<?php ini_set( "display_errors", true );
date_default_timezone_set("europe/lisbon" );
define( "DB_DSN", "mysql:host=localhost;dbname=cms" );
define( "DB_USERNAME", "username" );
define( "DB_PASSWORD", "password" );
define( "CLASS_PATH", "classes" );
define( "TEMPLATE_PATH", "templates" );
define( "HOMEPAGE_NUM_ARTICLES", 5 );
define( "ADMIN_USERNAME", "admin" );
define( "ADMIN_PASSWORD", "mypass" );
require( CLASS_PATH . "/Article.php" );
function handleException( $exception ) {
echo "Sorry, a problem occurred. Please try later.";
error_log( $exception->getMessage() ); }
set_exception_handler( 'handleException' ); ?>
archive.php
<?php include "templates/include/header.php" ?>
<h1>Article Archive</h1>
<ul id="headlines" class="archive">
<?php foreach ( $results['articles'] as $article ) { ?>
<li>
<h2>
<span class="pubDate"><?php echo date('j F Y', $article->publicationDate)?></span><?php echo htmlspecialchars( $article->title )?>
</h2>
<p class="summary"><?php echo htmlspecialchars( $article->summary )?></p>
</li>
<?php } ?>
</ul>
<p><?php echo $results['totalRows']?> article<?php echo ( $results['totalRows'] != 1 ) ? 's' : '' ?> in total.</p>
<p>Return to Homepage</p>
<?php include "templates/include/footer.php" ?>
article.php
<?php
/**
* Class to handle articles
*/
class Article
{
public $id = null;
public $publicationDate = null;
public $title = null;
public $summary = null;
public $content = null;
public function __construct( $data=array() ) {
if ( isset( $data['id'] ) ) $this->id = (int) $data['id'];
if ( isset( $data['publicationDate'] ) ) $this->publicationDate = (int) $data['publicationDate'];
if ( isset( $data['title'] ) ) $this->title = preg_replace ( "/[^\.\,\-\_\'\"\#\?\!\:\$ a-zA-Z0-9()]/", "", $data['title'] );
if ( isset( $data['summary'] ) ) $this->summary = preg_replace ( "/[^\.\,\-\_\'\"\#\?\!\:\$ a-zA-Z0-9()]/", "", $data['summary'] );
if ( isset( $data['content'] ) ) $this->content = $data['content'];
}
public function storeFormValues ( $params ) {
// Store all the parameters
$this->__construct( $params );
// Parse and store the publication date
if ( isset($params['publicationDate']) ) {
$publicationDate = explode ( '-', $params['publicationDate'] );
if ( count($publicationDate) == 3 ) {
list ( $y, $m, $d ) = $publicationDate;
$this->publicationDate = mktime ( 0, 0, 0, $m, $d, $y );
}
}
}
public static function getById( $id ) {
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$sql = "SELECT *, UNIX_TIMESTAMP(publicationDate) AS publicationDate FROM articles WHERE id = :id";
$st = $conn->prepare( $sql );
$st->bindValue( ":id", $id, PDO::PARAM_INT );
$st->execute();
$row = $st->fetch();
$conn = null;
if ( $row ) return new Article( $row );
}
public static function getList( $numRows=1000000, $order="publicationDate DESC" ) {
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$sql = "SELECT SQL_CALC_FOUND_ROWS *, UNIX_TIMESTAMP(publicationDate) AS publicationDate FROM articles
ORDER BY " . mysql_escape_string($order) . " LIMIT :numRows";
$st = $conn->prepare( $sql );
$st->bindValue( ":numRows", $numRows, PDO::PARAM_INT );
$st->execute();
$list = array();
while ( $row = $st->fetch() ) {
$article = new Article( $row );
$list[] = $article;
}
// Now get the total number of articles that matched the criteria
$sql = "SELECT FOUND_ROWS() AS totalRows";
$totalRows = $conn->query( $sql )->fetch();
$conn = null;
return ( array ( "results" => $list, "totalRows" => $totalRows[0] ) );
}
?>
You need to modify your code to $_GET the page number and use limit and offset in the query
you can see this example
http://www.tutorialspoint.com/php/mysql_paging_php.htm

Cannot redeclare class JSONParserException

This is my code,
which always produce error when "new Entity\UserAds($array);" is added
Entities are present in "models\Entity\" folder
use Entity\UserAds;
use Entity\Comment;
class postad extends CI_Controller {
protected $view_data;
public function __construct() {
parent::__construct ();
$this->load->helper ( array (
'form',
'url'
) );
$this->load->library ( 'form_validation' );
// view data
}
public function index() {
if ($this->form_validation->run() == FALSE) {
$this->view_data ['content'] = 'contents/postads';
$this->load->view ( 'templates/layout', $this->view_data );
} else {
$array = $this->input->post ();
try {
$ads = UserAds::createFromPost($array );
$this->em = $this->doctrine->em;
//$repository = $this->em->getRepository ( 'Entity\User' );
$this->em->persist ( $ads );
$this->em->flush ();
$this->session->set_flashdata ( 'err_msg', "" );
$this->log ( "create_post() created new ads." );
$this->view_data['count']=$this->input->post('count');
$this->view_data ['result'] = $ads;
$adid=$ads->getId();
$ads->getImages();
$this->session->set_userdata('id',$adid);
$this->load->model("emailmodel");
$this->emailmodel->send_notification($ads->getEmail(),$adid,$ads->getTitle());
if($this->session->userdata("username")==""){
/*new block added from */
$array = array ();
$name=$array ['name'] = $ads->getName();
$mobile=$array ['mobile'] = $ads->getMobile();
$array ['email'] =$ads->getEmail();
$array ['password'] = '12345';
$array ['dob'] = DateTime::createFromFormat ( "d/m/Y", '');
$array ['everified'] = 0;
$array ['mverified'] = 0;
$array ['devicetype'] = 0;
$array ['usertype'] = 0;
$user = new Entity\User ( $array );
$this->em->persist ( $user );
$this->em->flush (); //till this
$this->load->model ( 'homemodel' );
$randstr = $this->homemodel->rand_string ( $name, $mobile );
$this->load->model ( 'emailmodel' );
$email =$ads->getEmail();
$randstr = $this->emailmodel->getmailcode ( $email );
$this->emailmodel->sendVerificatinEmail ( $email, $randstr );
}
$this->view_data ['content'] = 'contents/adcreated';
$this->load->view ( 'templates/layout', $this->view_data );
} catch ( Exception $e ) {
$this->error ( "createAds(): creation faield." . $e->getMessage () );
$this->session->set_flashdata ( 'err_msg', "Failed to post ad" . $e->getMessage () );
$this->view_data ['content'] = 'contents/postads';
$this->load->view ( 'templates/layout', $this->view_data );
}
}
}
This is my error message:
Cannot redeclare class JSONParserException in C:\wamp\www\rah\application\core\JSONParserException.php on line 12

Can anyone help me display this php code in smarty?

I have sat 3 days trying to figure out Smarty, but I don't feel very much smartyer :)
Here is my php code:
somefile.php
include('libs/Smarty.class.php');
require( "configs/config.php" );
// create object
$smarty = new Smarty;
function homepage($params, $smarty, $numRows=1000000, $order="publicationDate DESC" ) {
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$sql = "SELECT SQL_CALC_FOUND_ROWS *, UNIX_TIMESTAMP(publicationDate) AS publicationDate FROM articles
ORDER BY " . mysql_escape_string($order) . " LIMIT :numRows";
$st = $conn->prepare( $sql );
$st->bindValue( ":numRows", $numRows, PDO::PARAM_INT );
$st->execute();
$list = array();
while ( $row = $st->fetch() ) {
$article = new Article( $row );
$list[] = $article;
}
// Now get the total number of articles that matched the criteria
$sql = "SELECT FOUND_ROWS() AS totalRows";
$totalRows = $conn->query( $sql )->fetch();
$conn = null;
return ( array ( "results" => $list, "totalRows" => $totalRows[0] ) );
if ( isset( $data['id'] ) ) $this->id = (int) $data['id'];
if ( isset( $data['publicationDate'] ) ) $this->publicationDate = (int) $data['publicationDate'];
if ( isset( $data['title'] ) ) $this->title = preg_replace ( "/[^\.\,\-\_\'\"\#\?\!\:\$ a-zA-Z0-9()]/", "", $data['title'] );
if ( isset( $data['summary'] ) ) $this->summary = preg_replace ( "/[^\.\,\-\_\'\"\#\?\!\:\$ a-zA-Z0-9()]/", "", $data['summary'] );
if ( isset( $data['content'] ) ) $this->content = $data['content'];
$results = array();
$results['articles'] = $data['articles'];
$results['totalRows'] = $data['totalRows'];
$smarty->assign("articles", $data['articles']);
$smarty->assign("totalRows", $data['totalRows']);
$smarty->assign("id", $data['id']);
$smarty->assign("publicationDate", $data['publicationDate']);
$smarty->assign("title", 'kkkkkkkkkkkkkkkkkkkkk');
$smarty->assign("summary", 'lllllllllllllllllllllll');
$smarty->assign("content", 'øøøøøøøøøøøøøøøøøøøøøøøøøøøøøø');
}
// display it
$smarty->display('index2.tpl');
index2.tpl
{include file="header.tpl"}
{debug}
<h1>Article Archive</h1>
{assign var=results value={cycle values="totalRows,articles,title,publicationDate,id"}}
<ul id="headlines" class="archive">
{foreach $articles['articles'] as $article}
<li>
<h2>
<span class="pubDate">{$publicationDate}</span>{$title}
</h2>
<p class="summary">{$summary}</p>
</li>
{/foreach}
</ul>
<p>Articles Archive</p>
{include file="footer.tpl"}
The errors I get are:
Notice: Undefined index: articles in /var/www/www.mypage.com/htdocs/smarty/templates_c/cd9ff0835daf703adc0ed3991c1d26021d9fcc09.file.index2.tpl.php on line 42
Notice: Trying to get property of non-object in /var/www/www.mypage.com/htdocs/smarty/templates_c/cd9ff0835daf703adc0ed3991c1d26021d9fcc09.file.index2.tpl.php on line 42
I think that the problem is that, for some reason, you assume that when you do
$smarty->assign("articles", $data['articles']);
they key 'articles' is included, wich is not, only the contents of it. So there is no such $articles['articles'] passed to the template, in he same way there is no $id['id'], only $id. Try to do the foreach with just $articles:
{foreach $articles as $article}

Fetching and echoing results with php

I'm having an issue displaying the results of query. The weird thing is, all of the results are being obtained and only one is not. I'm at a complete loss.
I'm going to describe, to the best of my knowledge, how this code is supposed to work. I built it from a tutorial.
In "listProducts.php" all the products in the database are listed in a table.
<table id="productTable">
<tr>
<th>UPC</th>
<th>Title</th>
<th>Thumb</th>
<th>Price</th>
<th>Stock</th>
<th>Lead Time</th>
<th></th>
</tr>
<?php foreach ( $results['products'] as $product ) {
list($week, $day) = explode("|", $product->lead);
echo htmlspecialchars($product->lead);
?>
<tr onclick="location='products.php?action=editProduct&productId=<?php echo $product->id?>'">
<td><img src="../<?php echo $product->thumb ?>"/></td>
<td><?php echo htmlspecialchars($product->upc)?></td>
<td><?php echo htmlspecialchars($product->title)?></td>
<td style="text-align:right;">$<?php echo number_format($product->price, 2 )?></td>
<td style="text-align:right;"><?php echo number_format($product->stock, 0)?></td>
<td style="text-align:right;"><? echo $week.'|'.$day;?></td>
<td><button >Edit</button></td>
</tr>
<? } ?>
</table>
The problem is lead, which exists in the database as lead, is not being or has not been fetched and therefore not being exploded and is therefore not being echoed as week and day.
Even if, for testing purposes, I echo just lead, i get nothing.
<? echo htmlspecialchars($products->lead)?>
There is a listProducts() function and some class junk that i did not come up with, but I have thoroughly manipulated to my own ends so I'm fairly confident that they should work. But, I'll post them anyway.
function listProducts() {
$results = array();
$data = Product::getList();
$results['products'] = $data['results'];
$results['totalRows'] = $data['totalRows'];
$results['pageTitle'] = "All Products";
if ( isset( $_GET['error'] ) ) {
if ( $_GET['error'] == "productNotFound" ) $results['errorMessage'] = "Error: Product not found.";
}
if ( isset( $_GET['status'] ) ) {
if ( $_GET['status'] == "changesSaved" ) $results['statusMessage'] = "Your changes have been saved.";
if ( $_GET['status'] == "productDeleted" ) $results['statusMessage'] = "Product deleted.";
}
require( TEMPLATE_PATH . "/admin/listProducts.php" );
}
And here is the parts of the product class that i think deal with displaying the list... cus it says get list.
public static function getList( $numRows=100, $order="title DESC" ) {
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$sql = "SELECT SQL_CALC_FOUND_ROWS *, id FROM products
ORDER BY " . $order . " LIMIT :numRows";
$st = $conn->prepare( $sql );
$st->bindValue( ":numRows", $numRows, PDO::PARAM_INT );
$st->execute();
$list = array();
while ( $row = $st->fetch() ) {
$product = new Product( $row );
$list[] = $product;
}
// Now get the total number of products that matched the criteria
$sql = "SELECT FOUND_ROWS() AS totalRows";
$totalRows = $conn->query( $sql )->fetch();
$conn = null;
return ( array ( "results" => $list, "totalRows" => $totalRows[0] ) );
}
and some constructors and variables. I don't know if they are necessary or not
public $id = null;
public $upc = null;
public $title = null;
public $thumb = null;
public $description = null;
public $price = null;
public $stock = null;
public $lead = null;
public function __construct( $data=array() ) {
if ( isset( $data['id'] ) ) $this->id = (int) $data['id'];
if ( isset( $data['upc'] ) ) $this->upc = preg_replace ( "/[^\.\,\-\_\'\"\#\?\!\:\$ a-zA-Z0-9()]/", "", $data['upc'] );
if ( isset( $data['title'] ) ) $this->title = preg_replace ( "/[^\.\,\-\_\'\"\#\?\!\:\$ a-zA-Z0-9()]/", "", $data['title'] );
if ( isset( $data['thumb'] ) ) $this->thumb = $data['thumb'];
if ( isset( $data['description'] ) ) $this->description = $data['description'];
if ( isset( $data['price'] ) ) $this->price = $data['price'];
if ( isset( $data['stock'] ) ) $this->stock = (int) $data['stock'];
if ( isset( $data['week'] ) && isset( $data['day'] ) ) $this->lead = $data['week']."|".$data['day'];
}

Wordpress database insert() and update() - using NULL values

Wordpress ships with the wpdb class which handles CRUD operations. The two methods of this class that I'm interested in are the insert() (the C in CRUD) and update() (the U in CRUD).
A problem arises when I want to insert a NULL into a mysql database column - the wpdb class escapes PHP null variables to empty strings. How can I tell Wordpress to use an actual MySQL NULL instead of a MySQL string?
If you want it to compatible you would have to SHOW COLUMN and determine ahead if NULL is allowed. If it was allowed then if the value was empty($v) use val = NULL in the query.
$foo = null;
$metakey = "Harriet's Adages";
$metavalue = "WordPress' database interface is like Sunday Morning: Easy.";
if ($foo == null) {
$wpdb->query( $wpdb->prepare( "
INSERT INTO $wpdb->postmeta
( post_id, meta_key, meta_value, field_with_null )
VALUES ( %d, %s, %s, NULL )",
10, $metakey, $metavalue ) );
} else {
$wpdb->query( $wpdb->prepare( "
INSERT INTO $wpdb->postmeta
( post_id, meta_key, meta_value, field_with_null )
VALUES ( %d, %s, %s, %s)",
10, $metakey, $metavalue, $foo ) );
}
Here's a solution to your problem. In "wp-content" folder, create a file named "db.php" and put this code in it:
<?php
// setup a dummy wpdb to prevent the default one from being instanciated
$wpdb = new stdclass();
// include the base wpdb class to inherit from
//include ABSPATH . WPINC . "/wp-db.php";
class wpdbfixed extends wpdb
{
function insert($table, $data, $format = null) {
$formats = $format = (array) $format;
$fields = array_keys($data);
$formatted_fields = array();
$real_data = array();
foreach ( $fields as $field ) {
if ($data[$field]===null)
{
$formatted_fields[] = 'NULL';
continue;
}
if ( !empty($format) )
$form = ( $form = array_shift($formats) ) ? $form : $format[0];
elseif ( isset($this->field_types[$field]) )
$form = $this->field_types[$field];
else
$form = '%s';
$formatted_fields[] = "'".$form."'";
$real_data[] = $data[$field];
}
//$sql = "INSERT INTO <code>$table</code> (<code>" . implode( '</code>,<code>', $fields ) . "</code>) VALUES (" . implode( ",", $formatted_fields ) . ")";
$sql = "INSERT INTO $table (" . implode( ',', $fields ) . ") VALUES (" . implode( ",", $formatted_fields ) . ")";
return $this->query( $this->prepare( $sql, $real_data) );
}
function update($table, $data, $where, $format = null, $where_format = null)
{
if ( !is_array( $where ) )
return false;
$formats = $format = (array) $format;
$bits = $wheres = array();
$fields = (array) array_keys($data);
$real_data = array();
foreach ( $fields as $field ) {
if ($data[$field]===null)
{
$bits[] = "$field = NULL";
continue;
}
if ( !empty($format) )
$form = ( $form = array_shift($formats) ) ? $form : $format[0];
elseif ( isset($this->field_types[$field]) )
$form = $this->field_types[$field];
else
$form = '%s';
$bits[] = "$field = {$form}";
$real_data[] = $data[$field];
}
$where_formats = $where_format = (array) $where_format;
$fields = (array) array_keys($where);
foreach ( $fields as $field ) {
if ( !empty($where_format) )
$form = ( $form = array_shift($where_formats) ) ? $form : $where_format[0];
elseif ( isset($this->field_types[$field]) )
$form = $this->field_types[$field];
else
$form = '%s';
$wheres[] = "$field = {$form}";
}
$sql = "UPDATE $table SET " . implode( ', ', $bits ) . ' WHERE ' . implode( ' AND ', $wheres );
return $this->query( $this->prepare( $sql, array_merge($real_data, array_values($where))) );
}
}
$wpdb = new wpdbfixed(DB_USER, DB_PASSWORD, DB_NAME, DB_HOST);
?>
In this way you can use null values with wpdb!
I find this on Wordpress StackExchange forum and it works very well for me.
// Add a filter to replace the 'NULL' string with NULL
add_filter( 'query', 'wp_db_null_value' );
global $wpdb;
$wpdb->update(
'table',
array(
'status' => 'NULL',
),
array( 'id' => 1 )
);
// Remove the filter again:
remove_filter( 'query', 'wp_db_null_value' );
and the function wp_db_null_value is:
/**
* Replace the 'NULL' string with NULL
*
* #param string $query
* #return string $query
*/
function wp_db_null_value( $query )
{
return str_ireplace( "'NULL'", "NULL", $query );
}
Because in my case I cannot use $db->prepare() function...
wpdb insert() and update() works with NULL values, it was patched many years ago but never mentioned in the Codex.
In your case:
$wpdb->update(
'table',
array(
'status' => null,
),
array( 'id' => 1 ),
null,
'%d'
);
Ref: https://core.trac.wordpress.org/ticket/15158#no0
I tried to edit one of the other solutions listed here, because it resulted in the format array being misaligned with the data array, but failed.
Here is a solution that modifies the wpdb from the latest version of wordpress, in order to allow inserting and updating null values into SQL tables using insert() and update():
/*
* Fix wpdb to allow inserting/updating of null values into tables
*/
class wpdbfixed extends wpdb
{
function insert($table, $data, $format = null) {
$type = 'INSERT';
if ( ! in_array( strtoupper( $type ), array( 'REPLACE', 'INSERT' ) ) )
return false;
$this->insert_id = 0;
$formats = $format = (array) $format;
$fields = array_keys( $data );
$formatted_fields = array();
foreach ( $fields as $field ) {
if ( !empty( $format ) )
$form = ( $form = array_shift( $formats ) ) ? $form : $format[0];
elseif ( isset( $this->field_types[$field] ) )
$form = $this->field_types[$field];
else
$form = '%s';
//***Steve Lee edit begin here***
if ($data[$field]===null) {
unset($data[$field]); //Remove this element from array, so we don't try to insert its value into the %s/%d/%f parts during prepare(). Without this, array would become shifted.
$formatted_fields[] = 'NULL';
} else {
$formatted_fields[] = $form; //Original line of code
}
//***Steve Lee edit ends here***
}
$sql = "{$type} INTO `$table` (`" . implode( '`,`', $fields ) . "`) VALUES (" . implode( ",", $formatted_fields ) . ")";
return $this->query( $this->prepare( $sql, $data ) );
}
function update($table, $data, $where, $format = null, $where_format = null)
{
if ( ! is_array( $data ) || ! is_array( $where ) )
return false;
$formats = $format = (array) $format;
$bits = $wheres = array();
foreach ( (array) array_keys( $data ) as $field ) {
if ( !empty( $format ) )
$form = ( $form = array_shift( $formats ) ) ? $form : $format[0];
elseif ( isset($this->field_types[$field]) )
$form = $this->field_types[$field];
else
$form = '%s';
//***Steve Lee edit begin here***
if ($data[$field]===null)
{
unset($data[$field]); //Remove this element from array, so we don't try to insert its value into the %s/%d/%f parts during prepare(). Without this, array would become shifted.
$bits[] = "`$field` = NULL";
} else {
$bits[] = "`$field` = {$form}"; //Original line of code
}
//***Steve Lee edit ends here***
}
$where_formats = $where_format = (array) $where_format;
foreach ( (array) array_keys( $where ) as $field ) {
if ( !empty( $where_format ) )
$form = ( $form = array_shift( $where_formats ) ) ? $form : $where_format[0];
elseif ( isset( $this->field_types[$field] ) )
$form = $this->field_types[$field];
else
$form = '%s';
$wheres[] = "`$field` = {$form}";
}
$sql = "UPDATE `$table` SET " . implode( ', ', $bits ) . ' WHERE ' . implode( ' AND ', $wheres );
return $this->query( $this->prepare( $sql, array_merge( array_values( $data ), array_values( $where ) ) ) );
}
}
global $wpdb_allow_null;
$wpdb_allow_null = new wpdbfixed(DB_USER, DB_PASSWORD, DB_NAME, DB_HOST);
Insert this code into somewhere that always gets run, like your functions.php, and then use your new global $wpdb_allowed_null->insert() and ->update() as normal.
I preferred this method vs. overriding the default $wpdb, in order to preserve the DB behavior that the rest of Wordpress and other plugins will expect.

Categories