$URL value not being added to mySQL db PHP - php

Here is my code:
<?php
/**
* Class to handle articles
*/
class Article
{
// Properties
/**
* #var int The article ID from the database
*/
public $id = null;
/**
* #var int When the article is to be / was first published
*/
public $publicationDate = null;
/**
* #var string Full title of the article
*/
public $title = null;
/**
* #var string A short summary of the article
*/
public $summary = null;
/**
* #var string The HTML content of the article
*/
public $content = null;
/**
* Sets the object's properties using the values in the supplied array
*
* #param assoc The property values
*/
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'];
}
/**
* Sets the object's properties using the edit form post values in the supplied array
*
* #param assoc The form post values
*/
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;
}
}
}
/**
* Returns an Article object matching the given article ID
*
* #param int The article ID
* #return Article|false The article object, or false if the record was not found or there was a problem
*/
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 );
}
/**
* Returns all (or a range of) Article objects in the DB
*
* #param int Optional The number of rows to return (default=all)
* #param string Optional column by which to order the articles (default="publicationDate ASC, id ASC")
* #return Array|false A two-element array : results => array, a list of Article objects; totalRows => Total number of articles
*/
public static function getList( $numRows=1000000, $order="publicationDate DESC, ID 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] ) );
}
/**
* Inserts the current Article object into the database, and sets its ID property.
*/
public function insert() {
// Does the Article object already have an ID?
if ( !is_null( $this->id ) ) trigger_error ( "Article::insert(): Attempt to insert an Article object that already has its ID property set (to $this->id).", E_USER_ERROR );
$preURL = $data['title'];
$preURL2 = preg_replace('/[^a-z0-9]/i',' ', $preURL);
$preURL3 = str_replace(" ","-", $preURL2);
$url = $date.'/'.$preURL3.'.html';
// Insert the Article
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$sql = "INSERT INTO articles ( publicationDate, title, summary, content, url)
VALUES ( FROM_UNIXTIME(:publicationDate), :title, :summary, :content, :url )";
$st = $conn->prepare ( $sql );
$st->bindValue( ":publicationDate", $this->publicationDate, PDO::PARAM_INT );
$st->bindValue( ":title", $this->title, PDO::PARAM_STR );
$st->bindValue( ":summary", $this->summary, PDO::PARAM_STR );
$st->bindValue( ":content", $this->content, PDO::PARAM_STR );
$st->bindValue( ":url", $this->url, PDO::PARAM_STR );
$st->execute();
$this->id = $conn->lastInsertId();
$conn = null;
}
?>
This doesn't add the stripped down version of 'titl'e to the Url row as I want it to. Am I doing something wrong? Have i defined a variable incorrectly somewhere? I'm not getting any error - just getting left with a null value in the url row.
Thankyou.

In your insert() function, you are binding $this->url which should probably be just $url. And the following line,
$preURL = $data['title'];
should also be changed to,
$preURL = $this->title;

Related

Fatal error: Uncaught PDOException: SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens in php:74 [duplicate]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I am receiving the error of SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens on line 102 in comments.php below:
<?php
/**
* Class to handle articles
*/
class Comment
{
// Properties
/**
* #var int The article ID from the database
*/
public $id = null;
/**
* #var int When the article is to be / was first published
*/
public $publicationDate = null;
/**
* #var string Full title of the article
*/
public $title = null;
/**
* #var string The HTML content of the article
*/
public $content = null;
/**
* #var int The article ID from the database
*/
public $articleid = null;
/**
* Sets the object's properties using the values in the supplied array
*
* #param assoc The property values
*/
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['content'] ) ) $this->content = $data['content'];
if ( isset( $data['articleid'] ) ) $this->articleid = (int) $data['articleid'];
}
/**
* Sets the object's properties using the edit form post values in the supplied array
*
* #param assoc The form post values
*/
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 comments 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 Comment( $row );
}
/**
* Returns all (or a range of) Article objects in the DB
*
* #param int Optional The number of rows to return (default=all)
* #param string Optional column by which to order the articles (default="publicationDate DESC")
* #return Array|false A two-element array : results => array, a list of Article objects; totalRows => Total number of articles
*/
public static function getList( $art=1, $order="publicationDate DESC", $numRows=10000 ) {
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$sql = "SELECT SQL_CALC_FOUND_ROWS *, UNIX_TIMESTAMP(publicationDate) AS publicationDate FROM comments WHERE articleid = :art
ORDER BY " . mysql_escape_string($order) . " LIMIT :numRows";
$st = $conn->prepare( $sql );
$st->bindValue( ":art", $art, PDO::PARAM_INT );
$st->execute();
$list = array();
while ( $row = $st->fetch() ) {
$comments = new Comment( $row );
$list[] = $comment;
}
}
/**
* Inserts the current Article object into the database, and sets its ID property.
*/
public function insert() {
// Insert the Article
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$sql = "INSERT INTO comments ( publicationDate, title, content, articledid ) VALUES ( FROM_UNIXTIME(:publicationDate), :title, :content, :articleid )";
$st = $conn->prepare ( $sql );
$st->bindValue( ":publicationDate", $this->publicationDate, PDO::PARAM_INT );
$st->bindValue( ":title", $this->title, PDO::PARAM_STR );
$st->bindValue( ":content", $this->content, PDO::PARAM_STR );
$st->bindValue( ":articleid", $this->articleid, PDO::PARAM_STR );
$st->execute();
$this->id = $conn->lastInsertId();
$conn = null;
}
/**
* Updates the current Article object in the database.
*/
public function update() {
// Update the Article
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$sql = "UPDATE comments SET publicationDate=FROM_UNIXTIME(:publicationDate), title=:title, summary=:summary, content=:content, articleid=:articleid,imageExtension=:imageExtension WHERE id = :id";
$st = $conn->prepare ( $sql );
$st->bindValue( ":publicationDate", $this->publicationDate, PDO::PARAM_INT );
$st->bindValue( ":title", $this->title, PDO::PARAM_STR );
$st->bindValue( ":content", $this->content, PDO::PARAM_STR );
$st->bindValue( ":articleid", $this->articleid, PDO::PARAM_STR );
$st->bindValue( ":id", $this->id, PDO::PARAM_INT );
$st->execute();
$conn = null;
}
/**
* Deletes the current Article object from the database.
*/
public function delete() {
// Delete the Article
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$st = $conn->prepare ( "DELETE FROM comments WHERE id = :id LIMIT 1" );
$st->bindValue( ":id", $this->id, PDO::PARAM_INT );
$st->execute();
$conn = null;
}
}
?>
You didn't bind all your bindings here
$sql = "UNIX_TIMESTAMP(publicationDate) AS publicationDate
FROM comments WHERE articleid = :art
ORDER BY some LIMIT :numRows";
$st = $conn->prepare( $sql );
$st->bindValue( ":art", $art, PDO::PARAM_INT );
You've declared a binding called :numRows but you never actually bind anything to it.

Call to undefined method PDOStatement

I'm having this error and been trying to figure whats wrong for like 3 days straight with no luck:
Fatal error: Call to undefined method PDOStatement::bindValues() on line 92
My complete code
<?php
//CLASS TO HANDLE AD
class Ad
{
//Ad id from database
public $id = null;
//Ad client
public $client = null;
//Ad client login id
public $client_loginID = null;
//Ad video source
public $video = null;
//Ad banner source
public $banner = null;
//Ad cover source
public $cover = null;
//Ad mid video banner ad
public $midVideoBannerAd = null;
//Ad link
public $link = null;
//Ad click
public $clicks = null;
//Ad impressions
public $impressions = null;
//If ad is active
public $active = null;
//Sets the obect properties using the values in supplied array
public function __construct( $data=array() ){
if( isset ( $data['id'] ) ) $this->id = (int) $data['id'];
if( isset ( $data['client'] ) ) $this->client = $data['client'];
}
//Sets the object properties using the edit form post values in the supplied array
public function storeFormValues( $params ){
//Store all the parameters
$this->__construct( $params );
}
//Returns an Author Object matching the given id
public static function getById( $statement ){
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$sql = "SELECT * FROM ad $statement";
$st = $conn->prepare( $sql );
$st->execute();
$row = $st->fetch();
$conn = null;
if( $row ) return new Ad( $row );
}
//Returns all (or range of) ad object in the db
public static function getList( $statement ){
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$sql = "SELECT * FROM ad $statement";
$st = $conn->prepare( $sql );
$st->execute();
$list = array();
while( $row = $st->fetch() ){
$ad = new Ad( $row );
$list[] = $ad;
}
//Now get the total number of Ad that match the criteria
$sql = "SELECT FOUND_ROWS() AS totalRows";
$totalRows = $conn->query( $sql )->fetch();
$conn = null;
return ( array ( "results" => $list, "totalRows" => $totalRows[0] ) );
}
//Insert current Ad object into database and set its ID properties
public function insert(){
//Check if Ad object already has an id
//Insert the Ad
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$sql = "INSERT INTO ad (client) VALUES ( :client )";
$st = $conn->prepare( $sql );
$st->bindValues( ":client", $this->client, PDO::PARAM_STR );
$st->execute();
$this->id = $conn->lastInsertId();
$conn = null;
}
//Updates the current Ad in DB
public function update(){
//Check if Ad object has an id
if( !is_null ( $this->id ) ) trigger_error ( "Ad::update(): Attempt to update an Ad object that already has an ID set.", E_USER_ERROR );
//Updates the Ad
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$sql = "UPDATE ad set client=:client, client_loginID=:client_loginID, video=:video, midVideoBannerAd=:midVideoBannerAd, banner=:banner, cover=:cover, link=:link, active=:active WHERE id=:id";
$st = $conn->prepare( $sql );
$st->bindValues( ":client", $this->client, PDO::PARAM_STR );
$st->bindValues( ":client_loginID", $this->client_loginID, PDO::PARAM_INT );
$st->bindValues( ":video", $this->video, PDO::PARAM_INT );
$st->bindValues( ":midVideoBannerAd", $this->midVideoBannerAd, PDO::PARAM_INT );
$st->bindValues( ":banner", $this->banner, PDO::PARAM_INT );
$st->bindValues( ":cover", $this->cover, PDO::PARAM_INT );
$st->bindValues( ":link", $this->link, PDO::PARAM_STR );
$st->bindValues( ":active", $this->active, PDO::PARAM_INT );
$st->bindValues( ":id", $this->id, PDO::PARAM_INT );
$st->execute();
$conn = null;
}
//Delete current Ad from Database
public function delete(){
//Delete the Ad
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$st = $conn->prepare( "DELETE FROM ad WHERE id=:id" );
$st->bindValues( ":id", $this->id, PDO::PARAM_INT );
$st->execute();
$conn = null;
}
}
And this is what's on line 92:
$st->bindValues( ":client", $this->client, PDO::PARAM_STR );
The method is called PDOStatement->bindValue() without the trailing "s"
see http://www.php.net/manual/en/pdostatement.bindvalue.php

How to combine two table in one php class file

i am using the below php class file as an example to built a back end system. My question is how can i call one more table in this file called articles2? Should i create a new class file or it can be combined here?
<?php
/**
* Class to handle articles
*/
class Article
{
// Properties
/**
* #var int The article ID from the database
*/
public $id = null;
/**
* #var int When the article is to be / was first published
*/
public $publicationDate = null;
/**
* #var string Full title of the article
*/
public $title = null;
/**
* #var string A short summary of the article
*/
public $summary = null;
/**
* #var string The HTML content of the article
*/
public $content = null;
/**
* Sets the object's properties using the values in the supplied array
*
* #param assoc The property values
*/
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'];
}
/**
* Sets the object's properties using the edit form post values in the supplied array
*
* #param assoc The form post values
*/
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 );
}
}
}
/**
* Returns an Article object matching the given article ID
*
* #param int The article ID
* #return Article|false The article object, or false if the record was not found or there was a problem
*/
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 );
}
/**
* Returns all (or a range of) Article objects in the DB
*
* #param int Optional The number of rows to return (default=all)
* #param string Optional column by which to order the articles (default="publicationDate DESC")
* #return Array|false A two-element array : results => array, a list of Article objects; totalRows => Total number of articles
*/
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] ) );
}
/**
* Inserts the current Article object into the database, and sets its ID property.
*/
public function insert() {
// Does the Article object already have an ID?
if ( !is_null( $this->id ) ) trigger_error ( "Article::insert(): Attempt to insert an Article object that already has its ID property set (to $this->id).", E_USER_ERROR );
// Insert the Article
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$sql = "INSERT INTO articles ( publicationDate, title, summary, content ) VALUES ( FROM_UNIXTIME(:publicationDate), :title, :summary, :content )";
$st = $conn->prepare ( $sql );
$st->bindValue( ":publicationDate", $this->publicationDate, PDO::PARAM_INT );
$st->bindValue( ":title", $this->title, PDO::PARAM_STR );
$st->bindValue( ":summary", $this->summary, PDO::PARAM_STR );
$st->bindValue( ":content", $this->content, PDO::PARAM_STR );
$st->execute();
$this->id = $conn->lastInsertId();
$conn = null;
}
/**
* Updates the current Article object in the database.
*/
public function update() {
// Does the Article object have an ID?
if ( is_null( $this->id ) ) trigger_error ( "Article::update(): Attempt to update an Article object that does not have its ID property set.", E_USER_ERROR );
// Update the Article
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$sql = "UPDATE articles SET publicationDate=FROM_UNIXTIME(:publicationDate), title=:title, summary=:summary, content=:content WHERE id = :id";
$st = $conn->prepare ( $sql );
$st->bindValue( ":publicationDate", $this->publicationDate, PDO::PARAM_INT );
$st->bindValue( ":title", $this->title, PDO::PARAM_STR );
$st->bindValue( ":summary", $this->summary, PDO::PARAM_STR );
$st->bindValue( ":content", $this->content, PDO::PARAM_STR );
$st->bindValue( ":id", $this->id, PDO::PARAM_INT );
$st->execute();
$conn = null;
}
/**
* Deletes the current Article object from the database.
*/
public function delete() {
// Does the Article object have an ID?
if ( is_null( $this->id ) ) trigger_error ( "Article::delete(): Attempt to delete an Article object that does not have its ID property set.", E_USER_ERROR );
// Delete the Article
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$st = $conn->prepare ( "DELETE FROM articles WHERE id = :id LIMIT 1" );
$st->bindValue( ":id", $this->id, PDO::PARAM_INT );
$st->execute();
$conn = null;
}
}
?>

'SELECT FOUND_ROWS()' returning a minimum of 1 when results empty

I have a problem getting SELECT FOUND_ROWS() to return 0 when the result from MSQL query is empty.
I have the following function that calls getBasket();
function viewBasket(){
include('classes/Orders.php');
$BasketID = 10;
$numRows=100;
$data = Orders::getBasket( $numRows, $BasketID);
$results['basket'] = $data['results'];
$results['totalRows'] = $data['totalRows'];
require( "templates/Basket.php" );
};
getBasket() builds the required results using LEFT OUTER JOIN and places into an array which is then returned to viewBasket().
public static function getBasket( $numRows, $BasketID ) {
$order="Name ASC";
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$sql = "
SELECT SQL_CALC_FOUND_ROWS B.BasketID
, BP.ProductID
, BP.Quantity
, P.Name
, P.Price
, PT.NameType
FROM Basket B
LEFT
JOIN BasketProducts BP
ON B.BasketID = BP.BasketID
LEFT
JOIN Products P
ON BP.ProductID = P.ProductID
LEFT
JOIN ProductTypes PT
ON P.ProductTypeID = PT.ProductTypeID
WHERE B.BasketID = :BasketID
ORDER
BY $order
LIMIT :numRows;
";
$st = $conn->prepare( $sql );
$st->bindValue( ":numRows", $numRows, PDO::PARAM_INT );
$st->bindValue( ":BasketID", $BasketID, PDO::PARAM_INT );
$st->execute();
$list = array();
while ( $row = $st->fetch() ) {
$basket = new Orders( $row );
$list[] = $basket;
}
// 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] ) );
}
My HTML then echos the totalRows value stored in $results by viewBasket();
<p>You have <?php echo $results['totalRows']?> item<?php echo ( $results['totalRows'] != 1 ) ? 's' : '' ?> in your Basket</p>
It works, but just wont send a 0 if the table is empty !
Thanks, Adam
I cannot reproduce the problem using php-5.6.3 and mysql-5.6 (default: myisam) under windows.
<?php
define('DB_DSN', 'mysql:host=localhost;dbname=test;charset=utf8');
define('DB_USERNAME', 'localonly');
define('DB_PASSWORD', 'localonly');
var_dump( getBasket(10, 1) );
function getBasket( $numRows, $BasketID ) {
$order="Name ASC";
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
setup($conn); // boilerplate: creating empty, temp tables
$sql = "
SELECT
SQL_CALC_FOUND_ROWS
Basket.BasketID, BasketProducts.ProductID, BasketProducts.Quantity,
Products.Name, Products.Price, ProductTypes.NameType
FROM
soBasket as Basket
LEFT OUTER JOIN
soBasketProducts as BasketProducts
ON
Basket.BasketID = BasketProducts.BasketID
LEFT OUTER JOIN
soProducts as Products
ON
BasketProducts.ProductID = Products.ProductID
LEFT OUTER JOIN
soProductTypes as ProductTypes
ON
Products.ProductTypeID = ProductTypes.ProductTypeID
WHERE
Basket.BasketID = :BasketID
ORDER BY
" . $order . " LIMIT :numRows
";
$st = $conn->prepare( $sql );
$st->bindValue( ":numRows", $numRows, PDO::PARAM_INT );
$st->bindValue( ":BasketID", $BasketID, PDO::PARAM_INT );
$st->execute();
$list = array();
while ( $row = $st->fetch() ) {
$basket = new Orders( $row );
$list[] = $basket;
}
// 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] ) );
}
class Orders {
public $_data;
public function __Construct(array $data) {
$this->_data = $data;
}
}
function setup($pdo) {
$queries = array(
"
CREATE TEMPORARY TABLE soBasket (
BasketID int
)
",
"
CREATE TEMPORARY TABLE soBasketProducts (
ProductID int,
BasketID int,
Quantity int
)
",
"
CREATE TEMPORARY TABLE soProducts (
ProductID int,
ProductTypeID int,
Price DECIMAL(10,2),
Name varchar(64)
)
",
"
CREATE TEMPORARY TABLE soProductTypes (
ProductTypeID int ,
NameType varchar(64)
)
"
);
foreach( $queries as $q ) {
$pdo->exec($q);
}
}
prints
array(2) {
'results' =>
array(0) {
}
'totalRows' =>
int(0)
}
if($results['totalRows'] > 0){
echo $results['TotalRows'];
else{
echo '0';
}
an IF condition before echoing would do it.
Try to cast it:
return ( array ( "results" => $list, "totalRows" => (int)$totalRows[0] ) );
thanks to the input from #VolkerK and #Phate01 I have solved the issue.
I cleared the BasketID set in the basket table if the row returned from basketProducts is NULL. i.e. if I have removed the last row from products associated to that user, remove the cart session from Basket.
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$st = $conn->prepare ( "select BasketID FROM basketProducts WHERE BasketID = :basketID" );
$st->bindValue(":basketID", $basketID, PDO::PARAM_INT );
$st->execute();
$row = $st->fetch();
$conn = null;
/**
* If the row returned from BasketProducts DOES NOT include the customers $basketID
* remove the row.
**/
if($row == 0){
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$st = $conn->prepare ( "DELETE FROM Basket WHERE BasketID = :basketID LIMIT 1" );
$st->bindValue(":basketID", $basketID, PDO::PARAM_INT );
$st->execute();
$row = $st->fetch();
$conn = null;
}else{
//do nothing
}
#VolkerK, I had a quick read of that link and its gone over my head. Will read up tonight, but would you mind explaining how this might help me?

Retrieve data from multiple mySQL tables

I will try and explain this as succinctly as possible as I'm quite new to this.
I have 3 tables: articles; categories; articles_to_categories
The complete Article class is below. The function getById is where I am aiming to pull the category through too.
<?php
/**
* Class to handle articles
*/
class Article
{
// Properties
/**
* #var int The article ID from the database
*/
public $id = null;
/**
* #var int When the article was published
*/
public $publicationDate = null;
/**
* #var string Full title of the article
*/
public $title = null;
/**
* #var string A short summary of the article
*/
public $summary = null;
/**
* #var string The HTML content of the article
*/
public $content = null;
/**
* Sets the object's properties using the values in the supplied array
*
* #param assoc The property values
*/
public function __construct( $data=array() ) {
if ( isset( $data['article_id'] ) ) $this->id = (int) $data['article_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'];
}
/**
* Sets the object's properties using the edit form post values in the supplied array
*
* #param assoc The form post values
*/
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 ( $d, $m, $y ) = $publicationDate;
$this->publicationDate = mktime ( 0, 0, 0, $m, $d, $y );
}
}
}
/**
* Returns an Article object matching the given article ID
*
* #param int The article ID
* #return Article|false The article object, or false if the record was not found or there was a problem
*/
public static function getById( $id ) {
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$sql = "SELECT *, UNIX_TIMESTAMP(publicationDate) AS publicationDate FROM articles WHERE article_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 );
}
/**
* Returns all (or a range of) Article objects in the DB
*
* #param int Optional The number of rows to return (default=all)
* #param string Optional column by which to order the articles (default="publicationDate DESC")
* #return Array|false A two-element array : results => array, a list of Article objects; totalRows => Total number of articles
*/
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] ) );
}
/**
* Inserts the current Article object into the database, and sets its ID property.
*/
public function insert() {
// Does the Article object already have an ID?
if ( !is_null( $this->id ) ) trigger_error ( "Article::insert(): Attempt to insert an Article object that already has its ID property set (to $this->id).", E_USER_ERROR );
// Insert the Article
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$sql = "INSERT INTO articles ( publicationDate, title, summary, content ) VALUES ( FROM_UNIXTIME(:publicationDate), :title, :summary, :content )";
//PDO prepare escapes string like mysql_real_escape_string
//PDO Allows you to enforce a datatypye ie. Sting, Integer etc
$st = $conn->prepare ( $sql );
$st->bindValue( ":publicationDate", $this->publicationDate, PDO::PARAM_INT );
$st->bindValue( ":title", $this->title, PDO::PARAM_STR );
$st->bindValue( ":summary", $this->summary, PDO::PARAM_STR );
$st->bindValue( ":content", $this->content, PDO::PARAM_STR );
$st->execute();
$this->id = $conn->lastInsertId();
$conn = null;
}
/**
* Updates the current Article object in the database.
*/
public function update() {
// Does the Article object have an ID?
if ( is_null( $this->id ) ) trigger_error ( "Article::update(): Attempt to update an Article object that does not have its ID property set.", E_USER_ERROR );
// Update the Article
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$sql = "UPDATE articles SET publicationDate=FROM_UNIXTIME(:publicationDate), title=:title, summary=:summary, content=:content WHERE id = :id";
$st = $conn->prepare ( $sql );
$st->bindValue( ":publicationDate", $this->publicationDate, PDO::PARAM_INT );
$st->bindValue( ":title", $this->title, PDO::PARAM_STR );
$st->bindValue( ":summary", $this->summary, PDO::PARAM_STR );
$st->bindValue( ":content", $this->content, PDO::PARAM_STR );
$st->bindValue( ":id", $this->id, PDO::PARAM_INT );
$st->execute();
$conn = null;
}
/**
* Deletes the current Article object from the database.
*/
public function delete() {
// Does the Article object have an ID?
if ( is_null( $this->id ) ) trigger_error ( "Article::delete(): Attempt to delete an Article object that does not have its ID property set.", E_USER_ERROR );
// Delete the Article
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$st = $conn->prepare ( "DELETE FROM articles WHERE id = :id LIMIT 1" );
$st->bindValue( ":id", $this->id, PDO::PARAM_INT );
$st->execute();
$conn = null;
}
}
?>
What I need to do is output which multiple categories the article is in. Would I have to create another SQL statement within this function or can I do it in the one statement.
Table/Columns overview:
articles - id, publicationDate, title, summary, content
categories - id, categoryTitle
articles_to_categories - article_id, category_id
I hope this is enough information for someone to help me on my way.
Thanks.
I think you should modify your class and add
public $categorie = null; //because you will add new column to table article
and modify all the code that depends on it, add the column to your db. etc

Categories