CRUD PDO working on XAMPP but not on live server - php

I am trying to update and add posts to a custom coded blog using PDO.
I can read and delete fine, but adding posts or editing them does not work on the live server.
It works fine on XAMPP...
I have made sure the PDO_mysql extension is enable on my database.
At a loss as to where the problem is?
My EDIT POST code looks like:
<?php
//if form has been submitted process it
if(isset($_POST['submit'])){
//collect form data
extract($_POST);
//very basic validation
if($postID ==''){
$error[] = 'This post is missing a valid id!.';
}
if($postTitle ==''){
$error[] = 'Please enter the title.';
}
if($postDesc ==''){
$error[] = 'Please enter the description.';
}
if($postCont ==''){
$error[] = 'Please enter the content.';
}
if(!isset($error)){
try {
$postSlug = slug($postTitle);
//insert into database
$stmt = $db->prepare('UPDATE blog_posts_seo SET postTitle = :postTitle, postSlug = :postSlug, postDesc = :postDesc, postCont = :postCont WHERE postID = :postID') ;
$stmt->execute(array(
':postTitle' => $postTitle,
':postSlug' => $postSlug,
':postDesc' => $postDesc,
':postCont' => $postCont,
':postID' => $postID
));
//delete all items with the current postID
$stmt = $db->prepare('DELETE FROM blog_post_cats WHERE postID = :postID');
$stmt->execute(array(':postID' => $postID));
if(is_array($catID)){
foreach($_POST['catID'] as $catID){
$stmt = $db->prepare('INSERT INTO blog_post_cats (postID,catID)VALUES(:postID,:catID)');
$stmt->execute(array(
':postID' => $postID,
':catID' => $catID
));
}
}
//redirect to index page
header('Location: index.php?action=updated');
exit;
} catch(PDOException $e) {
echo $e->getMessage();
}
}
}
?>
<?php
//check for any errors
if(isset($error)){
foreach($error as $error){
echo $error.'<br />';
}
}
try {
$stmt = $db->prepare('SELECT postID, postTitle, postDesc, postCont FROM blog_posts_seo WHERE postID = :postID') ;
$stmt->execute(array(':postID' => $_GET['id']));
$row = $stmt->fetch();
} catch(PDOException $e) {
echo $e->getMessage();
}
?>
and my ADD POST code is
<?php
//if form has been submitted process it
if(isset($_POST['submit'])){
//collect form data
extract($_POST);
//very basic validation
if($postTitle ==''){
$error[] = 'Please enter the title.';
}
if($postDesc ==''){
$error[] = 'Please enter the description.';
}
if($postCont ==''){
$error[] = 'Please enter the content.';
}
if(!isset($error)){
try {
$postSlug = slug($postTitle);
//insert into database
$stmt = $db->prepare('INSERT INTO blog_posts_seo (postTitle,postSlug,postDesc,postCont,postDate) VALUES (:postTitle, :postSlug, :postDesc, :postCont, :postDate)') ;
$stmt->execute(array(
':postTitle' => $postTitle,
':postSlug' => $postSlug,
':postDesc' => $postDesc,
':postCont' => $postCont,
':postDate' => date('Y-m-d H:i:s')
));
$postID = $db->lastInsertId();
//redirect to index page
header('Location: index.php?action=added');
exit;
} catch(PDOException $e) {
echo $e->getMessage();
}
}
}
//check for any errors
if(isset($error)){
foreach($error as $error){
echo '<p class="error">'.$error.'</p>';
}
}
?>
Is there anything I should check on the MySQL DB or is there something in my code that is preventing my CRUD from working in a live environment?
As said before, the exact same code (other than the config file) is working on XAMPP.

It might be a privilege error on the server side, since you cannot edit (write) the files or create new ones. I suggest checking the users privileges on the database.
When you say it does not work, what does it return to you?
Have you tried a var_dump or echo if it works as a query, or it doesn't allow the query to execute at all?
UPDATE:
Last but not least, the configuration file, as suggested by the comments, should be the main problem. It really depends how you have configured the files to work on the server. Check includes and such.

The problem is how you insert DATE.
That's the only difference between Insert, update and delete.
The best is not to add it at all via PHP and since you are adding the current time you can let the database do it for you.
':postDate' => date('Y-m-d H:i:s') <- let the db do it for you as default parameter set to now() or just use TIMESTAMP probably the best.

Related

Unable to get Table Name using variable string MYSQL Error

if ($_GET['category'] == "ebooks")
{ $tableName = $smallsubcodewithoutspace.'_ebooks';
$sectionTitle = "Ebook";
}
elseif ($_GET['category'] == "syllabus")
{ $tableName = $smallsubcodewithoutspace.'_syllabus';
$sectionTitle = "Syllabus";
}
elseif ($_GET['category'] == "pnotes")
{ $tableName = $smallsubcodewithoutspace.'_pnotes';
$sectionTitle = "Practical Note";
}
elseif ($_GET['category'] == "assignments")
{ $tableName = $smallsubcodewithoutspace.'_assignments';
$sectionTitle = "Assignment";
}
elseif ($_GET['category'] == "tnotes")
{ $tableName = $smallsubcodewithoutspace.'_tnotes';
$sectionTitle = "Theory Notes";
}
//if form has been submitted process it
if(isset($_POST['submit'])){
$_POST = array_map( 'stripslashes', $_POST );
//collect form data
extract($_POST);
//very basic validation
if($contentTitle ==''){
$error[] = 'Please enter the Content Title !';
}
if($contentLink ==''){
$error[] = "Please enter the Content Link !";
}
if(!isset($error)){
try {
//insert into database
$stmt = $db->prepare("INSERT INTO `$tableName` (contentTitle,contentLink,contentAuthor) VALUES (:contentTitle, :contentLink, :contentAuthor)") ;
$stmt->execute(array(
':contentTitle' => $contentTitle,
':contentLink' => $contentLink,
':contentAuthor' => $contentAuthor
));
//redirect to index page
header('Location: add-content.php?notallowed=true');
exit;
} catch(PDOException $e) {
echo $e->getMessage();
}
}
}
//check for any errors
if(isset($error)){
foreach($error as $error){
echo '<div align="center" class="alertpk"><div class="alert alert-warning" role="alert">'.$error.'</div></div>';
}
}
Actually, problem started when I tried inserting Table name with variable. Tables exist in database. total 5 databases are there in which I will insert data according to users selection, but when form executed, a error is thrown saying:
SQLstate[42000]: SYNTAX ERROR OR ACCESS VIOLATION 1103, INCORRECT TABLE NAME ' '
The error INCORRECT TABLE NAME '' error means you don't have a value in $tableName. Your $_GET['category'] is not picking up a recognized value or the extract($_POST) is changing $tableName to an empty value.
I got the solution, I shifted tableVariables section inside try and its now working.
var dump your variable, post to see what value comes up.

php include not working on host server but works on local (xampp) server

I cannot resolve why what works locally fails at the host server. It connects to the database, retrieves and displays data, but it fails to retrieve the data and include the form. Hopefully, I have included enough code.
First the data is retrieved and displayed:
/*------------------- DISPLAY ACCESSORIES ------------------*/
if(isset($_GET['table']) && $_GET['table'] === "accessories")
{
$table = 'accessories';
include '../includes/dbconnect.php';
try {
$result = $db->query("SELECT * FROM $table");
while($row = $result->fetch(PDO::FETCH_ASSOC)){
$accessories[] = array(
'id' => $row['id'],
'buy_link' => $row['buy_link'],
'img' => $row['img'],
'item_number' => $row['item_number'],
'name' => $row['name'],
'description' => $row['description'],
'laser_series' => $row['laser_series'],
'laser_model' => $row['laser_model'],
'quantity' => $row['quantity'],
'price' => $row['price'],
);
}
}
catch (PDOException $e)
{
$error = 'Error fetching data.' . $e->getMessage();
include 'error.html.php';
exit();
}
try {
$sql2 = 'DESCRIBE accessories';
$s2= $db->prepare($sql2);
$s2->execute();
$table_fields = $s2->fetchAll(PDO::FETCH_COLUMN);
}
catch (PDOException $e)
{
$error = 'Error fetching data from database.';
include 'error.html.php';
exit();
}
// Close database connection
$db = null;
// Display data on included page
include 'display-accessories.html.php';
exit();
}
Then, in the row the user wishes to edit, he clicks the edit button. Here's that html:
<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="post">
<input type="hidden" name="id" value="<?php htmlout($accessory['id']); ?>">
<button class="btn btn-default btn-sm" type="submit" name="action" value="edit_accessories">Edit</button>
</form>
Clicking the edit button triggers this php, which fails (not locally). It does not include the file (the path is correct; in the same folder).
/*------------------- EDIT ACCESSORIES ------------------*/
if(isset($_POST['action']) && $_POST['action'] === "edit_accessories")
{
// Assign name of table being queried to variable
$table = 'accessories';
// Sanitize posted data
$id = sanitize($_POST['id']);
// Connect to database
include '../includes/dbconnect.php';
try {
$sql = "SELECT * FROM $table WHERE id = :id";
$s = $db->prepare($sql);
$s->bindValue(':id', $id);
$s->execute();
}
catch (PDOException $e)
{
$error = 'Error fetching data.' . $e->getMessage();
include 'error.html.php';
exit();
}
// Store single row result in $item associative array
$item = $s->fetch(PDO::FETCH_ASSOC);
// Close database connection
$db = null;
// Display row content in form
include 'edit-accessories-form.html.php';
exit();
}
If anyone has any ideas why this does not work, I welcome your insight!
Just change the sentence:
FROM: '../includes/dbconnect.php';
TO: $_SERVER['DOCUMENT_ROOT'].'/includes/dbconnect.php';
In the server the path can't be write as '../' because there is a whole different server path configuration.

How to use inform users of form submission errors if header is used to redirect the user to another page

When the user submits the form, the form information is posted to a php file and the php file redirects the user straight away to the next webpage once the form is submitted by using the header function. I have already validated the form using HTML and Javascript however the PHP has validation in it so that any errors that get past the Javascript and HTML are identified and the user is notified, however this is not possible at the minute as the user is redirected before they are notified.
How would I identify the user if the PHP locates an error?
Is it necessary as will the only errors be by people who are intentionally trying to be malicious?
My code is:
<?php
header("location: (next webpage)");
if(isset($_POST['submit'])){
$data_missing = array();
if(empty($_POST['email_banned'])){
// Adds name to array
$data_missing[] = 'Email';
} else {
// Trim white space from the name and store the name
$email_banned = trim($_POST['email_banned']);
}
if(empty($_POST['notes'])){
// Adds name to array
$data_missing[] = 'Notes';
} else {
// Trim white space from the name and store the name
$notes = trim($_POST['notes']);
}
if(empty($data_missing)){
require_once('mysqli_connect.php');
$query = "INSERT INTO banned_emails (id, email_banned, created_on, notes) VALUES ( NULL, ?, NOW(), ?)";
$stmt = mysqli_prepare($dbc, $query);
//i Interger
//d Doubles
//s Everything Else
mysqli_stmt_bind_param($stmt, "ss", $email_banned, $notes);
mysqli_stmt_execute($stmt);
$affected_rows = mysqli_stmt_affected_rows($stmt);
if($affected_rows == 1){
echo 'Student Entered';
mysqli_stmt_close($stmt);
mysqli_close($dbc);
} else {
echo 'Error Occurred<br />';
echo mysqli_error();
mysqli_stmt_close($stmt);
mysqli_close($dbc);
}
} else {
echo 'You need to enter the following data<br />';
foreach($data_missing as $missing){
echo "$missing<br />";
}
}
}
?>
Thanks :)
You can use $_SESSION to store errors, and retrieve them later.
$_SESSION['errors'] = array('an error message', 'a second error message');
Then in the script the user has been redirected to :
while($err = array_shift($_SESSION['errors'])){
?>
<p class='p_error'><?=$err?></p>
<?php
}

PDO update two tables at once

I am trying to update two tables at once when form is submited.
http://pastebin.com/ctmaWWN8
Beside updating the article_cat table, I also need to update article_posts table.
In article_posts table I need to set cat to what ever I have typed in the form.
UPDATE article_posts SET cat=:cat WHERE cat=:cat
Something like that I guess, but I don't know how to combine them together!
Here is my PHP code:
if (isset($_POST['submit'])) {
$cat = $_POST['cat'];
$name = $_POST['name'];
$sqlInsert = 'UPDATE article_cat SET cat=:cat, name=:name WHERE id=:id';
$preparedStatement = $db->prepare($sqlInsert);
$preparedStatement->execute(array(':cat' => $cat, ':name' => $name, ':id' => $id));
if (empty($name)) {
// do something
echo'<div class="alert-box error"><span>error: </span>Categorys name field is Empty!</div>';
}
elseif (empty($cat)) {
echo'<div class="alert-box error"><span>error: </span>Categorys short name field is Empty!</div>';
}
else {
if ($preparedStatement->execute())
{
echo'<div class="alert-box success"><span>success: </span>Category Updated!</div>';
}
// If execution failed then ->
else
{
echo'<div class="alert-box error"><span>error: </span>Something went wrong while updating Category :/ ! Please try again.</div>';
}
}
}
Your code should become this and make sure you replace placeholder values in the second statement.
if (isset($_POST['submit'])) {
$cat = $_POST['cat'];
$name = $_POST['name'];
// first
$sqlInsert = 'UPDATE article_cat SET cat=:cat, name=:name WHERE id=:id';
$preparedStatement = $db->prepare($sqlInsert);
// second
$sqlInsert = 'UPDATE article_posts SET cat=:cat WHERE cat = :_cat';
$preparedStatement->execute(array(':cat' => $cat, ':name' => $name, ':id' => $id));
$preparedStatement->closeCursor();
if (empty($name)) {
echo'<div class="alert-box error"><span>error: </span>Categorys name field is Empty!</div>';
} elseif (empty($cat)) {
echo'<div class="alert-box error"><span>error: </span>Categorys short name field is Empty!</div>';
} else {
// second
$preparedStatement = $db->prepare($sqlInsert);
// second query statement
if ($preparedStatement->execute(array(':cat' => 'set-your-cat', ':_cat' => 'where-clause'))) {
$preparedStatement->closeCursor();
echo'<div class="alert-box success"><span>success: </span>Category Updated!</div>';
} else {
echo'<div class="alert-box error"><span>error: </span>Something went wrong while updating Category :/ ! Please try again.</div>';
}
}
}

MySQL parameter error

I'm trying to get my query to work for this PHP but I'm getting a "Invalid Parameter Number: number of bound variables do not match number of tokens" This is a snippet of my PHP:
<?php
/*
Our "config.inc.php" file connects to database every time we include or require
it within a php script. Since we want this script to add a new user to our db,
we will be talking with our database, and therefore,
let's require the connection to happen:
*/
require("configmob.php");
//if posted data is not empty
if (!empty($_POST)) {
//If the username or password is empty when the user submits
//the form, the page will die.
//Using die isn't a very good practice, you may want to look into
//displaying an error message within the form instead.
//We could also do front-end form validation from within our Android App,
//but it is good to have a have the back-end code do a double check.
if (empty($_POST['FirstName']) || empty($_POST['LastName'])) {
// Create some data that will be the JSON response
$response["success"] = 0;
$response["message"] = "Please Enter Both a First Name and a Last Name.";
//die will kill the page and not execute any code below, it will also
//display the parameter... in this case the JSON data our Android
//app will parse
die(json_encode($response));
}
//if the page hasn't died, we will check with our database to see if there is
//already a user with the username specificed in the form. ":user" is just
//a blank variable that we will change,Spot FROM Reservation WHERE Date = ':Date' AND Time = ':Time' AND Spot = ':Spot' ";
//now lets update what :user should be
$query = "Select * FROM Reservation WHERE Date = ':Date' AND TimeIn = ':TimeIn' AND Spot = ':Spot'";
$query_params = array(':Date' => $_POST['Date'] , ':TimeIn' => $_POST['Time'] , ':Spot' => $_POST['Spot']
);
//Now let's make run the query:
try {
// These two statements run the query against your database table.
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
// For testing, you could use a die and message.
//die("Failed to run query: " . $ex->getMessage());
//or just use this use this one to product JSON data:
$response["success"] = 0;
$response["message"] = $ex->getMessage();
die(json_encode($response));
}
//fetch is an array of returned data. If any data is returned,
//we know that the username is already in use, so we murder our
//page
$row = $stmt->fetch();
if ($row) {
// For testing, you could use a die and message.
//die("This username is already in use");
//You could comment out the above die and use this one:
$response["success"] = 0;
$response["message"] = "I'm sorry, this Reservation is already Taken";
die(json_encode($response));
}
//If we have made it here without dying, then we are in the clear to
//create a new user. Let's setup our new query to create a user.
//Again, to protect against sql injects, user tokens such as :user and :pass
$query = "INSERT INTO Reservation (Fname, Lname, Garno, Gname, EmpID, CustID, License, Floor, Spot, TimeIn, TimeOut, Date, Confirmation)
VALUES (:Fname, :Lname, :Garno, :Gname, :EmpID, :CustID, :License, :Floor, :Spot, :TimeIn, :TimeOut, :Date, :Confirmation) ";
//Again, we need to update our tokens with the actual data:
$query_params = array(
':Fname' => $_POST['FirstName'],
':Lname' => $_POST['LastName'],
':Gname' => $_POST['Garage'],
':Date' => $_POST['Date'],
':TimeIn' => $_POST['Time'],
':Spot' => $_POST['Spot'],
':Confirmation' => $_POST['Confirmation'],
);
//time to run our query, and create the user
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
// For testing, you could use a die and message.
//die("Failed to run query: " . $ex->getMessage());
//or just use this use this one:
$response["success"] = 0;
$response["message"] = $ex->getMessage();
die(json_encode($response));
}
//If we have made it this far without dying, we have successfully added
//a new user to our database. We could do a few things here, such as
//redirect to the login page. Instead we are going to echo out some
//json data that will be read by the Android application, which will login
//the user (or redirect to a different activity, I'm not sure yet..)
$response["success"] = 1;
$response["message"] = "Reservation Added!!";
echo json_encode($response);
//for a php webservice you could do a simple redirect and die.
//header("Location: loginmob.php");
//die("Redirecting to loginmob.php");
} else {
?>
<h1>Register</h1>
<form action="register.php" method="post">
Username:<br />
<input type="text" name="username" value="" />
<br /><br />
Password:<br />
<input type="password" name="password" value="" />
<br /><br />
<input type="submit" value="Register New User" />
</form>
<?php
}
?>
Thank you for the help!
This is what I found in your second statement:
$query = "Select * FROM Reservation WHERE Date = ':Date' AND TimeIn = ':Time' AND Spot = ':Spot'";
$query_params = array(':Date' => $_POST['Date'] , ':TimeIn' => $_POST['Time'] , ':Spot' => $_POST['Spot']
);
Your :TimeIn should be :Time like follows:
$query_params = array(':Date' => $_POST['Date'] , ':Time' => $_POST['Time'] , ':Spot' => $_POST['Spot']
Update:
Also in your second query you have :Garno missing, please try the following:
$query = "INSERT INTO Reservation (Fname, Lname, Garno, Gname, EmpID, CustID, License, Floor, Spot, TimeIn, TimeOut, Date, Confirmation)
VALUES (:Fname, :Lname, :Garno, :Gname, :EmpID, :CustID, :License, :Floor, :Spot, :TimeIn, :TimeOut, :Date, :Confirmation) ";
//Again, we need to update our tokens with the actual data:
$query_params = array(
':Fname' => $_POST['FirstName'],
':Lname' => $_POST['LastName'],
':Garno' => $_POST['Garno'], // Hopefully $_POST['Garno'] is what you want.
':EmpID' => $_POST['EmpID'], // Hopefully $_POST['EmpID'] is what you want.
':CustID' => $_POST['CustID'], // Hopefully $_POST['CustID'] is what you want.
':License' => $_POST['License'], // Hopefully $_POST['License'] is what you want.
':Floor' => $_POST['Floor'], // Hopefully $_POST['Floor'] is what you want.
':TimeOut' => $_POST['TimeOut'], // Hopefully $_POST['TimeOut'] is what you want.
':Gname' => $_POST['Garage'], // You don't need this, remove this.
':Date' => $_POST['Date'],
':TimeIn' => $_POST['Time'],
':Spot' => $_POST['Spot'],
':Confirmation' => $_POST['Confirmation'],
);

Categories