Button to update MySQL column not working - php

I want to update my database with an SQL statement once someone clicks a button on the website. I've tried something, no success. Can you guys help me ? Here's the code:
http://pastebin.com/D0S83Jgh
Don't know if I made this question correctly, I'm new here.

Your prepared statement is wrong.
The code I use with pdo to do a query is this:
$sqlUpd = $upd->prepare("UPDATE league_signups SET approved='1' WHERE id = :id");
$q->bindParam(':id', $id, PDO::PARAM_STR);
$q->execute();
Should work like a charm.

Get this code out of the main loop: while($row = $q->fetch(PDO::FETCH_ASSOC)) {}
<?php
include('pdoconnect.php');
$id = isset($row['id'];
if(isset($_REQUEST['approve']))
{
$sqlUpd = "UPDATE league_signups SET approved='1' WHERE id=$id";
$q = $upd->prepare($sqlUpd);
$q->execute();
}
if(isset($_REQUEST['unapprove']))
{
$sqlUpd = "UPDATE league_signups SET approved='0' WHERE id=$id";
$q = $upd->prepare($sqlUpd);
$q->execute();
}
?>
Put this code after the loop ending or the beginning of your code...
The data you want to update comes from the checkbox am I right? then you may want to make a loop to update all the values selected with checkbox to the corresponding action 'approve' or 'unapproved'
remove include('pdoconnect.php'); its utterly unnecessary if you are including this file from the beginning already
<?php
// checkbox[] it's an array...
$UpdateIDs = (isset($_REQUEST['checkbox'])) ? $_REQUEST['checkbox'] : [];
// check if $_REQUEST['approve'] is set else check if $_REQUEST['unapprove'] is set else set $approve to null;
$approved = (isset($_REQUEST['approve']) ?
$_REQUEST['approve'] :
(isset($_REQUEST['unapprove'])) ? $_REQUEST['unapprove'] : null;
if(!is_null($approved))
{
try {
foreach($UpdateIDs as $ID)
{
$stmt = $upd->prepare("UPDATE league_signups SET approved=:approved WHERE id=:id");
$stmt->execute([
':approved' => $approved,
':id' => $ID
]);
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
}

Related

Doing php select to use the string within math problem with Json Decoded string and then update my database

I am passing the number 1 from my javascript file as $played = json decode.
I am not sure my Select query is working correctly, or my math is just all wrong. PHP is still new to me and I'm not sure if I can rename strings, and still have the query work. I know everything has to be passed into PHP to work and that I cant just make a variable and bind it and have the update work. I was thinking I could rename my passed JSON string so it could be used temporarily, but then I figured I could just name my SELECT string $results and then add the two.
The problem I am having is, it appears to UPDATE twice to the database. No matter how many times I wager, my database only shows the number 2. It's like it stops counting and UPDATE.
Any advice is welcome, thank you in advance for looking and helping if you can.
Okay this didn't work. Maybe I'm not understanding the answer. It didn't post anything to the database. Do I still need to bind the values, or no?
<?php
session_start();
if(empty($_SESSION['userid']))
{
header("Location: ../login/index.php");
}
include('../../login/database.php');
if (isset($_SESSION['userid']))
$played = json_decode(file_get_contents('php://input'), true);
$userid = $_SESSION['userid'];
try {
$db = DB();
$stmt = $db->prepare("UPDATE usersystem SET played = played + :played WHERE userid = :userid");
$stmt->bindValue(':played', $played, PDO::PARAM_STR);
$stmt->bindValue(':userid', $userid, PDO::PARAM_STR);
$stmt->execute();
}
catch(PDOException $e)
{
$db = null;
echo $e->getMessage();
}
}
echo $_POST['package'];
?>
And here is the javascript POST
function updateDatabase() {
played = 1;
var package = played;
//console.log(package);
fetch('../php/played/played.php', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(package)
});
}
This is getting aggravating. I have this Version information: 4.6.4 , latest stable version: 4.9.7 phpmyadmin.
Since my played.php will not post the data to the database I decided to use my credit.php file to test the played entry I am trying to make. Here is how I tested it, and this too does not post the info to my database, but my credits do get posted into the database.
credits.php
<?php
session_start();
if(empty($_SESSION['userid']))
{
header("Location: ../login/index.php");
}
include('../../login/database.php');
if (isset($_SESSION['userid'])) {
$money = json_decode(file_get_contents('php://input'), true);
$money_as_number = intval( $money );
$userid = $_SESSION['userid'];
try {
$db = DB();
//$a = 1;
//$db->query("update usersystem set played=played+". intval($a) ."WHERE userid=:userid");
$db->query("UPDATE usersystem set played = played + 1 WHERE userid=:userid");
$stmt = $db->prepare("UPDATE usersystem SET money=:money WHERE userid=:userid");
$stmt->bindValue(':money', $money_as_number, PDO::PARAM_STR);
$stmt->bindValue(':userid', $userid, PDO::PARAM_STR);
$stmt->execute();
}
catch(PDOException $e)
{
$db = null;
echo $e->getMessage();
}
}
echo $_POST['package'];
?>
Here is my money Ajax which is identical to the played ajax
var package = money;
//console.log(package);
fetch('../php/credits/credit.php', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(package)
});
Maybe I can't do played = played + with my version? Any ideas?
I solved it finally !!!
Thank you very much for answering and educating. Your answer led me to the research i needed so I could understand things better and let me tell you, no more query for me, and have a way better understanding of fetch and how it's used!
<?php
session_start();
if(empty($_SESSION['userid']))
{
header("Location: ../login/index.php");
}
include('../../login/database.php');
if (isset($_SESSION['userid'])) {
$money = json_decode(file_get_contents('php://input'), true);
$money_as_number = intval( $money );
$userid = $_SESSION['userid'];
try {
$db = DB();
$stmt = $db->prepare("SELECT played FROM usersystem WHERE userid=?");
$stmt->execute([$userid]);
$played = $stmt->fetchColumn();
$results = 1;
$played = $results + $played;
$stmt = $db->prepare("UPDATE usersystem SET money=:money, played=:played WHERE userid=:userid");
$stmt->bindValue(':money', $money_as_number, PDO::PARAM_INT);
$stmt->bindValue(':userid', $userid, PDO::PARAM_STR);
$stmt->bindValue(':played', $played, PDO::PARAM_INT);
$stmt->execute();
}
catch(PDOException $e)
{
$db = null;
echo $e->getMessage();
}
}
//echo $_POST['package'];
?>
You can totally do this in a single UPDATE statement without the need for using a SELECT statement.
You can increment the stored value by whatever $played is, by simply:
UPDATE usersystem SET played = played + :played WHERE userid = :userid
And remove that foreach statement. Not sure what your intention is there but it is grabbing the final row of user data whose userid is sorted descending.
Also, $played = json_decode(file_get_contents('php://input'), true); is very suspicious to me. Are you sure $played is an integer at this point? json_decode(..., true) will give you an array. I think you need to fix this before moving forward.

No Update done with PDO php

I have problem without any error in my code that update row ..
if(!isset($error)){
try {
$sql = "UPDATE `invoice` SET `client`='".$client."', `company`='".$company."' , `clientemail`='".$clientemail."' , `mobailclient`='".$mobailclient."' , `startdate`='".$startdate."' , `enddate`='".$enddate."' WHERE `id` ='".$id."'";
$count = $db->exec($sql);
//redirect to invoice page
header('Location: invoice.php');
exit;
//else catch the exception and show the error.
} catch(PDOException $e) {
$error[] = $e->getMessage();
}
}
This is my code , i try to get variable $sql and go to mysql phpmyadmin and its work good ,, but in file not work and i dont get any error
==== Update ====
i try this and not work
try {
$sql = 'UPDATE invoice SET client = :client, company = :company, clientemail = :clientemail, mobailclient = :mobailclient, startdate = :startdate, enddate = :enddate WHERE id = :id';
$statement = $db->prepare($sql);
$statement->bindParam(":client", $client);
$statement->bindParam(":company", $company);
$statement->bindParam(":clientemail", $clientemail);
$statement->bindParam(":mobailclient", $mobailclient);
$statement->bindParam(":startdate", $startdate);
$statement->bindParam(":enddate", $enddate);
$statement->bindParam(":id", intval($_GET['id']) );
$statement->execute();
if($statement->rowCount() > 0) // will return 1 if any row is updated
{
echo "<script>alert('".$statement->rowCount()."')</script>";
}
else
{
echo "<script>alert('No record updated')</script>";
}
Your query is opened for SQL Injection. You should use parameterized query which provide a kind of protection against SQL injection but will not provide 100% of protection. Kindly visit this Post for more details.
Try the following code by replacing table and column names.
$client = "my name";
$company = "my-company";
$id= 2;//make sure your table has a record with that specific id
$sql = 'UPDATE invoice SET client = :client, company = :company WHERE id = :id'; // here i am updating only two columns
//You can add more column that you want to upate like ColumnName = :ParameterIdentifier
//Where ParameterIdentifier Is the name of parameter used in bindParam as in my example company
$statement = $db->prepare($sql);
$statement->bindParam("client", $client); //Binding parameter for client
$statement->bindParam("company", $company); //Binding parameter for company
$statement->bindParam("id", $id);
$statement->execute();
if($statement->rowCount() > 0) // will return 1 if any row is updated
{
echo "Record updated successfully";
}
else
{
echo "No record updated";
}

Update an enum type

This is my Code:
public function enUser($userID) {
try {
$userStatus = "Y";
$tokenCode = "";
$sql = ('UPDATE tbl_users SET userStatus = ? AND tokenCode = ? WHERE userID = ?');
$stmt = $this->conn->prepare($sql);
$stmt->bindParam(1, $userStatus);
$stmt->bindParam(2, $tokenCode);
$stmt->bindParam(3, $userID);
$stmt->execute();
} catch (PDOException $e) {
echo $e->getMessage();
}
}
This is my enum in database
I have try more to edit it. But in database always appear nothing. I mean in the field 'userStatus' after running the update script, its just value like "" (empty). Can any one help me? Thanks.
You update must be:
'UPDATE tbl_users SET userStatus = ?, tokenCode = ? WHERE userID = ?
See the comma instead of AND
And make sure that $userID exists in your DB

PHP While loop of ID's only works with first id

I am currently building a lightweight blogging platform with some nice Material Design but i have run into a problem. I have a table with ID's and I want to change the value of public in my table so that you can hide articles from the blog, to do so I made a loop but it only works on the first id and none of the other id's. Here is my code:
try {
if (isset($_POST['submit'])) {
$stmt = $db->query('SELECT postID FROM blog_posts ORDER BY postID DESC');
while ($row = $stmt->fetch()) {
// set public based on the submitted value from your form
$public = empty($_POST['public'][$row['postID']]) ? 0 : 1;
// do the update
$stmt = $db->prepare('UPDATE blog_posts SET public = ? WHERE postID = ?');
$stmt->execute(array($public, $row['postID']));
header('Location: index.php');
}
}
} catch (PDOException $e) {
echo $e->getMessage();
}
If it is of any use here is my full page of PHP, also my fully loaded page can be found here
Thanks in advance.
Please put this header('Location: index.php'); outside the while-loop and don't override the $stmt instead use another one :
//.......
//.......
while ($row = $stmt->fetch()) {
// set public based on the submitted value from your form
$public = empty($_POST['public'][$row['postID']]) ? 0 : 1;
// do the update
//Create another statement
$stmt2 = $db->prepare('UPDATE blog_posts SET public = ? WHERE postID = ?');
$stmt2->execute(array(
$public,
$row['postID']
));
}
header('Location: index.php');
//.......
//.......

saving multiple check-boxes as different records in php

Am trying to save the result of multiple check-boxes as separate records. my code is not functioning. please help!
<?php
session_start();
$id = $_SESSION['user_id'];
$db = new PDO('mysql:host=localhost;dbname=idp;charset=utf8','root', '');
foreach($_POST['comp'] as $val){
$tmp['user_id'] = $id;
$tmp['comp_id'] = $val;
$vars[] = $tmp;
}
$qry = "INSERT INTO compentency_result (user_id, result) VALUES (:user_id, :comp_id)";
try
{
$sql = $db->prepare($qry);
$numRows = 0;
foreach($vars as $insert){
$numRows += $sql->execute($insert);
}
print("<p>There were {$numRows} inserted into the database!</p>");
}
catch(PDOException $e)
{
print("<p>Oops! There was an issue - this is the message: {$e->getMessage()}</p>");
}
?>
The result is showing me that nothing is added to the database.
To bind the parameters individually you would do this:
try
{
$sql = $db->prepare($qry);
$numRows = 0;
foreach($vars as $insert){
$sql->bindParam(':user_id', $insert['user_id'], PDO::PARAM_STR);
$sql->bindParam(':comp_id', $insert['comp_id'], PDO::PARAM_STR);
$sql->execute();
$numRows += $sql->rowCount(); // get the rows affected this way
}
echo "<p>There were {$numRows} inserted into the database!</p>";
}
In addition, I added a more proper and reliable method of getting the affected rows, using rowCount().
If you don't want to bind the elements individually you can use execute() with an array as shown in Demystifying PDO

Categories