how to do change this query into a prepared statement? - php

Right, so i'm still getting my head around prepared statements and every time i think, yeah i've got it, a new query comes along and i'm thinking Hmmmm i would i set that up?
So here we go, i have a query that pulls records from a database based on a date and orders them by said date. The records it finds are based on a year and month value and the query looks like this:
$getresults = mysql_query(" SELECT * FROM `results` WHERE `date` LIKE '2012-$monthid%' ORDER BY date ");
I already have basic prepared statement for getting a users record from my database:
$query = "SELECT *
FROM results
WHERE date = ?
LIMIT 1";
if($stmt = $this->conn->prepare($query))
{
$stmt->bind_param('s', $date);
$stmt->execute();
if($stmt->fetch())
{
$stmt->close();
return true;
}
else
return false;
}
How would i change this to make it more like the first query?
Thanks for the help.

One idea would be to filter by year and month in separate parts of the WHERE clause:
$query = "SELECT * FROM results WHERE YEAR(date) = 2012 AND MONTH(date) = ? ORDER BY date";
if ($stmt = $this->conn->prepare($query)) {
$stmt->bind_param('i', $monthid);
...
}

Related

What can be problem in this line with PDO? [duplicate]

I have a mysql query that targets a single column in a single row
"SELECT some_col_name FROM table_name WHERE user=:user"
After I execute the statement $stmt->execute(); how do I get this single cell directly placed into a variable with no loops? In other words how to get
from $stmt->execute();
to $col_value = 100;
I tried the 2 below, but neither worked.. The column is number 4 in the original table, but I'm assuming since in my select statement I'm selecting it only, it should be 1 when I specify the parameter for fetchColumn.
$col_value = $stmt->fetchColumn();
$col_value = $stmt->fetchColumn(0);
As you can see, I'm trying to do it in as few lines as possible.
Are you sure it's returning any rows?
$stmt->fetchColumn()
is correct way to fetch a single value, so either you probably didn't bind the :user parameter or it simply returned no rows.
$sql='SELECT some_col_name FROM table_name WHERE user=?';
$sth=$pdo_dbh->prepare($sql);
$data=array($user);
$sth->execute($data);
$result=$sth->fetchColumn();
I'm not sure why so many people mess this up:
$stmt = $dbh->prepare("SELECT `column` FROM `table` WHERE `where`=:where");
$stmt->bindValue(':where', $MyWhere);
$stmt->execute();
$SingleVar = $stmt->fetchColumn();
Make sure that you are selecting a specific column in the query and not * or you will need to specify the column order number in fetchColumn(), example: $stmt->fetchColumn(2); That usually isn't a good idea because the columns in the database may be reorganized by, someone...
This will only work properly with unique 'wheres'; fetchColumn() will not return an array.
When you want to get the last insert you add the DESC Limit 1 to the sql statement.
$sql = "SELECT `some_col_name` FROM table_name\n"
. "ORDER BY `some_col_name` DESC\n"
. "LIMIT 1";
$stmt = $conn->prepare($sql);
$result = $stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
//convert the array content to string and store in variable
$col = implode(" ", $row);
echo $col;
Have you prepared the statement first? (Before $stmt->execute())
$stmt = $db->prepare("SELECT some_col_name FROM table_name WHERE user=:user");
You could use this:
$stmt->fetch(PDO::FETCH_COLUMN, $number_of_column);

Query specific data from sqlite database with php

Hi there i am using a sqlite database to manage reservations on a system (written in php and html) that I built. I have managed to connect to the database and run a simple count query that runs (see code below). However i am finding it difficult to execute a query that will allow me to select reservations between two dates i.e (2018-02-20 and 2018-02-25). I have also enclosed a screenshot of my database for visualization purposes.
Code for count query:
<?php
$db = new PDO('sqlite:daypilot.sqlite');
$query = 'SELECT count(*) FROM events;';
$result = $db->query($query);
$data = $result->fetch(PDO::FETCH_ASSOC);
echo "There are {$data['count(*)']} bookings made\n";
?>
Since you'll be passing input to your query, you'll want to use a prepared statement rather than just query(). It looks like your events table has two dates, so the following query should catch all events that overlap a specified date range.
$start = '2018-02-20';
$end = '2018-02-25';
$sql = 'SELECT * FROM events WHERE `end` > ? AND `start` < ?';
$stmt = $db->prepare($sql);
$stmt->execute([$start, $end]);
$events = $stmt->fetchAll();
foreach ($events as $event) {
var_dump($event); // output with your desired formatting here
}

Sum multiuple columns

I have numbers stored in my MySQL (paid). I need to SUM the columns.
$sql= "SELECT SUM(furniture) FROM paid";
$stmt = $connect->prepare($sql);
$stmt->execute();
$furniture = (int) $stmt->fetchColumn();
$sql= "SELECT SUM(groceries) FROM paid";
$stmt = $connect->prepare($sql);
$stmt->execute();
$groceries = (int) $stmt->fetchColumn();
//so on....
There are morthan 50 columns in the database. My question is, Is there a shorter way to write this so I can get the SUM for each column and assign it to a variable?
Try with single query
$sql = "SELECT SUM(`furniture`) AS sumFurniture,
SUM(`groceries`) AS sumGroceries ,
...
FROM `paid` ";
result can be get with
$sth = $connect->prepare($sql);
$sth->execute();
$result = $sth->fetch();
$sumFurniture = $result['sumFurniture'];
$sumGroceries = $result['sumGroceries'];
....
You can combine them as a Single SQL Query
SELECT SUM(furniture) AS furniture, SUM(groceries) AS groceries....... FROM paid
If your where clause is same you can combine the query like this:
select sum(<column_name1>) column_name1,sum(<column_name2>) column_name2 from tablename where <where>
From php, you can fetch it: using array index "column_name1","column_name2"

pdo lastInsertId() keeps returning 0

I have two queries that insert data to their respective tables. That works fine. What I have been trying to do is get the lastInsertId after each query is executed and insert those values into a third table. However, when I check the database, the value 0 is entered. Both tables have an auto-incremented field. Can you tell by my code why that is happening or have any suggestions? I'm relatively new to php so if you notice the way I'm coding is untidy, particularly at the end where I execute the queries, please tell me. I'd appreciate it.
if ($oneWay)
{
$query = "INSERT INTO journey
(from_destination,to_destination,journey_type,depart_date,depart_time,seats_available,journey_message,user_type)
VALUES('$pjFrom','$pjTo','$radioJourneyType', STR_TO_DATE('$departDate','%d/%m/%Y'),'$newDepTime','$seatcounter','$textareanotes','$radUserType')";
$userID = "SELECT user_id FROM `user` ORDER BY journey_id DESC LIMIT 1";
}
else
{
$query = "INSERT INTO journey
(from_destination,to_destination,journey_type,depart_date,depart_time,return_date,return_time,seats_available,journey_message,user_type)
VALUES('$pjFrom','$pjTo','$radioJourneyType', STR_TO_DATE('$departDate','%d/%m/%Y'),'$newDepTime',STR_TO_DATE('$returnDate','%d/%m/%Y'),'$newRetTime ','$seatcounter','$textareanotes','$radUserType')";
//$userID = "SELECT user_id FROM `user` ORDER BY journey_id DESC LIMIT 1";
}
$queryfb = "INSERT INTO user
(facebook_id,facebook_username,facebook_first_name,facebook_last_name,facebook_image,facebook_link)
VALUES('$hdnFacebookId','$hdnUsername','$hdnFirstName','$hdnLastName','$hdnFacebookImg','$hdnFacebookUrl')";
//$journeyID = "SELECT journey_id FROM `journey` ORDER BY journey_id DESC LIMIT 1";
$queryUserJourney = "INSERT INTO user_journey
(user_id,journey_id)
VALUES('$lastUserID','$lastJourneyID')";
$db->exec($query);
$lastUserID = $db->lastInsertId();
$db->exec($queryfb);
$lastJourneyID = $db->lastInsertId();
$db->exec($queryUserJourney);//problem: 0 values being entered???
}
Updated
$db->exec($query);
$lastUserID = $db->lastInsertId();
$db->exec($queryfb);
$lastJourneyID = $db->lastInsertId();
$queryUserJourney = "INSERT INTO user_journey
(user_id,journey_id)
VALUES('$lastUserID','$lastJourneyID')";
$db->exec($queryUserJourney);working thanks to jmadsen
Now that I've had my coffee - you are creating the last insert statement BEFORE you populate the variables. I think this is what Maerlyn was hinting at
You need to move $queryUserJourney down below your 2 inserts.
You might want to try
$db->lastInsertId();
... instead. Note the lowercase d in lastInsertId.
Reference doc
#Colin,
PDO's last insert id returns the value of an auto-increment primary key, if I'm not completely mistaken. It looks to me like $query's table doesn't have this

Prepared statement and null value when using?

I have a need to evaluate if a user logged in to a system after a specific date. To do this, there are three tables in a MySQL database, users, survey and logins. Survey holds the date of a point in time that needs compared against the users last log in. Here's the question.
When I used the "?" placeholder, the resulting num_rows count was always 0. But when I assign the values before handing the query statement to $mysqli->prepare(), the process works as expected. Somehow, store_result() was not picking up the column. Here is my code:
if (isset($userId)){
//get survey release date
$res3 = $mysqli->query("SELECT sur_date,sur_url FROM survey ORDER BY sur_id DESC limit 1");
$array = $res3->fetch_assoc();
$theta_date = $array['sur_date'];
//$theta_date = "2013-01-18 01:00:00";
//this didn't generate errors, but didn't output the correct result either.
//$query = "SELECT login_id FROM logins WHERE login_user=? AND login_date>=?";
//if ($stmt = $mysqli->prepare($query)){
// $stmt->bind_param('ss',$userID,$theda_date);
// $stmt->execute();
//this works
$query = "SELECT login_id FROM logins WHERE login_user='$userId' AND login_date>='$theta_date'";
if ($stmt = $mysqli->prepare($query)){
$stmt->execute() or die("The query did not work");
//if number is greater than 0 do something
$stmt->store_result();
printf("The number of login ids after theta are %d",$stmt->num_rows);
$stmt->close();
}else{
echo "The query did not execute.";
}
}else{
echo "The User ID was not valid.";
exit();
}
$mysqli->close();
Any insight would be helpful,
The prepared statement seems to be having an issue with the $theta_date datetime format. $theta_date is stored in the survey table as '2013-01-18 01:00:00'. bind_param() was trying to parse $theta_date as a reference. Here is the solution:
//convert datetime to Unix timestamp with strtotime()
$theta_date = $array['sur_date'];
$timestamp = strtotime($theta_date);
//In the prepared statement, use MySQL FROM_UNIXTIME function to convert timestamp
$query = "SELECT login_id FROM logins WHERE login_user=? AND login_date>=FROM_UNIXTIME(?)";
//changed the parameter types to integer and bound $timestamp to second placeholder
if ($stmt = $mysqli->prepare($query)){
$stmt->bind_param('ii',$userId,$timestamp);
$stmt->execute();
//the rest is the same
$stmt->store_result();
printf("The number of login ids after theta are %d",$stmt->num_rows);
$stmt->close();
}
That was a pain.

Categories