How to properly use variable in a query? postgresql - php

$result = pg_query(Postgres::getInstance(), "SELECT
date_start,
date_end,
cnt_hands,
cnt_hands_won,
amt_won,
id_session,
id_player,
amt_won
FROM
cash_table_session_summary
WHERE
date_start = '2016-04-27 07:20:47'");
This works perfectly.
echo $sessionStart;
$result = pg_query(Postgres::getInstance(), "SELECT
date_start,
date_end,
cnt_hands,
cnt_hands_won,
amt_won,
id_session,
id_player,
amt_won
FROM
cash_table_session_summary
WHERE
date_start = $sessionStart");
This throws this:
2016-04-27 07:20:47 Warning: pg_query(): Query failed: ERROR: syntax
error at or near "07" LINE 13: ... date_start = 2016-04-27 07:20:47 ^
in /home/haris/public_html/project/DAL_General.php on line 102
Is colon a problem? Do I need to escape it somehow? If so, how? I've google but found nothing about escaping colons.

Your date must be inside quotes. You need to change
FROM
cash_table_session_summary
WHERE
date_start = $sessionStart
To
FROM
cash_table_session_summary
WHERE
date_start = '$sessionStart'// add quotes here
For more understand about quotes check When to use single quotes, double quotes, and backticks in MySQL

I had the same issue when I was learning database work, but you need the query to be made in ""'s - Then when referencing a variable or data you need to put it in ''s, example:
$test_query = type_of_connection_query("SELECT * FROM users WHERE id = '1'");
That would not work like:
$text_query = type_of_connection_query("SELECT * FROM users WHERE id = 1");
And of course there are some times when you don't need quotes, like referencing LIMIT's
$text_query = type_of_connection_query("SELECT * FROM users WHERE id = '1' LIMIT 1");

Related

Getting undefined index while fetching column value from mysql

I have the following code :
$sql = 'select count(*) from match as count where match_status != :status';
$query = $con->prepare($sql);
$query->bindValue(':status',LOST,PDO::PARAM_INT);
$query->execute();
$row = $query->fetch(PDO::FETCH_ASSOC);
if(!empty($row))
$row_count = $row['count'];
else
$row_count = 0;
I am getting Notice: Undefined index: count
What's the mistake?
You created the alias for the wrong thing. This should work:
SELECT count(*) as count FROM `match` WHERE match_status != :status
//^^^^^ Alias for 'count(*)' NOT for your table name
Also you have to put ` around keywords/Mysql reserved words e.g. match: http://dev.mysql.com/doc/refman/5.6/en/reserved-words.html
And if you turn on error mode then you also get an error for this, just put it right after your connection:
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = 'select count(*) from match as count where match_status != :status';
In this query, the as count won't do a thing, because you don't know what column you want to rename.
You need to place it directly after the original column name, so the database knows what column-name it needs to hide:
$sql = 'select count(*) as count from `match` where `match_status` != :status';
Because of this $row['count'] won't work, because you don't have a count-column, only a count(*) column.
N.B.: You're using a MySQL reserved word, being match and requires special attention in MySQL. Either rename it to something else, or use ticks around it, in order to escape it properly.

Cannot compare date in SQL statement

I'm using Joshcam's PHP Mysqli Database Class (github) and have been fighting over comparing dates for a long while now.
Bottom line is could anyone explain this error message:
PHP Fatal error: Problem preparing query (SELECT * FROM jobs WHERE business_id = 5 AND active = 1 AND date_visit > `2015-01-01 05:02:14` ORDER BY date_appt DESC) Unknown column '2015-01-01 05:02:14' in 'where clause'
My query goes:
$jobs = $db->rawQuery("SELECT * FROM jobs WHERE business_id = $business_id AND active = 1 AND date_visit > `".$search_from."` ORDER BY date_appt DESC");
Why would my date input be considered a column instead of a field value?
I've tried double quotes, single quotes, no quotes, and it's either turning the quotes to ' or put off by the space between Y-m-d and H:i:s.
You are using backticks for query variable rather single quote so try to remove backticks from value($search_from) else it will be treat as column
$jobs = $db->rawQuery("SELECT * FROM jobs WHERE business_id = '$business_id' AND active = 1 AND date_visit > '$search_from' ORDER BY date_appt DESC");
Enclose the names of database objects (databases, tables, fields, indexes, triggers a.s.o.) in backquotes (``). This is usually not needed but it is useful (read "required") when the name is a MySQL reserved word.
Enclose the string literals in apostrophes ('2015-01-01 05:02:14') or quotes ("2015-01-01 05:02:14"):
SELECT *
FROM `jobs`
WHERE `business_id` = 5
AND `active` = 1
AND `date_visit` > '2015-01-01 05:02:14'
ORDER BY `date_appt` DESC
None of the field names in the query above is a MySQL keyword, there is no need to enclose them in backquotes. I only did it for explanatory purposes.
Your PHP code should read:
$jobs = $db->rawQuery("SELECT * FROM jobs WHERE business_id = $business_id AND active = 1 AND date_visit > '".$search_from."' ORDER BY date_appt DESC");
The issue was mainly that this class doesn't allow for
WHERE the_date > $date1
AND the_date < $date2
I actually had to use between to solve it.
My final code:
$params = array($business_id,1,$search_from,$search_to,$limit_end);
$jobs = $db->rawQuery("SELECT * FROM jobs WHERE business_id = ? AND active = ? AND date_visit BETWEEN ? AND ? ORDER BY date_appt DESC, id DESC LIMIT ?",$params,false);

PHP: MySQL Select with multiple Where [duplicate]

This question already has an answer here:
Syntax error due to using a reserved word as a table or column name in MySQL
(1 answer)
Closed 8 years ago.
I looked mostly everywhere on Stackoverflow for adding multiple WHERE instances but none of them seem to work.
My Select query:
$result = mysql_query("SELECT * FROM $tableName WHERE user = $user AND column = 1"); //query
I tried IN and some other ways but I dont know why it wont get the column. If I take out the user column it works, but I want it to also restrict to the column as well..
Any help will be appreciated!
column is reserved word in mysql. You have to use ` around that kind of column_name and use ' single quotes around string data '$user'
SELECT * FROM $tableName WHERE user = '$user' AND `column` = 1
You need to wrap the username in single-quotes & as mentioned by Yogesh column is a reserved keyword in MySQL. Try this:
user = '$user' AND `column` = 1
So the whole statement becomes:
$result = mysql_query("SELECT * FROM $tableName WHERE user = '$user' AND `column` = 1");
Also, you should be using mysqli or PDO with prepared statements instead.
Rewrite your query. Use the below code:
$result = mysql_query("SELECT * FROM `".$tableName."` WHERE user = '".$user."' AND `column` = 1");
And here I am missing that what is column in query is it name of column?
And you need to give the value in single quota and table name in ` till mark.
try this one:
$sql = 'SELECT * FROM $tableName WHERE user = "'.$user.'" AND `column` = 1';

Counting rows with variables in where clause

I'm having trouble using variables in my SQL WHERE clause. I'm getting this error:
Warning: mysql_fetch_array(): supplied argument is not a valid MySQL
result resource
The code is:
$sql3= mysql_query("SELECT COUNT($ww) FROM data WHERE $".$ww." = ".$weeknumber." ");
What am I doing wrong?
Why don't you count the table column by putting the columns name in your COUNT(column_name)?
Like so:
$sql3= mysql_query("SELECT COUNT(week_num) as wknum FROM data WHERE '$ww' = '$weeknumber'");
$counted_weeks["week_num"]
// $counted_weeks["week_num"] will output your sum
//week_num would be a column name from your "data" table
I recommend looking at this link. As #Crontab mentioned I am not sure why you have a dollar sign in front of your where clause.
A couple other things to point out:
As it says in the link, you will need to make sure the query text is properly escaped. Also, If I'm not mistaken (not familiar with PHP) do you need to explicitly concatenate the text instead of just using quotes? (i.e. instead of "SELECT ... " ... " do you need to do "SELECT ... " + " ... ")
php string formatting is perfect here, take your messy confusing concat string and make it clean and readable!
$sql3= mysql_query(sprintf("SELECT COUNT(%s) FROM data WHERE %s=%d", $ww, $ww, $weeknumber));
Assuming that $ww is a valid column name and $weekNumber is an integer, this should work:
$query = "SELECT COUNT(*) AS cnt FROM data WHERE $ww = '$weekNumber'";
$rs = mysql_query($query);
$r = mysql_fetch_assoc($rs);
echo "Count: {$r['cnt']}";
I am guessing $ww is referring to a column name. $weekNumber is obviously the value. In that case, your SQL query should look like this:
$sql3= mysql_query("SELECT COUNT(".$ww.") FROM data WHERE ".$ww." = ".$weeknumber." ");
I'm not a PHP guy, but I'm assuming you have the correct PHP syntax.

mysql like statement is not working as expected

I have a table with 4 record.
Records: 1) arup Sarma
2) Mitali Sarma
3) Nisha
4) haren Sarma
And I used the below SQL statement to get records from a search box.
$sql = "SELECT id,name FROM ".user_table." WHERE name LIKE '%$q' LIMIT 5";
But this retrieve all records from the table. Even if I type a non-existence word (eg.: hgasd or anything), it shows all the 4 record above. Where is the problem ? plz any advice..
This is my full code:
$q = ucwords(addslashes($_POST['q']));
$sql = "SELECT id,name FROM ".user_table." WHERE name LIKE '%".$q."' LIMIT 5";
$rsd = mysql_query($sql);
Your query is fine. Your problem is that $q does not have any value or you are appending the value incorrectly to your query, so you are effectively doing:
"SELECT id,name FROM ".user_table." WHERE name LIKE '%' LIMIT 5";
Use the following code to
A - Prevent SQL-injection
B - Prevent like with an empty $q
//$q = ucwords(addslashes($_POST['q']));
//Addslashes does not work to prevent SQL-injection!
$q = mysql_real_escape_string($_POST['q']);
if (isset($q)) {
$sql = "SELECT id,name FROM user_table WHERE name LIKE '%$q'
ORDER BY id DESC
LIMIT 5 OFFSET 0";
$result = mysql_query($sql);
while ($row = mysql_fetch_row($result)) {
echo "id: ".htmlentities($row['id']);
echo "name: ".htmlentities($row['name']);
}
} else { //$q is empty, handle the error }
A few comments on the code.
If you are not using PDO, but mysql instead, only mysql_real_escape_string will protect you from SQL-injection, nothing else will.
Always surround any $vars you inject into the code with single ' quotes. If you don't the escaping will not work and syntax error will hit you.
You can test an var with isset to see if it's filled.
Why are you concatenating the tablename? Just put the name of the table in the string as usual.
If you only select a few rows, you really need an order by clause so the outcome will not be random, here I've order the newest id, assuming id is an auto_increment field, newer id's will represent newer users.
If you echo data from the database, you need to escape that using htmlentities to prevent XSS security holes.
In mysql, like operator use '$' regex to represent end of any string.. and '%' is for beginning.. so any string will fall under this regex, that's why it returms all records.
Please refer to http://dev.mysql.com/doc/refman/5.0/en/pattern-matching.html once. Hope, this will help you.

Categories