Why is my php "if statement" not affecting my mysql query? - php

First of all, I know mysql is deprecated. Will change to mysqli as soon as I figure out the issue at hand. My query continues to update all my rows even if the data is not set in the 'stripetoken' column. Why is this happening?
Code snippet:
$token_query = 'SELECT * FROM jobsubmission';
$token_res = mysql_query($token_query);
$token_row = mysql_fetch_array($token_res);
if(isset($token_row['stripetoken'])) {
$updqry = 'UPDATE jobsubmission SET assigned=1 WHERE ID="'.$book_ids[$jcount].'"';
$update = mysql_query($updqry);
$bookdate = date("d-m-Y");

Because $token_row['stripetoken'] is always set because it is a column in your database and it will be available in $token_row as a result. Now whether it has a value or not is a different story. You should be using empty() instead (assuming you don't want it to be true for falsy values).
if(!empty($token_row['stripetoken'])) {

So while #JohnConde was absolutely correct in saying I needed to use the empty function over the isset, my solution layed elsewhere. Here is how I managed to get the query to work to my specifications:
instead of searching for empty, I made the 'stripetoken' column NULL
by default.
This allowed me to use the following code:
$token_query = 'SELECT * FROM jobsubmission WHERE ID="'.$book_ids
[$jcount].'" and stripetoken is not null';
$token_res = mysql_query($token_query);
$token_row = mysql_fetch_object($token_res);
if(!$token_row->stripetoken == NULL) {

Related

How to get parameters from a URL and use them in a MySQL query in PHP

So, I will have a page where a user lands with a /?ref=123 type ending on the URL.
Then, what I want to achieve, is to use that ref 123 in a MySQL query, like this:
SELECT foo FROM table WHERE table.ref = 123
The issue I have hit is that if i use $_GET to get the variable, it breaks my SQL query (obviously!)
SELECT foo FROM table WHERE table.ref = $_GET['ref']; falls over because $_GET is not a MySQL function.
Trouble is, I want to dynamically create page content based on the ref value but I can't figure how.
Any help gratefully accepted.
Timezone GMT+13 so replies will potentially be slow :)
**********EDIT**********
As I may not have given enough info in the OP, here's the code I'm struggling with:
<?php
global $wpdb;
header('Content-Type: text/html; charset=utf-8');
include "../../../wp-config.php";
$get_donation_amount = "select SUM(amount) AS total_donations from SaveContactForm7_1 where ref = 123 ";
$get_donation_amount_result = $wpdb->get_results($get_donation_amount);
$total_donation = isset($get_donation_amount_result[0]->total_donations) && $get_donation_amount_result[0]->total_donations !="" ? $get_donation_amount_result[0]->total_donations :"0" ;
?>
What I need to do is add a call to the URL for the value of ref and add it where shown with the SQL querycode. Then a particular donor who knows his 'ref' value will see results relevant to him alone.
Using PHP7 this could look something like this
$ref = $_GET['ref'] ?? null;
$sth = $dbh->prepare('SELECT foo FROM table WHERE table.ref = ?');
$sth->execute([$ref]);
$orders = $sth->fetchAll();
You should probably have some way of handling errors (ref is not set)
Note that the last variable (result of the query) is called orders. I didn't know what the result set you expected would be, but it was just to illustrate that it makes sense to call it something spesific (what it actually represents), instead of "rows", "result" or similar.
Note that PHP 7 introduces the so called null coalescing operator which simplifies isset statements
PHP7
$ref = $_GET['ref'] ?? null;
PHP < 7
$ref = isset($_GET['ref']) ? $_GET['ref']: null;

CodeIgniter UPDATE works on first, but not successive AJAX calls

This is the weirdest problem. My update query works consistently if I write it as a query string. Here's my model function:
public function approveListing($params)
{
//This always works.
$sql = "UPDATE `assets` set approved = ".$params['approved']." WHERE as_id = ".$params['as_id']."";
$this->db->query($sql);
// and I use this select query to detect the actual updated value change.
$this->db->select('approved');
$this->db->where('as_id', $params['as_id']);
$query = $this->db->get('assets');
foreach($query->result() as $row)
{
$params['approved'] = $row->approved;
}
return $params;
}
...and the output will look something like this:
as_id = 260
approved = 1 (or 0, if the input param is 0)
But if I use the query builder method, rather than a sql string, it works exactly once:
public function approveListing($params)
{
// This only works on the first ajax call. After that, no update occurs.
$this->db->set('approved', $params['approved']); // this will be a value of 1 or 0
$this->db->where('as_id', $params['as_id']);
$this->db->update('assets');
$params['updated'] = $this->db->affected_rows();
// and I use this select query to detect the actual updated value change.
$this->db->select('approved');
$this->db->where('as_id', $params['as_id']);
$query = $this->db->get('assets');
foreach($query->result() as $row)
{
$params['approved'] = $row->approved;
}
return $params;
}
...and the output will look something like this:
as_id = 260
approved = 1
updated = 0 <!- notice this is the affected_rows() value. :( ->
$params['approved'] is either a 1 or a 0. The field approved in table assets is a BIT(1)
The function is being called from a controller function, which itself is being called from an ajax call, which sends the changes of a set of radio button clicks (either '1' or '0').
In the case of the query builder update, I am also capturing the affected_rows. The first time I do the query, the affected_rows() = 1. Every time thereafter, the affected_rows = 0, and by checking the record in PHPMyAdmin, I can see the value just doesn't want to change.
Well, I really dislike answering my own questions, but since I did find an answer, and since the question (though rare) is not "too local", but is, in fact, something other coders are going to run into if they try to update a MySQL data type BIT (why we don't see a lot of questions about data type BIT is because it's one of the newest MySQL or MariaDB data types), here is what's going on.
CodeIgniter query builder wraps the value with single quotes, like so:
UPDATE `assets` set approved = '1' WHERE as_id = 260
MySQL doesn't like that. You could either just hand write your query, like this:
$sql = "UPDATE `assets` set approved = ".$params['approved']." WHERE as_id = ".$params['as_id']."";
$this->db->query($sql);
...But that's not a good solution, it's a copout. The query builder should work.
What you have to do is to declare the value as an INT, and the way you do it is like this:
$this->db->set('approved', (int) $params['approved']);
$this->db->where('as_id', $params['as_id']);
$this->db->update('assets');

SQL UPDATE value as null or string

I searched almost whole internet, but could not find something similar, yet my question looks so simple.
I have a php code like so:
$id = 1;
if (!isset($_POST['port1'])) {
$port1 = null;
}
... which simply checks if submitted value is empty or not, if it is empty, then variable $port1 = null;
then, further in the code, I need to insert this value/update it in the database
$sql_update = ("UPDATE names_10 SET `digName1`=$port1 WHERE `device_id`='$id'");
...which should set the "digname1" to null. but it won't!
I tried every combination, every type of quotes, but every time I got UPDATE error..
any ideas?
Try this:
$id = 1;
if (!isset($_POST['port1'])) {
$port1 = "NULL";
}
$sql_update = ("UPDATE names_10 SET `digName1`= $port1 WHERE `device_id`='$id'");
I would rather suggest you to use PDO when you plan to bind something like this. There are a lot of benefits using PDO that would amaze you!

Get 'Update' error using SQLite3 and PHP

I created a function that tries to UPDATE a value using a condition. If something goes wrong, it tries to do a INSERT.
The code is as follow:
if(!$result=$this->query("UPDATE collect_data_settings SET setting_value ='".$setting_value."' WHERE collect_point = '".$collect_point."' AND setting_name='".$setting_name."';"))
$result=$this->query("INSERT INTO collect_data_settings ('collect_point','setting_name','setting_value') VALUES ('".$collect_point."','".$setting_name."','".$setting_value."');");
Unfortunately, for some reason the UPDATE query never returns false even if the condition is not satisfied. Can someone help me?
Why don't you try doing a search for the collect_point (assuming this is a unique key) variable first and if it is not yet in the database you use the INSERT statement and if not you use the UPDATE statement. For example:
$db = new SQLite3('database.db')
$check = $db->query("SELECT * FROM collect_data_settings WHERE collect_point = '$collect_point'")
$check_query = $check->numRows();
if($check_query > 0) {
*Your UPDATE query*
}else {
*Your INSERT query*
}
The UPDATE statement modifies all rows that happen to match the WHERE condition. The final number does not matter; even if no row matches, all rows were checked successfully.
To find out how many rows were changed, use the changes() function:
$this->exec("UPDATE ... WHERE ...");
if ($this->changes() == 0)
$this->exec("INSERT ...");

PHP mysql result issue

I have this line in my registration page.
if (device_id_exists($_POST['device_id']) == true) {
$errors[] = 'Sorry the Serial Number \'' . htmlentities($_POST['device_id']) . '\' does not exist.';
}
I have this in my function page.
function device_id_exists($device_id) {
$device_id = sanitize($device_id);
$query = mysql_query("SELECT COUNT(`numbers`) FROM `devicenumbers` WHERE `numbers` = '$numbers'");
return (mysql_result($query, 0) == 0) ? true : false;
If I run this query SELECT COUNT(numbers) FROMdevicenumbersWHEREnumbers= '1234567890'
(a valid number) it will return 1 = match found right? If I put a bogus number it returns a '0'.
What is happening is when there is a valid number it still returns the error the number doesn't exist. If I change it to the result to == 1 it will submit any number? Im a newbie to DB calls any help appreciated. I hope I provided enough info.
Looks like you're calling the incorrect variable. Within the device_id_exists() function, you're accepting a variable named $device_id. However when you're performing the query, you're calling what appears to be an undefined variable: $numbers. I suspect $numbers should be renamed to $device_id.
I see your $device_id comes from a form post. I'd HIGHLY recommend you escape the variable, using mysql_real_escape_string() to ensure you are protected against SQL injection. Please note that sanitize() does NOT protect against SQL injection!
On one additional note, I'd recommend utilizng mysql_num_rows() rather than mysql_result() because mysql_result() actually asks the database server to return an actual result when all you really care about is whether the entry exists or not, not it's actual value.
function device_id_exists($device_id) {
$device_id = sanitize($device_id);
$device_id = mysql_real_escape_string($device_id);
$query = mysql_query("SELECT COUNT(`numbers`) FROM `devicenumbers` WHERE `numbers` = '$device_id'");
return mysql_num_rows($query) ? True : False;
}
I had a similar problem with mysql result set , It returns nums_rows == 1 even when there are no records (while using max() inside select query - In your case you have used count())... Instead of checking mysqlquery to 0, check it whether the result set empty (That's how i solved my problem).. eg. if(!empty(mysql_result($query))) ? true : false;

Categories