user3134759 user3134759 - 7 months ago 37
PHP Question

How to properly use variable in a query? postgresql

$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.

Answer

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?

Comments