when adding a title that stores in database, create slug automatically - php

I have a basic insert record that inserts the data captured by a user into the database. It is a very simple form with a title, article and date. I want to create a slug entry as well though. So, if I type: this is a news title then I want it store that in the title column but also store, this-is-a-news-title in the slug column.
I'm using this which does work for creating the hyphens:
function create_url_slug($string){
$slug=preg_replace('/[^A-Za-z0-9-]+/', '-', $string);
return $slug;
}
And I have an insert like this:
$hostname_slugs = "localhost";
$database_slugs = "slugs";
$username_slugs = "root";
$password_slugs = "root";
try{
$conn = new PDO('mysql:host=$hostname_slugs;dbname=$database_slugs', '$username_slugs', '$password_slugs');
$slug = create_url_slug($_POST['newsarticle']);
//we'll use a prepared statement, which will sanitize our strings for us!
$stmt = $conn->prepare('INSERT INTO news (articledate, newsheadline, headlineslug, newsarticle) VALUES (:articledate, :newsheadline, :headlineslug, :newsarticle)');
$stmt->bindParam(':articledate', $_POST['articledate']);
$stmt->bindParam(':newsheadline', $_POST['newsheadline']);
$stmt->bindParam(':headlineslug', $_POST['headlineslug']);
$stmt->bindParam(':newsarticle', $slug);
$stmt->execute();
echo 'Successfully saved article!';
} catch(PDOException $e){
echo "There was an error: ".$e->getMessage();
exit();
}
But I am not sure how to achieve what I want.

Looks like you have the headline slug, which is what you want anyway. right? So let's just wrap that in our function create_url_slug()
create_url_slug(GetSQLValueString($_POST['headlineslug'], "text"))
Should be all you need.
Let's do it using PDO as the gentlemen above suggested!
try{
$conn = new PDO('mysql:host=host;dbname=yourdatabasename', 'user', 'pass');
$slug = create_url_slug($_POST['newsarticle']);
//we'll use a prepared statement, which will sanitize our strings for us!
$stmt = $conn->prepare('INSERT INTO news (articledate, newsheadline, headlineslug, newsarticle) VALUES (:articledate, :newsheadline, :headlineslug, :newsarticle)');
$stmt->bindParam(':articledate', $_POST['articledate']);
$stmt->bindParam(':newsheadline', $_POST['newsheadline']);
$stmt->bindParam(':headlineslug', $_POST['headlineslug']);
$stmt->bindParam(':newsarticle', $slug);
$stmt->execute();
echo 'Successfully saved article!';
} catch(PDOException $e){
echo "There was an error: ".$e->getMessage();
exit();
}
Resources
PDO connection
PDO Prepared Statements

Related

Mysqli Prepared statement usage with AJAX POST to PHP file

My question is, how efficient are PHP Mysqli prepared statements? From what I have understand from basic reading, prepared statements 1) help in security using bound inputs 2) speed up and 'reduce' data sent to the server by somewhat 'pre-packaging' or 'preparing' the sql query to an extent, and once data is available, it just attaches the data to the prepared statement and executes it. This also helps on 'repeated' use of the same statement when inserting the same data (different values) repeatedly, because the statement is prepared only once.
Now, I am building a website with several functionalities, and all (or most) of them use JQuery and AJAX to get obtain user input, do some checks (either in the JS/JQ or in PHP), Send the data to a PHP file PHP_AJAX_Handler.php specified in the AJAX URL. The PHP file prepares the SQL statemtns to insert data into database, then return JSON success/failure messages. For example, most of my features/functionality are programmed as follows; below is one file which I am using to 1) check for existing continent-country pair, and 2) insert the new continent-country pair.
HTML:
<input type='text' id='continent'>
<input type='text' id='country'>
<button id='btn1'></button>
<p id='p1'></p>
<p id='p2'></p>
<p id='p3'></p>
JQuery:
$("#btn1")click(function(){
var Cntt = $("#continent").val();
var Ctry = $("#country").val();
$.post("PHP_AJAX_Handler.php",{CN:cntt,CT:ctry},function(DAT)
{ var RET_j = json.PARSE(dat);
if(RET_j.PASS=='FAIL')
{ $('#p1').html(RET_j.PASS);
$('#p2').html(RET_j.MSG1);
}
if(RET_j.PASS=='OKAY')
{ $('#p1').html(RET_j.PASS);
$('#p3').html(RET_j.MSG2);
} }
);
});
PHP_AJAX_Handler.php
<?PHP
session_start();
if( (isset($_POST['CT'])) && (isset($_POST['CN'])))
{ require_once ("golin_2.php");
$CN = $_POST['CN'];
$CT = $_POST['CT'];
$ER = "";
$CONN = mysqli_connect($SERVER, $USER, $PASS, $DBNAME);
If($CONN == FALSE)
{ $ER = $ER . "Err: Conn Could not connect to Databse ".mysqli_connect_errno().' '.mysqli_connect_error();
}
else
{ $SQL_1 = "SELECT * FROM sailors.continental_regions WHERE CONTINENT = ? AND COUNTRY = ?";
if(!($STMT_1 = mysqli_stmt_init($CONN)))
{ $ER = $ER . "Err: Stmt Prepare Failed";
}
else
{ if(!mysqli_stmt_prepare($STMT_1, $SQL_1)) ///FIRST SET of prepared statement lines
{ $ER = $ER . "Err: Stmt Prepare Failed";
}
else
{ if(!mysqli_stmt_bind_param($STMT_1,"ss",$CN, $CT))
{ $ER = $ER . "Err: Stmt Prepare Failed";
}
else
{ if(!(mysqli_stmt_execute($STMT_1)))
{ $ER = $ER . "Err: Stmt_1 Execute Failed";
}
else
{ $RES_1 = mysqli_stmt_get_result($STMT_1);
$NUMROWS_1 = mysqli_num_rows($RES_1);
if($NUMROWS_1>0)
{ $ER = $ER . "Err: duplicate '$CN' '$CT' pair";
}
if($NUMROWS_1==0)
{ $SQL_2 = "INSERT INTO DB.continental_regions (CONTINENT,COUNTRY) values (?, ?)";
if(!($STMT_2=(mysqli_stmt_init($CONN))))
{ $ER = $ER . "Err: Init2 failed";
}
else
{ if(!mysqli_stmt_prepare($STMT_2, $SQL_2)) ///SECOND SET of prepared statement lines
{ $ER = $ER . "Err: Prep2 failed".mysqli_error($CONN);
}
else
{ if(!mysqli_stmt_bind_param($STMT_2,"ss",$CN, $CT))
{ $ER = $ER . "Err: Bind2 failed";
}
else
{
if(!(mysqli_stmt_execute($STMT_2)))
{ $ER = $ER . "Err: Exec failed";
}
else
{ $arr['PASS'] = 'OK';
}
}
}
}
}
}
}
}
}
mysqli_free_result($RES_1);
mysqli_stmt_close($STMT_1);
mysqli_stmt_close($STMT_2);
mysqli_close($CONN);
}
if($ER!=="")
{ $arr['MSG'] = $ER;
$arr['PASS'] = 'FAIL';
}
if($arr['PASS']=="OK")
{ $arr['MSG2'] = "Insert Success";
}
echo json_encode($arr);
}
else
{ header("location: ../Error_Fail.php");
}
?>
As you can see, the PHP file is turning out to be pretty long. There is one set of prepare statements to check if the CC pair exists already in table, then another to insert the CC pair.
From what I see, for each AJAX request to add a new pair of values, the mysqli statements are prepared over again. Then again for the next request, and so on. I imagine this is creating a lot of overhead and data to the server just to achieve Security. Is this true for other people developing web applications with AJAX-POST-PHP? to me it seems unavoidable that for each prepare, values can only be inserted one time? How to get around to preparing this statement once, and only doing repeat executes whence data is available? I can't seem to get my head around the 'efficiency' factor of prepared statements..
Thanks.. would appreciate some advise from some seasoned programmers out there..
You said:
As you can see, the PHP file is turning out to be pretty long.
That is true, but that is not the fault of prepared statements. You must have been learning PHP development from a poorly written tutorial. This code does not need to be so long. In fact, it can be severely shortened.
Just fixing your existing code made it much more readable. I used OOP-style mysqli and I removed all these if statements. You should enable error reporting instead.
<?php
session_start();
if (isset($_POST['CT'],$_POST['CN'])) {
require_once "golin_2.php";
$CN = $_POST['CN'];
$CT = $_POST['CT'];
$ER = "";
$arr = [
'PASS' => "OK",
'MSG2' => "Insert Success",
]; // successful state should be the default outcome
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$CONN = new mysqli($SERVER, $USER, $PASS, $DBNAME);
$CONN->set_charset('utf8mb4'); // always set the charset
// To check existance of data in database we use COUNT(*)
$stmt = $CONN->prepare("SELECT COUNT(*) FROM sailors.continental_regions WHERE CONTINENT = ? AND COUNTRY = ?");
$stmt->bind_param("ss", $CN, $CT);
$stmt->execute();
$NUMROWS = $stmt->get_result()->fetch_row()[0];
if ($NUMROWS) {
$ER .= "Err: duplicate '$CN' '$CT' pair";
} else {
$stmt = $CONN->prepare("INSERT INTO DB.continental_regions (CONTINENT,COUNTRY) values (?, ?)");
$stmt->bind_param("ss", $CN, $CT);
$stmt->execute();
}
if ($ER) {
$arr = [
'PASS' => "FAIL",
'MSG' => $ER,
];
}
echo json_encode($arr);
} else {
header("location: ../Error_Fail.php");
}
If you have a composite UNIQUE key on these two columns in your table then you can remove the select statement. Also, you should clean up your response preparation. The successful state should be the default and it should be replaced with the error message only if something went wrong.
In this example, I removed one SQL statement. The whole thing is now much simpler.
<?php
define('DUPLICATE_KEY', 1062);
session_start();
if (isset($_POST['CT'],$_POST['CN'])) {
require_once "golin_2.php";
$CN = $_POST['CN'];
$CT = $_POST['CT'];
$arr = [
'PASS' => "OK",
'MSG2' => "Insert Success",
]; // successful state should be the default outcome
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$CONN = new mysqli($SERVER, $USER, $PASS, $DBNAME);
$CONN->set_charset('utf8mb4'); // always set the charset
try {
$stmt = $CONN->prepare("INSERT INTO continental_regions (CONTINENT,COUNTRY) values (?, ?)");
$stmt->bind_param("ss", $CN, $CT);
$stmt->execute();
} catch (mysqli_sql_exception $e) {
if ($e->getCode() !== DUPLICATE_KEY) {
// if it failed for any other reason than duplicate key rethrow the exception
throw $e;
}
// if SQL failed due to duplicate entry then set the error message
$arr = [
'PASS' => "FAIL",
'MSG' => "Err: duplicate '$CN' '$CT' pair",
];
}
echo json_encode($arr);
} else {
header("location: ../Error_Fail.php");
}
Regarding performance.
There is no problem with performance in this example and prepared statements don't improve or degrade the performance. I assume you are trying to compare the performance to static SQL queries, but in your simple example there should be no difference at all. Prepared statements can make your code faster compared to static queries when you need to execute the same SQL many times.
If you find writing the 3 lines of code each time too much, then you can create a wrapper function that will reduce it for you to a single function call. In fairness you should avoid using mysqli on its own. Either switch to PDO or use some kind of abstraction library around mysqli.

How to put an array to DB (php, pdo)?

Need your help. Got some problems with putting an array's data to DB via php pdo. I'm amateur frond-end dev. that's quite far from backend, so there are no people except you to help me! In the DB table I've got some columns, among others "myActions" - need to put all the data from my inputs with the names name="action[]" to this column row by row.
In html code I have inputs' names like that:
<div id="field">
<input autocomplete="off" class="input form-control" id="field1" name="action[]" type="text" placeholder="Type something" data-items="8"/>
<button id="b1" class="btn add-more" type="button">+</button>
</div>
In php file :
<?php
$incident_number = $_POST['incident_number'];
$incident_type = $_POST['incident_type'];
$incident_subject = $_POST['incident_subject'];
$incident_time = $_POST['incident_time'];
$status = $_POST['status'];
$wasdone = $_POST['action'];
try {
/*** connect to SQLite database ***/
$dbh = new PDO("sqlite:myDB2");
/*** echo a message saying we have connected ***/
//echo 'Connected to database<br />';
/*** The SQL SELECT statement ***/
$Log = date(DATE_RFC2822)." Creation".PHP_EOL;
//echo $Log;
$sql = "INSERT INTO myData
(incident_number,incident_type,incident_subject,incident_time,status) values
(:incident_number,:incident_type,:incident_subject,:incident_time,:status);"
$query = $dbh->prepare($sql);
$query->bindParam(':incident_number', $incident_number);
$query->bindParam(':incident_type', $incident_type);
$query->bindParam(':incident_subject', $incident_subject);
$query->bindParam(':incident_time', $incident_time);
$query->bindParam(':status', $status);
//$query->bindParam(':Log', $Log, PDO::PARAM_STR);
$query->execute();
//$query->execute(array(':NameImp'=>$NameImp));
// Close file db connection
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
try {
/*** connect to SQLite database ***/
$dbh = new PDO("sqlite:myDB2");
/*** echo a message saying we have connected ***/
//echo 'Connected to database<br />';
/*** The SQL SELECT statement ***/
$Log = date(DATE_RFC2822)." Creation".PHP_EOL;
//echo $Log;
$sql = "INSERT INTO myActions (action) values (:wasdone);";
foreach ($wasdone as $key => &$value) { //pass $value as a reference to the array item
$query->bindParam($key, $value); // bind the variable to the statement
}
//$query->bindParam(':Log', $Log, PDO::PARAM_STR);
$query->execute();
//$query->execute(array(':NameImp'=>$NameImp));
// Close file db connection
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
You could use PHP's implode() function which joins the elements of an array into a single string, delimited by a custom substring.
You can later use explode() to turn your string back into a workable array when you query it from the database.
Note: while this is a quick solution that could work for your use case, if the arrays in the dataset become too large or your project increases in complexity, you should look into data normalization and make additional tables for your actions array elements as good data management practice.

PHP PDO Querying code from database doesn't show, only in source

I'm using PDO to query some data from my database but I have a section with raw php code that doesn't show up, only in the source as if it's trying to run.
I have the slashes stripped and I have it echoed under pre/code tags so I'm wondering as to why it won't show on the page.
Database
id name(VARCHAR) code (LONGTEXT)
1 test <?php echo /'hello world/'; ?>
PHP File
<?php
try {
$db = new PDO('mysql:host=localhost;dbname=$dbname;charset=utf8', '$username', '$password');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$stmt = $db->prepare('SELECT name, codeOne FROM table_one WHERE id = :id');
$stmt->bindParam(':id', '1');
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo $row['name'] . '<pre><code>'. stripslashes($row['codeOne']) .'</code></pre>';
}
} catch(PDOException $e) {
return $e->getMessage();
};
?>
What Everyone Sees
test
View Source
test<pre><code><?php echo "Hello";?></code></pre>
Well just use htmlspecialchars() to encode your string, e.g.
echo htmlspecialchars('<?php echo "Hello";?>');
What you see:
<?php echo "Hello";?>
Source code:
<?php echo "Hello";?>
OR if you want to be really fancy you could use: highlight_string(), which also gives some nice color to your string:
echo highlight_string('<?php echo "Hello";?>', TRUE);

Update query not working using PDO

I tried updating my data like so but it doesn't work
<?php
require("config.inc.php");//this piece of code us for authentication and it works fine.
if(!empty($_POST))
{
/**
the values below in the POST are valid not empty values
**/
$shell = $_POST['shell'];
$reporter = $_POST['reporter'];
//query
$query = "UPDATE `shellingdb`
SET `likes` = `likes` + 1
WHERE `shell` = :shell AND `reporter` = :reporter";
try {
$query_params = array(':shell' => $_POST['shell'], ':reporter' => $_POST['reporter']);//Updates likes
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
$affected = $stmt->rowCount();//counts the number of affected rows during the update query
if($affected > 0)
{
$response["success"] = 1;
$response["message"] = "Updated! this number of rows were affected".$affected;
echo json_encode($response);
}else
{
$response["success"] = 2;
$response["message"] = "Not Updated! huh!".$affected;
echo json_encode($response);
}
}
catch (Exception $ex) {
$response["success"] = 0;
$response["message"] = "Database Error!".$ex->getMessage();
die(json_encode($response));
}
}
?>
the config.inc.php
<?php
// These variables define the connection information for your MySQL database
$username = "xmnj3jh0jhtheu_14265914";
$password = "jhikjskjiavethew";
$host = "sqlkjnlkkjlk101.x3kuhiu0lkj.us";
$dbname = "x3lnklj0u_1426jbkb5914_gbabbjkhjajhlert";
// UTF-8 is a character encoding scheme that allows you to conveniently store
// a wide varienty of special characters, like � or �, in your database.
// By passing the following $options array to the database connection code we
// are telling the MySQL server that we want to communicate with it using UTF-8
// See Wikipedia for more information on UTF-8:
// http://en.wikipedia.org/wiki/UTF-8
$options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
// A try/catch statement is a common method of error handling in object oriented code.
// First, PHP executes the code within the try block. If at any time it encounters an
// error while executing that code, it stops immediately and jumps down to the
// catch block. For more detailed information on exceptions and try/catch blocks:
// http://us2.php.net/manual/en/language.exceptions.php
try
{
// This statement opens a connection to your database using the PDO library
// PDO is designed to provide a flexible interface between PHP and many
// different types of database servers. For more information on PDO:
// http://us2.php.net/manual/en/class.pdo.php
$db = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options);
}
catch(PDOException $ex)
{
// If an error occurs while opening a connection to your database, it will
// be trapped here. The script will output an error and stop executing.
// Note: On a production website, you should not output $ex->getMessage().
// It may provide an attacker with helpful information about your code
// (like your database username and password).
die("Failed to connect to the database: " . $ex->getMessage());
}
// This statement configures PDO to throw an exception when it encounters
// an error. This allows us to use try/catch blocks to trap database errors.
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// This statement configures PDO to return database rows from your database using an associative
// array. This means the array will have string indexes, where the string value
// represents the name of the column in your database.
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
// This block of code is used to undo magic quotes. Magic quotes are a terrible
// feature that was removed from PHP as of PHP 5.4. However, older installations
// of PHP may still have magic quotes enabled and this code is necessary to
// prevent them from causing problems. For more information on magic quotes:
// http://php.net/manual/en/security.magicquotes.php
if(function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc())
{
function undo_magic_quotes_gpc(&$array)
{
foreach($array as &$value)
{
if(is_array($value))
{
undo_magic_quotes_gpc($value);
}
else
{
$value = stripslashes($value);
}
}
}
undo_magic_quotes_gpc($_POST);
undo_magic_quotes_gpc($_GET);
undo_magic_quotes_gpc($_COOKIE);
}
// This tells the web browser that your content is encoded using UTF-8
// and that it should submit content back to you using UTF-8
header('Content-Type: text/html; charset=utf-8');
// This initializes a session. Sessions are used to store information about
// a visitor from one web page visit to the next. Unlike a cookie, the information is
// stored on the server-side and cannot be modified by the visitor. However,
// note that in most cases sessions do still use cookies and require the visitor
// to have cookies enabled. For more information about sessions:
// http://us.php.net/manual/en/book.session.php
session_start();
// Note that it is a good practice to NOT end your PHP files with a closing PHP tag.
// This prevents trailing newlines on the file from being included in your output,
// which can cause problems with redirecting users.
?>
don't know what's wrong and it gives no error it goes into the else statement, meaning the values were not updated. i tried the same code in sqlfiddle and it works but not in my PhpMyAdmin.
I know the updated value is supposed to be passed into the $query_params but am incrementing the value of likes each time it is run, and am not sure how to do that in the $query_params unless i use a seperate query to get the numberof likes and then increament it but that could be costly.
Query without PDO still it does not work this time it give update unsuccessful
<?php
$username = "x3jbhiukhkj0u426jbhjnbvh591mbhb4";
$password = "savjiuejbiuhilkmthljiew";
$host = "sqlnjhbjhnkjjjhbj";
$dbname = "x3hjbh0ukjioiuhgbjhvhgvh";
$shell = "Rustig";
$reporter = "davies";
//query
$query = "UPDATE `shellingdb`
SET `favs` = 1
WHERE `shell` = 'Rustig'";
$link = mysql_connect($host, $username, $password);
if (!$link)
{
die('Could not connect: ' . mysql_error());
}else
{
echo 'Connected successfully';
$db_selected = mysql_select_db($dbname, $link);
if (!$db_selected)
{
die ('Can\'t use foo : ' . mysql_error());
}else
{
echo 'Connected to database successfully';
if(empty($_POST))
{
$retval = mysql_query( $query, $link )or die(mysql_error($link));;
if(! $retval )
{
die('Could not query database: ' . mysql_error());
}else
{
if(mysql_affected_rows() > 0)
{
echo "Updated data successfully\n";
}else
{
//echo "shell=".$shell." reporter=".$reporter';
echo "Updated data Unsuccessfully\n";
}
}
}
}
}
mysql_close($link);
?>
The below is the output of the PDOStatement::debugDumpParams(); for the first php syntax
SQL: [124] UPDATE shellingdb SET likes = likes + 1 WHERE shell = :shell AND reporter >= :reporter Params: 2 Key: Name: [6] :shell paramno=-1 name=[6] ":shell" is_param=1 param_type=2 Key: Name: [9] :reporter paramno=-1 name=[9] ":reporter" is_param=1 param_type=2
I used bindParam. bindParam is a method on PDOStatement.
Try:
<?php
require("config.inc.php");//this piece of code us for authentication and it works fine.
if(isset($_POST))
{
/**
the values below in the POST are valid not empty values
**/
$shell = $_POST['shell'];
$reporter = $_POST['reporter'];
//query
$query = "UPDATE `shellingdb`
SET `likes` = `likes` + 1
WHERE `shell` = :shell AND `reporter` = :reporter";
try {
$stmt = $db->prepare($query);
$stmt->bindParam(":shell", $shell);
$stmt->bindParam(":reporter", $reporter);
$stmt->execute();
$affected = $stmt->rowCount();//counts the number of affected rows during the update query
if($affected > 0)
{
$response["success"] = 1;
$response["message"] = "Updated! this number of rows were affected".$affected;
echo json_encode($response);
}else
{
$response["success"] = 2;
$response["message"] = "Not Updated! huh!".$affected;
echo json_encode($response);
}
}
catch (Exception $ex) {
$response["success"] = 0;
$response["message"] = "Database Error!".$ex->getMessage();
die(json_encode($response));
}
}
?>
some how, after long hours of try and error(Brut Forcing) this finally worked
$query = "UPDATE `shellingdb` SET `likes`=`likes`+1 WHERE `shell` = :shell AND `reporter` = :reporter";
Thanks all those who tried to help. :)

Error adding order: SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens

Hey guys I would love your help in regards to the code below, I am quite new to php and and sql, and I am trying to blind these values for a order check out process. There are multiple pages that I need to capture the information from....
I have looked over this code for hours and I am unable to find where I am going wrong...
This may be because I am really not sure where I need to be looking to fix this problem. Any help or advice would help so much!
function writeOrderToDatabase(){
// open database connection
include 'includes/connection.php';
// store order date in Australian format for printouts etc
$_SESSION['orderDate'] = date('d-m-Y');
try{
// create our sql insert orders statement
$sql = "INSERT INTO orders SET orderNbr=: orderNbr,custNbr=:custNbr,orderDate=:orderDate, OrderNetValue=:OrderNetValue,deliverTo = :deliverTo,
deliveryAddress1 = :deliveryAddress1, deliveryAddress2 = :deliveryAddress2, deliverySuburb = :deliverySuburb,
deliveryState = :deliveryState, deliveryPostCode = :deliveryPostCode, deliverySuburb = :deliverySuburb, deliveryState = :state, deliveryPostCode = :deliveryPostCode, deliveryInstructions = :deliveryInstructions, shippingValue=:shippingValue,
paymentType=:paymentType, paymentRef=:paymentRef;";
// prepare the statement
$statement = $pdo->prepare($sql);
$orderNbr = 0;
// bind the values
$statement->bindValue(':orderDate', date('Y-m-d'));
$statement->bindValue(':custNbr', $_SESSION['custNbr']);
$statement->bindValue(':dispatchDate', $_SESSION['dispatchDate']);
$statement->bindValue(':deliveryDate', $_SESSION['deliveryDate']);
$statement->bindValue(':OrderNetValue', $_SESSION['OrderNetValue']);
$statement->bindValue(':deliverTo', $_SESSION['deliverTo']);
$statement->bindValue(':deliveryAddress1', $_SESSION['deliveryAddress1']);
$statement->bindValue(':deliveryAddress2', $_SESSION['deliveryAddress2']);
$statement->bindValue(':deliverySuburb', $_SESSION['deliverySuburb']);
$statement->bindValue(':deliveryState', $_SESSION['deliveryState']);
$statement->bindValue(':deliveryPostCode', $_SESSION['deliveryPostCode']);
$statement->bindValue(':deliveryInstructions', $_SESSION['deliveryInstructions']);
$statement->bindValue(':shippingValue', $_SESSION['shippingValue']);
$statement->bindValue(':paymentType', $_SESSION['paymentType']);
$statement->bindValue(':paymentRef', $_SESSION['paymentRef']);
$statement->bindValue(':sellingPrice', $_SESSION['sellingPrice']);
$statement->bindValue(':newQtyOnHand', $_SESSION['newQtyOnHand']);
// execute the statement
$success = $statement->execute();
} // end try
catch (PDOException $e) {
echo 'Error adding order: ' . $e->getMessage();
exit();
} // end catch
// test the result and get order nbr just created or display appropriate message
if ($success) {
echo $sql = 'SELECT orderNbr FROM orders ORDER BY orderNbr';
foreach ($conn->query($sql) as $row) {
print $row['orderNbr'] . "\t";
}
}
else {
die("<p>Unable to retreive Order Nbr </p>");
}
// read cart and insert orderedItem record(s) and update stock on hand in product records
foreach($_SESSION['cart'] as $prodNbr => $value) {
// store required details in variables
$qtyOrdered = $_SESSION['cart'][$prodNbr]['qtyOrdered'];
$qtyOnHand = $_SESSION['cart'][$prodNbr]['qtyOnHand'];
$sellingPrice = $_SESSION['cart'][$prodNbr]['price'];
try {
// create orderedItem table sql insert statement
$sql = "INSERT INTO orderedItem SET orderNbr=:custNbr,prodNbr=: prodNbr, qtyOrdered=:qtyOrdered,sellingPrice = :sellingPrice;";
} // end try
catch (PDOException $e) {
echo 'Error adding orderedItem: ' . $e->getMessage();
exit();
} // end catch
// test the result and display appropriate message
if (!$success) {
die("<p>Unable to execute the orderedItem table insert</p>");
}
// create new quantity on hand value for the product record
$newQtyOnHand = $qtyOnHand - $qtyOrdered;
try {
// create product table sql update statement
$sql="UPDATE product SET prodNbr= :prodNbr,prodName= :prodName,price= :price,qtyOnHand= :qtyOnHand,description= :description, photo= :photo,thumbNail= :thumbNail ,suppCode= :suppCode ;";
} // end try
catch (PDOException $e) {
echo 'Error updating product qtyOnHand: ' . $e->getMessage();
exit();
} // end catch
// test the result and display appropriate message
if (!$success) {
die("<p>Unable to execute the product table update</p>");
}
} // end of foreach
} // end of function
Here:
$statement->bindValue(':dispatchDate', $_SESSION['dispatchDate']);
$statement->bindValue(':deliveryDate', $_SESSION['deliveryDate']);
$statement->bindValue(':sellingPrice', $_SESSION['sellingPrice']);
$statement->bindValue(':newQtyOnHand', $_SESSION['newQtyOnHand']);
These bind don't exist in the query.
Besides,
orderNbr=: orderNbr
should be
orderNbr = :orderNbr
Please note you don't bind it either.
Also, you're having twice the following parameters in the query:
deliveryState = :state
deliveryState = :deliveryState
deliveryPostCode = :deliveryPostCode
deliveryPostCode = :deliveryPostCode
You have a bad placeholder token first off: orderNbr=: orderNbr needs to be orderNbr=:orderNbr; Note the whitspace. Secondly, even if that was correct i dont see you binding :orderNbr anywhere.
I would think though that the order number should be an autoincrement integer field, and if that is the case you should not include it in your insert.

Categories