PHP PDO can't UPDATE - php

The same solution was working before but the parameters were not passed in JSON format and that's the only difference.
I even tried to write the SQL query manually with values not from variables and it's still giving back 0 rows affected.
What could cause this problem?
<?php
$db = new PDO("mysql:host=localhost:3306;dbname=skistatus", "root", "");
$data = json_decode(file_get_contents('php://input'), true);
if ($_SERVER['REQUEST_METHOD'] == "GET") {
$statement = $db->query('SELECT * FROM skilifts');
$statement->setFetchMode(PDO::FETCH_ASSOC);
echo json_encode($statement->fetchAll());
}
if ($_SERVER['REQUEST_METHOD'] == "PUT") {
if($data['secret'] == "fee2c775c18a12b7b52b58129b00e1bd") {
$sql = 'UPDATE skilifts SET `status` = :status WHERE `id` = :id';
$query = $db->prepare($sql);
$query->execute(array(":status"=>$data['status'], ":id"=>$data['id'] ));
$count = $query->rowCount();
if($count == '0'){
echo "Failed";
http_response_code(400);
}
else{
echo "Success";
http_response_code(200);
}
} else {
echo $data['secret']." is not the magic word!";
http_response_code(403);
}
}
?>

The parameter id wasn't being updated on the front-end before passing it to the back-end. Basically when the SQL query was executing, it was the same id with the same status value to be updated as the ones in the database, and therefore no rows were affected by the UPDATE

Related

PHP doesn't execute functions with sql correct

I will put my code below. I basically check on value in the database and if it's 1 or 0 i want to change it to the opposite (so if 1 change it to 0, if 0 change to 1).
If I execute one SQL statement without using the function (but then it only works one way once) it works. But if I want to execute the specific function with it depending on what the value currently is, it doesn't seem to work. Do you know what I am doing wrong here?
<?php
$date_id = $_POST['dateID'];
$con = mysqli_connect("localhost","root","","secret_name");
$sql = "SELECT * FROM date_list WHERE date_id = ".$dateID;
$result = mysqli_query($con, $sql);
while($row = mysqli_fetch_assoc($result)){
$occupied = $row['occupied'];
if($occupied == 1){
decross_entry();
} elseif( $occupied == 0){
cross_entry();
}else{
echo "Error"
}
}
function decross_entry(){
$dateID = $_POST['dateID'];
$con_2 = mysqli_connect("localhost","root","","secret_name");
$sql_edit = "UPDATE date_list SET occupied= '0' WHERE date_id = ".$dateID;
if($con_2 -> connect_errno){
echo "Failed to connect to database!" . $con_2->connect_error;
}
if ($con_2 -> query($sql_edit) === TRUE)
{
echo "saved!";
} else {
echo "error: " .$sql_edit."<br>".$con_2->error;
}
}
function cross_entry(){
$dateID = $_POST['dateID'];
$con_2 = mysqli_connect("localhost","root","","secret_name");
$sql_edit = "UPDATE date_list SET occupied= '1' WHERE date_id = ".$dateID;
if($con_2 -> connect_errno){
echo "Failed to connect to database!" . $con_2->connect_error;
}
if ($con_2 -> query($sql_edit) === TRUE)
{
echo "saved!";
} else {
echo "error: " .$sql_edit."<br>".$con_2->error;
}
}
?>
If the only possible values of occupied are 0 and 1 then you can do what you want in one query without needing to look up the value of occupied first:
UPDATE date_list
SET occupied = 1 - occupied
WHERE date_id = ?
In PHP, using a prepared query to avoid SQL injection:
$date_id = $_POST['dateID'];
$con = mysqli_connect("localhost","root","","secret_name");
$sql = "UPDATE date_list SET occupied = 1 - occupied WHERE date_id = ?";
$stmt = $con->prepare($sql);
$stmt->bind_param('i', $date_id); // use 's' if $date_id is not an integer
$stmt->execute();

Can I only insert into 1 table during a session in php?

if (isset($_POST["AddErrorCode"]))
{
$AddErrorCodeDB = $_POST["AddErrorCode"];
$AddErrorDescriptionDB = $_POST["AddErrorDescription"];
$AddQuantityDB = $_POST["AddQuantity"];
$AddStartDateDB = $_POST["AddStartDate"];
$AddCompletionDateDB = $_POST["AddCompletionDate"];
$AddReviewTypeDB = $_POST["AddReviewType"];
session_start();
$WO_ID = $_SESSION['SELECTED_WO_ID'];
if ($AddReviewTypeDB === 'PR')
{
$AddReviewerType = 'Peer Review';
$insert = "INSERT INTO `wo_errorinfo` (
`Error_Code` ,
`Error_Description` ,
`Error_Quantity` ,
`Review_Type` ,
`WO_NO`) VALUES (
'$AddErrorCodeDB' ,
'$AddErrorDescriptionDB' ,
'$AddQuantityDB' ,
'$AddReviewerType' ,
'$WO_ID')";
if ($AddCompletionDateDB === '')
{
//echo 'ritwik';
$status = 'Peer RWK';
$update = "UPDATE `associated_wos` SET `WO Status` = '$status' WHERE `ID` = '$WO_ID'";
}
else
{
//echo 'ritwik1';
$status = 'Peer Review Complete';
$update = "UPDATE `associated_wos` SET `WO Status` = '$status' WHERE `ID` = '$WO_ID'";
}
$sql = "SELECT * FROM `wo_reviewerqa` WHERE `WO_ID` = '$WO_ID' AND `reviewType` = '$AddReviewerType'";
$result = mysqli_query($conn, $sql);
$num_rows = mysqli_num_rows($result);
//echo $num_rows;
if ($num_rows === 0)
{
//echo 'ritwik';
$insertreview = "INSERT INTO `wo_reviewerqa` (
`reviewType`,
`reviewStartDate`,
`reviewCompleteDate`,
`WO_ID`) VALUES (
'$AddReviewerType',
'$AddStartDateDB',
'$AddCompletionDateDB' ,
'$WO_ID')";
//echo $insertreview;
}
else
{
if ($AddStartDateDB !== '')
{
echo "<script type='text/javascript'>alert('Review Already Started, Start Date cant be changed');</script>";
}
}
if($conn->query($insertreview) === True)
{
echo "<script type='text/javascript'>alert('Start date updated successfully');</script>";
}
if ($conn->query($insert) === True)
{
echo "<script type='text/javascript'>alert('Error Code Submitted successfully');</script>";
}
}
All my condition are getting satisfied. I am even getting all the correct values in the echo but only the first insert query i.e. insert into 'wo_errorinfo' is working and all else are having no effect on the table. Can we not insert into multiple tables during a session. Is it due to session_start()? I have been trying to figure this out for more 1 day now but can't figure it.
You need to execute your statements, currently only $sql is executed.
You should also avoid building queries by concatenating strings as this will leave you vulnerable to SQL injection attacks where your users can modify your queries by passing special characters in the input. You should use mysqli::prepare, e.g:
if ($stmt = $mysqli->prepare("SELECT District FROM City WHERE Name=?")) {
/* bind parameters for markers */
$stmt->bind_param("s", $city);
/* execute query */
$stmt->execute();
}

odbc_num_rows is not work

$stmt is execute and give Result in Print_r($stmt). Result is this "Resource id #4" but when Print_r($stmt) is put in if (odbc_num_rows($stmt) > 0) {Print_r($stmt);}. it's not give Result. and gone else conditon give message else condition.so How to Put odbc function instead of odbc_num_rows($stmt).if right Parameter pass query execute and gone if condition.
which Odbc function used in if condtion.
<?php
include 'Connection.php';
if(isset($_REQUEST["insert"]))
{
$user = $_GET['user'];
$pwd = $_GET['pass'];
$yid = $_GET['yid'];
$sql = "select RegNo, UserName, Pasword from Std_Reg where UserName= '$user' and Pasword = '$pwd' and YearID = $yid and IsActive = True";
$stmt = odbc_exec($conn, $sql);
$result = array();
if (!empty($stmt)) {
// check for empty result
if (odbc_num_rows($stmt) > 0)
{
print_r($stmt);
$stmt1 = odbc_fetch_array($stmt);
$product = array();
$product['RegNo'] = $stmt1['RegNo'];
$product['UserName'] = $stmt1['UserName'];
$product['Pasword'] = $stmt1['Pasword'];
// success
$result["success"] = 1;
// user node
$result["product"] = array();
array_push($result["product"], $product);
// echoing JSON response
echo json_encode($result);
} else {
// no product found
$result["succes"] = 0;
$result["message"] = "No product found";
// echo no users JSON
echo json_encode($result);
}
//sqlsrv_free_stmt($stmt);
odbc_close($conn); //Close the connnection first
}
}
?>
For INSERT, UPDATE and DELETE statements odbc_num_rows() returns the number of rows affected. The manual says-
Using odbc_num_rows() to determine the number of rows available after a SELECT will return -1 with many drivers.
one way around this behaviour is to do a COUNT(*) in SQL instead. See here for an example.

my function that checks if something is already in the database isn't working

I'm working on this project and I need help with something. I am trying to check if someone is already in the database upon logging in and if they are not, they will be added. However, my code always adds them to the database...
Login code:
<?php
if(isset($_POST["emaillogin"]) and isset($_POST["passwordlogin"])){
$sql = "SELECT `accnr`
FROM `Account`
WHERE '$emaillogin' = `emailadress`
AND '$passwordlogin' = `password` LIMIT 1";
$result = mysql_query($sql);
if ($result == false){
echo "E-mail or password incorrect! <br>";
}else{
$accnr = mysql_fetch_array($result);
setcookie("accnr", $accnr[0] , time() + (1800), "/");
$accnmr = $accnr[0];
if(check_firstest($accnmr) == false){
$query = "INSERT INTO `VRIENDEN`
(`accnr`,`vriendnr`)
VALUES ('$accnmr','$accnmr')";
$result = mysql_query($query);
}
header("location:home.php");
die();
}
}
?>
The function in functions.php:
function check_firstest($accnr){
$query = mysql_query("SELECT count(*) AS 'num' FROM `VRIENDEN` WHERE `accnr` = '$accnr' AND `vriendnr` = '$accnr'");
if($result > 0){
return true;
}
else{
return false;
}
}
The login on its own works just fine, so thats no problem.
Thank you!
Your first query is somewhat odd and you do not capture the values from $_POST into the variables that you are using in the query either
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
if(isset($_POST["emaillogin"]) and isset($_POST["passwordlogin"])){
$sql = "SELECT `accnr`
FROM `Account`
WHERE `emailadress` = '{$_POST['emaillogin']}'
AND `password` = '{$_POST['passwordlogin']}'
LIMIT 1";
$result = mysql_query($sql);
if ($result == false){
// something went REALLY WRONG, report it
echo mysql_error();
exit;
}
if ( mysql_num_rows($result) == 1 ) {
// found user and password matches
header("location:home.php");
exit;
}else{
// new user, create the account
$accnr = mysql_fetch_array($result);
setcookie("accnr", $accnr[0] , time() + (1800), "/");
$accnmr = $accnr[0];
if(check_firstest($accnmr) == false){
$query = "INSERT INTO `VRIENDEN`
(`accnr`,`vriendnr`)
VALUES ('$accnmr','$accnmr')";
$result = mysql_query($query);
}
// and go to home page
header("location:home.php");
die();
}
}
?>
And of course the fix for the check_firstest() is also required
function check_firstest($accnr){
$result = mysql_query("SELECT count(*) AS 'num'
FROM `VRIENDEN`
WHERE `accnr` = '$accnr'
AND `vriendnr` = '$accnr'");
if(mysql_fetch_field($result, 0) > 0){
return true;
} else{
return false;
}
}
But I have to add
Your script is at risk of SQL Injection Attack
Have a look at what happened to Little Bobby Tables Even
if you are escaping inputs, its not safe!
Use prepared parameterized statements
And
You should not be using the mysql_ database extension, it is deprecated and has been for years and is gone for ever in PHP7.
If you are just learning PHP, spend your energies learning the PDO or mysqli database extensions and prepared statements.
Start here
You have to count the resulting rows:
function check_firstest($accnr){
$result = mysql_query("SELECT count(*) AS 'num'
FROM `VRIENDEN`
WHERE `accnr` = '$accnr'
AND `vriendnr` = '$accnr'");
if(mysql_fetch_field($result, 0) > 0){
return true;
} else{
return false;
}
}
Here the mysql_num_rows() function gives the number of rows in the result set. If it is greater than 0 then it means that there is some data.

Checking for an empty result (PHP, PDO, and MySQL) [duplicate]

This question already has an answer here:
How to check fetched result set is empty or not?
(1 answer)
Closed 11 months ago.
What am I doing wrong here? I'm simply retrieving results from a table and then adding them to an array. Everything works as expected until I check for an empty result...
This gets the match, adds it to my array and echoes the result as expected:
$today = date('Y-m-d', strtotime('now'));
$sth = $db->prepare("SELECT id_email FROM db WHERE hardcopy = '1' AND hardcopy_date <= :today AND hardcopy_sent = '0' ORDER BY id_email ASC");
$sth->bindParam(':today', $today, PDO::PARAM_STR);
if(!$sth->execute()) {
$db = null;
exit();
}
while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
$this->id_email[] = $row['id_email'];
echo $row['id_email'];
}
$db = null;
return true;
When I try to check for an empty result, my code returns 'empty', but no longer yields the matching result:
$today = date('Y-m-d', strtotime('now'));
$sth = $db->prepare("SELECT id_email FROM db WHERE hardcopy = '1' AND hardcopy_date <= :today AND hardcopy_sent = '0' ORDER BY id_email ASC");
$sth->bindParam(':today',$today, PDO::PARAM_STR);
if(!$sth->execute()) {
$db = null;
exit();
}
if ($sth->fetchColumn()) {
echo 'not empty';
while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
$this->id_email[] = $row['id_email'];
echo $row['id_email'];
}
$db = null;
return true;
}
echo 'empty';
$db = null;
return false;
You're throwing away a result row when you do $sth->fetchColumn(). That's not how you check if there are any results. You do
if ($sth->rowCount() > 0) {
... got results ...
} else {
echo 'nothing';
}
Relevant documentation is here: PDOStatement::rowCount
If you have the option of using fetchAll() then, if there are no rows returned, it will just be an empty array.
count($sql->fetchAll(PDO::FETCH_ASSOC))
will return the number of rows returned.
You should not use rowCount for SELECT statements as it is not portable. I use the isset function to test if a select statement worked:
$today = date('Y-m-d', strtotime('now'));
$sth = $db->prepare("SELECT id_email FROM db WHERE hardcopy = '1' AND hardcopy_date <= :today AND hardcopy_sent = '0' ORDER BY id_email ASC");
// I would usually put this all in a try/catch block, but I kept it the same for continuity
if(!$sth->execute(array(':today'=>$today)))
{
$db = null;
exit();
}
$result = $sth->fetch(PDO::FETCH_OBJ)
if(!isset($result->id_email))
{
echo "empty";
}
else
{
echo "not empty, value is $result->id_email";
}
$db = null;
Of course this is only for a single result, as you might have when looping over a dataset.
I thought I would weigh in as I had to deal with this lately.
$sql = $dbh->prepare("SELECT * from member WHERE member_email = '$username' AND member_password = '$password'");
$sql->execute();
$fetch = $sql->fetch(PDO::FETCH_ASSOC);
// if not empty result
if (is_array($fetch)) {
$_SESSION["userMember"] = $fetch["username"];
$_SESSION["password"] = $fetch["password"];
echo 'yes this member is registered';
}else {
echo 'empty result!';
}
what I'm doing wrong here?
Almost everything.
$today = date('Y-m-d'); // no need for strtotime
$sth = $db->prepare("SELECT id_email FROM db WHERE hardcopy = '1' AND hardcopy_date <= :today AND hardcopy_sent = '0' ORDER BY id_email ASC");
$sth->bindParam(':today',$today); // no need for PDO::PARAM_STR
$sth->execute(); // no need for if
$this->id_email = $sth->fetchAll(PDO::FETCH_COLUMN); // no need for while
return count($this->id_email); // no need for the everything else
Effectively, you always have your fetched data (in this case in $this->id_email variable) to tell whether your query returned anything or not. Read more in my article on PDO.
One more approach to consider:
When I build an HTML table or other database-dependent content (usually via an AJAX call), I like to check if the SELECT query returned any data before working on any markup. If there is no data, I simply return "No data found..." or something to that effect. If there is data, then go forward, build the headers and loop through the content, etc. Even though I will likely limit my database to MySQL, I prefer to write portable code, so rowCount() is out. Instead, check the the column count. A query that returns no rows also returns no columns.
$stmt->execute();
$cols = $stmt->columnCount(); // no columns == no result set
if ($cols > 0) {
// non-repetitive markup code here
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
I only found one way that worked...
$quote = $pdomodel->executeQuery("SELECT * FROM MyTable");
//if (!is_array($quote)) { didn't work
//if (!isset($quote)) { didn't work
if (count($quote) == 0) { //yep the count worked.
echo 'Record does not exist.';
die;
}
Thanks to Marc B's help, here's what worked for me (note: Marc's rowCount() suggestion could work too, but I wasn't comfortable with the possibility of it not working on a different database or if something changed in mine... also, his select count(*) suggestion would work too, but, I figured because I'd end up getting the data if it existed anyway, so I went this way).
$today = date('Y-m-d', strtotime('now'));
$sth = $db->prepare("SELECT id_email FROM db WHERE hardcopy = '1' AND hardcopy_date <= :today AND hardcopy_sent = '0' ORDER BY id_email ASC");
$sth->bindParam(':today', $today, PDO::PARAM_STR);
if(!$sth->execute()) {
$db = null;
exit();
}
while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
$this->id_email[] = $row['id_email'];
echo $row['id_email'];
}
$db = null;
if (count($this->id_email) > 0) {
echo 'not empty';
return true;
}
echo 'empty';
return false;

Categories