PDO update two tables at once - php

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>';
}
}
}

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.

Condition to Skip Input field if Empty

I'm trying to set a condition wherein if the 'filefield' is empty, it will skip the insert in DB as it is only an option and just proceed in inserting of 'name' and 'description' in the DB, which will never be empty.
<?php
include("connection.php");
if (isset($_POST['submit']))
{
$name = mysqli_real_escape_string($conn, $_POST['name']);
$description = mysqli_real_escape_string($conn, $_POST['description']);
if ($name == '' || $description == '' )
{
$error = 'ERROR: Please fill required fields!';
renderForm($name, $description);
}
else
{
if(!empty($_FILES['filefield'])){
if(isset($_FILES['filefield'])){
$file=$_FILES['filefield'];
$upload_directory='uploads/';
$ext_str = "gif,jpg,jpeg,mp3,tiff,bmp,doc,docx,ppt,pptx,txt,pdf";
$allowed_extensions=explode(',',$ext_str);
$ext = substr($file['name'], strrpos($file['name'], '.') + 1);
if (!in_array($ext, $allowed_extensions) )
{
echo '<script language="javascript">';
echo 'alert("file type not allowed for upload")';
echo '</script>';
exit();
}
$path=md5(microtime()).'.'.$ext;
if(move_uploaded_file($file['tmp_name'],$upload_directory.$path)){
$filefield = $_FILES["filefield"]["name"];
$path = $path."/".$filefield;
}
}
}
}
if (!empty($_FILES['filefield']) || !isset($_FILES['filefield'])) {
$query = "INSERT INTO `item`(`name`, `description`, `path`) VALUES ('$name','$description','$path')";
}
else {
$query = "INSERT INTO `item`(`name`, `description`) VALUES ('$name','$description')";
}
$result = mysqli_query($conn, $query);
if($result)
{
echo '<script language="javascript">';
echo 'alert("Success!")';
echo '</script>';
exit();
}
}
?>
I'm not sure how to proceed with the condition. Any help is highly appreciated.
First, close off all of your logic, including if(move_uploaded_file), so that the $query is competely outside of any conditionals. Then it's just a matters of checking whether the filefield was filled out or not. If it's not empty, your $query insert all three fields. If it is, your $query only inserts $name and $description.
This can be seen in the following (heavily cut-down) code:
/* Existing logic */
else
{
if (!empty($_FILES['filefield'])) {
if (isset($_FILES['filefield'])) {
if (move_uploaded_file($file['tmp_name'], $upload_directory.$path)) {
...
$path = $path."/".$filefield;
}
}
}
}
/* Modified logic */
if (!empty($_FILES['filefield']) || !isset($_FILES['filefield'])) {
$query = "INSERT INTO `item`(`name`, `description`, `path`) VALUES ('$name','$description','$path')";
}
else {
$query = "INSERT INTO `item`(`name`, `description`) VALUES ('$name','$description')";
}
$result = mysqli_query($conn, $query);

CRUD PDO working on XAMPP but not on live server

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.

Updating SQL with form and PHP. Values resetting to 0 on submit?

I am attempting to create a simple form that updates a row in a MYSQL database based on what ID the row is.
I have managed to get the form and updating values working, but for one of my variables I need its new value to be added to it, based on the values of two other variables. (So like $currPoints = $currPoints+$addPoints-$remPoints;).
The problem I am facing is that whenever the form is submitted, $currPoints is either resetting to 0, then adding and subtracting the other values, or the value of $cuurPoints isn't being found so that it cannot add to it's original value.
I am not sure where specifically in my code I am going wrong so I will paste the whole page if that is okay!
My form function. This get's called on page load:
// creates the form
function renderForm($name = '', $currPoints = '', $addPoints = '', $remPoints = '', $reason = '', $error = '', $id = '')
{ ?>
<title>
<?php if ($id != '') { echo "Edit Punk"; } else { echo "New Punk"; } ?>
</title>
<h1><?php if ($id != '') { echo "Edit Punk"; } else { echo "New Punk"; } ?></h1>
<?php if ($error != '') {
echo "<div style='padding:4px; border:1px solid red; color:red'>" . $error
. "</div>";
} ?>
<form name="pointsForm" action="" method="post" style="margin-top:50px;">
<?php if ($id != '') { ?>
<input type="hidden" name="id" value="<?php echo $id; ?>" />
<p>Name: <?php echo $name; ?> / <?php echo $currPoints; ?></p>
<?php } ?>
<input type="number" name="addPoints" placeholder="Add Punk Points">
<input type="number" name="remPoints" placeholder="Remove Punk Points">
<input type="text" name="reason" placeholder="Reason">
<input type="submit" name="submit" value="Update Punk Points">
</form>
</body>
</html>
<script>
$(function() {
$('form[name="pointsForm"]').submit(function(e) {
var reason = $('form[name="pointsForm"] input[name="reason"]').val();
if ( reason == '') {
e.preventDefault();
window.alert("Enter a reason, fool!")
}
});
});
</script>
<?php
}
Then my PHP for editing a record:
Where I get the variables from the URL/form I have added $currPoints = $currPoints+$addPoints-$remPoints;
Then on my bind_param is just add $currPoints.
I believe I am going wrong somewhere around these lines... or where I SET currPoints = ? . should that be something else?
Forgive me I am just learning PHP.
/*
EDIT RECORD
*/
// if the 'id' variable is set in the URL, we know that we need to edit a record
if (isset($_GET['id']))
{
// if the form's submit button is clicked, we need to process the form
if (isset($_POST['submit']))
{
// make sure the 'id' in the URL is valid
if (is_numeric($_POST['id']))
{
// get variables from the URL/form
$id = $_POST['id'];
$addPoints = htmlentities($_POST['addPoints'], ENT_QUOTES);
$remPoints = htmlentities($_POST['remPoints'], ENT_QUOTES);
$reason = htmlentities($_POST['reason'], ENT_QUOTES);
$currPoints = $currPoints+$addPoints-$remPoints;
// if everything is fine, update the record in the database
if ($stmt = $mysqli->prepare("UPDATE points SET currPoints = ? , addPoints = ?, remPoints = ?, reason = ?
WHERE id=?"))
{
$stmt->bind_param("iiisi", $currPoints, $addPoints, $remPoints, $reason, $id);
$stmt->execute();
$stmt->close();
}
// show an error message if the query has an error
else
{
echo "ERROR: could not prepare SQL statement.";
}
// redirect the user once the form is updated
header("Location: index.php");
}
// if the 'id' variable is not valid, show an error message
else
{
echo "Error!";
}
}
// if the form hasn't been submitted yet, get the info from the database and show the form
else
{
// make sure the 'id' value is valid
if (is_numeric($_GET['id']) && $_GET['id'] > 0)
{
// get 'id' from URL
$id = $_GET['id'];
// get the record from the database
if($stmt = $mysqli->prepare("SELECT * FROM points WHERE id=?"))
{
$stmt->bind_param("i", $id);
$stmt->execute();
$stmt->bind_result($id, $name, $currPoints, $addPoints, $remPoints, $reason, $date);
$stmt->fetch();
// show the form
renderForm($name, $currPoints, $addPoints, $remPoints, $reason, NULL, $id);
$stmt->close();
}
// show an error if the query has an error
else
{
echo "Error: could not prepare SQL statement";
}
}
// if the 'id' value is not valid, redirect the user back to the view.php page
else
{
header("Location: index.php");
}
}
}
?>
Sorry If I have been too vague. Please let me know if you need more information.
Thank you!
Oh found the error I think, you are never defining $currPoints before you try and use it, so you can't have $currPoints = $currPoints+.. because it isn't created yet. PHP more or less so will read line by line, so you have to query the SQL table and set $currPoints equal to the value from your database before you do $currPoints = $currPoints+$addPoints-$remPoints;
Ok, this probably won't work, but you should be able to figure out what I changed and adapt your code to work with it. I wouldn't say it's the 'proper' way, but it is a little easier to read and see what the code is doing when you have the if statements at the top to deal with what data is submitted vs not submitted.
if (!isset($_GET['id'] || !isset($_POST['submit'])))
{
echo "No Data!"
return;
}
if (!is_numeric($_POST['id']))
{
echo "Invalid ID!";
header("Location: index.php");
return;
}
// get variables from the URL/form
$id = $_POST['id'];
$addPoints = htmlentities($_POST['addPoints'], ENT_QUOTES);
$remPoints = htmlentities($_POST['remPoints'], ENT_QUOTES);
$reason = htmlentities($_POST['reason'], ENT_QUOTES);
$currPoints = 0;
//Check what the current points are first
// make sure the 'id' value is valid also
if (is_numeric($_GET['id']) && $_GET['id'] > 0)
{
// get 'id' from URL
$id = $_GET['id'];
// get the record from the database
if($stmt = $mysqli->prepare("SELECT * FROM points WHERE id=?"))
{
$stmt->bind_param("i", $id);
$stmt->execute();
$stmt->bind_result($id, $name, $currPoints, $addPoints, $remPoints, $reason, $date);
$stmt->fetch();
// show the form
renderForm($name, $currPoints, $addPoints, $remPoints, $reason, NULL, $id);
$stmt->close();
}
else
echo "Error: could not prepare SQL statement";
}
//Now update currPoints
$currPoints += $addPoints-$remPoints;
// if everything is fine, update the record in the database
if ($stmt = $mysqli->prepare("UPDATE points SET currPoints = ? , addPoints = ?, remPoints = ?, reason = ?
WHERE id=?"))
{
$stmt->bind_param("iiisi", $currPoints, $addPoints, $remPoints, $reason, $id);
$stmt->execute();
$stmt->close();
}
else
echo "ERROR: could not prepare SQL statement.";
// redirect the user once the form is updated
header("Location: index.php");

PHP OOP NOT ADDING

Im trying to create a to-do list following a tutorial from phpacademy. Iv managed to get everything to work, accept for submitting the user input into the database. This is my code so far.
<?php
require 'init.php';
if(isset($_POST['submit'])){
$name = trim($_POST['name']);
if(!empty($name)) {
$query = $db->prepare("
INERT INTO items (name,done) VALUES (:name,0)
");
$query->execute([
'name' => $name
]);
}
}
else {
echo ' not submitted';
} ?>
Try this way to fix your typo INSERT and :name
<?php
require 'init.php';
if(isset($_POST['submit']))
{
$name = trim($_POST['name']);
if(!empty($name))
{
$query = $db->prepare("
INSERT INTO items (name,done) VALUES (:name,0)
");
$query->execute([
':name' => $name
]);
echo "Successfully Inserted";
}
}
else{
echo ' not submitted';
}
?>

Categories