Thursday, February 12

PHP MySql query, when using php variables

Based on certain php variables, we would sometime like to fetch/insert data from mysql. I always forget and find it difficult to pass the variables in the query. So below is just an example for my records.

Plain vanilla MySql query would look something like
SELECT * FROM `task_details` WHERE `users_id` = “1” AND `date` >= CURDATE() AND date < CURDATE() + INTERVAL 1 DAY

Let’s say we want to fetch data depending on the users_id. So in Php we would have a variable/session that has users_id stored in it.

$users_id  = $_SESSION[‘users_id’];
/* Without the variable the query looks like */
$query = mysql_query('SELECT * FROM `task_details` WHERE `users_id` = "1" AND `date` >= CURDATE() AND date < CURDATE() + INTERVAL 1 DAY');

/* With the variable the query would look like */
$query = mysql_query('SELECT * FROM `task_details` WHERE `users_id` = "'.$users_id.'" AND `date` >= CURDATE() AND date < CURDATE() + INTERVAL 1 DAY');

Be the first one to Comment!!!

Post a Comment