Im working in postgres 8.4 and PHP 5.4.3 using pg_query_params. I have a table called armies taht have 3 rows (well only for this example, it really have more). the id is an integer and the other two are timestamp withouth timezone. Now the SQL insert is:
INSERT INTO public.armies(id,build_start,build_end) VALUES ($1,$2,$3)
And the array I'm inserting is:
$data['id'] = 1;
$data['build_start'] = "now()";
$data['build_end'] = "now() + time '00:00:50'";
The error is E_WARNING: pg_query_params(): Query failed: ERROR: invalid input syntax for type timestamp: «now() + time '00:00:50'»
Its works when i tried to insert it as a raw sql using pg_query like : INSERT INTO public.armies(id,build_start,build_end) VALUES (11935,now(),now() + time '00:00:50').
So I guess it has something to do with the pg_query_params(), I really really want to insert it using pg_query_params.
What I want to achieve is sum that now() with that 00:00:50 seconds, so i can manage to alter that $data['build_end'].
Please do note that you are passing string literals
$data['build_start'] = "now()";
$data['build_end'] = "now() + time '00:00:50'";
to pg_query_params which cannot prepare a valid date/time value from "now()" or "now() + time '00:00:50'".
Instead of
INSERT INTO public.armies(id,build_start,build_end) VALUES ($1,$2,$3);
change it to
INSERT INTO public.armies(id,build_start) VALUES ($1,now());
and remove the parameters
$data['build_start'] = "now()";
$data['build_end'] = "now() + time '00:00:50'";
Now when the action completes, update the table.
UPDATE public.armies SET build_end=now() WHERE id=$1;
Hope I was able to help you.
Related
I have a PHP file which calls Stored Procedure from MSSQL. The stored procedure calculate the value and store into a temp table. When I call the stored procedure from PHP like this
$cmd="exec get_value ".implode(",",$parameter_arr);
$result = mssql_query("SET ANSI_NULLS ON;");
$result = mssql_query("SET ANSI_WARNINGS ON;");
$result= mssql_query($cmd,$conn) or die("Error :".mssql_get_last_message());
The value return was only "::" without integer number.
When I run the stored procedure in T-Sql, it returns the correct value '02:15:00' T-SQL output
I am using PHP 5.3.3. Do I need to upgrade my php? Or why I cannot display the value correctly in PHP?
I have no control over the stored procedure. But I need to display the result into my php page. However, the result come incompletely. Some values are returning and some are not. Those value with heavy calculation in SELECT statement has problem displaying in PHP page. Like
SELECT CASE WHEN LEN(CONVERT(VARCHAR,CONVERT(INT,ETS_PhoneHours*1.0))) = 1 THEN '0' + CONVERT(VARCHAR,CONVERT(INT,ETS_PhoneHours*1.0)) ELSE CONVERT(VARCHAR,CONVERT(INT,ETS_PhoneHours*1.0)) END + ':'
+ CASE WHEN LEN(CONVERT(VARCHAR,CONVERT(INT,(ETS_PhoneHours*1.0 - CONVERT(INT,ETS_PhoneHours*1.0))*60) )) = 1 THEN '0' + CONVERT(VARCHAR,CONVERT(INT,(ETS_PhoneHours*1.0 - CONVERT(INT,ETS_PhoneHours*1.0))*60) ) ELSE CONVERT(VARCHAR,CONVERT(INT,(ETS_PhoneHours*1.0 - CONVERT(INT,ETS_PhoneHours*1.0))*60) ) END + ':'
+ CASE WHEN LEN(SUBSTRING(CONVERT(VARCHAR,CONVERT(INT,((ETS_PhoneHours*1.0 - CONVERT(INT,ETS_PhoneHours*1.0))*60 - CONVERT(INT,(ETS_PhoneHours*1.0 - CONVERT(INT,ETS_PhoneHours*1.0))*60))*60)),1,2)) = 1 THEN '0' + SUBSTRING(CONVERT(VARCHAR,CONVERT(INT,((ETS_PhoneHours*1.0 - CONVERT(INT,ETS_PhoneHours*1.0))*60 - CONVERT(INT,(ETS_PhoneHours*1.0 - CONVERT(INT,ETS_PhoneHours*1.0))*60))*60)),1,2) ELSE SUBSTRING(CONVERT(VARCHAR,CONVERT(INT,((ETS_PhoneHours*1.0 - CONVERT(INT,ETS_PhoneHours*1.0))*60 - CONVERT(INT,(ETS_PhoneHours*1.0 - CONVERT(INT,ETS_PhoneHours*1.0))*60))*60)),1,2) END
AS 'ETS_Program_Hours'
This will only return :: to my mssql_query.
Anyone face the similar issue before?
Please advice. Thanks
Why don't you use CONVERT?
SELECT CONVERT(nvarchar(40),ETS_PhoneHours,108) AS 'ETS_Program_Hours'
I'm trying to filter out repeated values entering into a MySQL table, by comparing the input PHP variable with the timestamp of an entry already present in the table and only if they don't match, the input PHP variable is entered into the table.
$user1_date = mysql_real_escape_string($user1_date); // the date variable
$user1_temp1 = mysql_real_escape_string($user1_temp1);
$user1_temp2 = mysql_real_escape_string($user1_temp2);
$user1_temp3 = mysql_real_escape_string($user1_temp3);
$user1_date = date("Y-m-d H:i:s", strtotime($user1_date)); //Typecasting PHP variable into timestamp
$sql_check = "SELECT * FROM user_details WHERE temp_date ='$user1_date'";
$result_check = mysql_query($sql_check);
$num_rows_check = mysql_num_rows($result_check);
if ($num_rows_check == 0) // To check if there is no entry in the table with the same date and time as input PHP variable
{
$sql_insert = "INSERT INTO data_hour (user_id, temp1, temp_date, temp2, temp3)
VALUES (1,'$user1_temp1', '$user1_date', '$user1_temp2', '$user1_temp3')";
$result_insert = mysql_query($sql_insert);
}
temp_date is a column in the table of type timestamp. Even when the $user1_date is the same as the temp_date(timestamp) column for one of the entries in the table, it considers it as not equal and is inserting it into the table and hence I'm getting repeated values. I'm guessing the WHERE temp_date = '$user1_date'is not working properly. Some troubleshooting that I have done included
Changing '$user1_date' to just $user1_date in the WHERE
statement
Changing the WHERE clause as follows WHERE temp_date = (date)'$user1_date'
It will be great if somebody can help me out with this!
A nice easy solution would be giving temp_date a UNIQUE INDEX in your Mysql Table, as that would not allow the same value to be inserted twice. This would also make your operations more efficient, as you wouldn't have to do SELECT * every time you want to insert something.
However, for what you're doing, I think I see your problem; there are some quirks in your logic so I'll try to dispel them here. (Hopefully?) this will make your program cleaner and you'll be able to pinpoint the error, if not eliminate it altogether.
Examining this piece of code:
// $user1_date doesn't have a value here! //
$user1_date = mysql_real_escape_string($user1_date);
...
$user1_date = date("Y-m-d H:i:s", strtotime($user1_date));
Error 1 - You escape the string before ever setting a value.
What you are doing is that you are using mysql_real_escape_string() before $user1_date is ever defined.
Correction:
// Getting better, but not done. //
$user1_date = date("Y-m-d H:i:s", strtotime($user1_date));
...
$user1_date = mysql_real_escape_string($user1_date);
Error 2 - You do not give the date() function appropriate parameters
The date() function in PHP expects a timestamp, which is just an int. You can easily get the time with time(), so that should rectify your problem
Correction:
// You use strtotime($user1_date), but you should use time() //
$user1_date = date("Y-m-d H:i:s", time());
...
$user1_date = mysql_real_escape_string($user1_date);
These are small mistakes, but they can be deadly. Like I said, you should assign temp_date to a UNIQUE INDEX in your MySQL table, but make sure to correct these errors listed as well.
Let me know how it goes!
I'm trying to pass a MySQL's NOW() function into PDO's assigned value through PHP and it's failing. I found that I must pass this directly into MySQL statement. But in my case, sometimes the datetime field can be empty.
Is it even possible to pass NOW() as PHP's assigned value?
Some code:
I'm building query dynamically and the datetime is dependent on some other variable's value.
if(isset($accountStatus)&&$accountStatus!=""){
$tmp[':account_status']=$accountStatus;
if($accountStatus==0){
$tmp[':vCodeExpire']="NOW() + INTERVAL 1 WEEK";
$tmp[':verified']=0;
}else{
$tmp[':verified']=1;
}
}
Building SQL query:
$sql="";
foreach($tmp as $k=>$v){
$sql.=str_replace(":","",$k)."=".$k.",";
}
$sql=substr($sql,0,strlen($sql)-1);
Then, I run PDO query:
$db=$pdo->prepare("UPDATE users SET $sql WHERE id=:id");
$db->execute($tmp);
I tried replacing double-quotes with single-quote around NOW() + INTERVAL 1 WEEK with no luck.
I also tried with single-quote around PDO query, but then $sql is passed directly, not using an assigned values.
is it possible?
No.
There are 2 solutions.
Calculate expiration date using PHP. Something like date('Y-m-d',strtotime('+1 week'))
Create a conditional part for the query
if(isset($accountStatus)&&$accountStatus!=""){
$tmp[':account_status']=$accountStatus;
if($accountStatus==0){
$accSql = "NOW() + INTERVAL 1 WEEK,";
$tmp[':verified']=0;
}else{
$accSql ='';
$tmp[':verified']=1;
}
$db=$pdo->prepare("UPDATE users SET $accSql $sql WHERE id=:id");
Use strtotime() instead of MySQL to get date values.
I am making a meeting room booking system in which there should be no times within the start and end dates so in theory the validation should check for no dates/times within one start and end date time frame.
I have two tables, I can insert into it fine with both start and end dates so the only columns i am interested in at the moment are these
meetingrooms
|------------------------------------||- bookingtime -|-bookingend-|
I understand the principle behind the sanity check and the check i can do in psudocode. Here is the code i have got so far -
>
p4a_db::singleton()->query("INSERT INTO meetingrooms(location_id, bookingtime, bookingend, merono_id)
WHERE bookingtime < " . $date . " AND bookingend > " . $date . "
OR
bookingdate < " . $date . " AND bookingend > " . $dateend . "
VALUES(?,?,?,?)",
array($location, $date, $dateend, $merono));
I don't want to insert data directly into the statement but until i understand how to do this i am stuck, so the question,
How do i perform a sanity check before the data is inserted so that i don't get dates within booked times.
any help would be greatly appreciated.
Edit:
I've been overthinking my answer and I realized that the old solution will not work in your case since you need the time span, comparing the start and end date is useless.
My way of processing this would be:
Save the dates as int, use 24h system (7:40am is 740, 9:50pm is 2150)
Check for stored dates where: (Start<NewStart<End)
Check for stored dates where: (Start<NewEnd<End)
When processing several rooms, just store room number + time as int. That way you can still use the method from 2 and 3.
2 and 3 can be done in a sql query, check out this link.
Old answer (checking for duplicates)
This is an example of how to check for duplicates (in this case email) before inserting the text:
$emailexist = $mysqli->prepare("select email from users where email = ?");
$emailexist->bind_param('s', $email);
$emailexist->execute();
$emailexist->store_result();
if ($emailexist->num_rows > 0) {
$emailexist->close();
$mysqli->close();
return true;
}
else {
$emailexist->close();
$mysqli->close();
return false;
}
It checks if there are rows which contain the string. If so (if number of rows higher than 0) it returns true (which means, the date already exists).
You can just adapt this to you code.
However, you could also just set the columns to UNIQUE. Then you get an error when trying to insert it. It is easier and you won't have problems with concurrent connections.
after a long and intensive search, I have now got a working example of this method, along with a method of protecting against sql injection, here's the code;
if ($this->BookingValue == 1)
{
$sql = "SELECT COUNT(*) as num FROM meeting_room_bookings
WHERE
(
(? < start_at AND ? > start_at)
OR
(? > start_at AND ? < end_at)
)
AND
meeting_room_id = ?";
$result = p4a_db::singleton()->fetchRow($sql, array($date, $date, $date, $dateend, $merono));
if ( 0 == $result["num"] )
{
p4a_db::singleton()->query("INSERT INTO meeting_room_bookings (start_at, end_at, meeting_room_id)
VALUES
(?,?,?)", array($date, $dateend, $merono));
return true;
}
else
{
return false;
There isn't much to explain about this code, but in term of differences, (excluding the change in column names with the table) the query is now prepared before the value is set, then it is possible to use it in an if statement, thus allowing the validation to take place to filter results between different dates.
along with this i have added validation to stop dates from other meeting rooms being included within the statement via the AND statement where the meeting room id is limeted to a single value.
Although now, which will lead on to a separate question is another thrown error that comes from this statement, i know the insert is sound but something from this prepared statement causes the error:
SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens
File: Pdo.php, Line: 234
Although now i am looking into a error that is thrown from the prepared statement and will update this answer when there is a fix, thanks for the help.
I'm trying to use a MERGE INTO statement in my php file to update or insert into a MySQL database for a multiplayer game.
Here's a full description of what I'm trying to accomplish:
The php file is called with the following line from a javascript file:
xmlhttp.open('GET', "phpsqlajax_genxml.php?" + "lat=" + lla[0] + "&heading=" + truckHeading + "&lng=" + lla[1] + "&velocity0=" + vel0 + "&velocity1=" + vel1 + "&velocity2=" + vel2 + "&id=" + playerNumber, true);
This will be sending the php file information to update the database with. Either this will be a new player and the first time this information has been sent, meaning that a new row in the database will be created, or it will be a current player who just needs to have their information updated.
If it is a new player the "id" that is sent will be one that doesn't yet exist in the database.
For some reason the database isn't being updated, nor are new rows being added. I'm thinking it's a syntax error because I don't have much experience using MERGE statements. Could someone with experience with this please let me know what I might be doing wrong?
Here is the code before the MERGE INTO statement so you can understand which variables are which:
$id = $_GET['id'];
$lat = $_GET['lat'];
$lng = $_GET['lng'];
$heading = $_GET['heading'];
$velocity0 = $_GET['velocity0'];
$velocity1 = $_GET['velocity1'];
$velocity2 = $_GET['velocity2'];
id is the column heading, $id is the id being passed in
Here is my current MERGE INTO statement in my php file:
MERGE INTO markers USING id ON (id = $id)
WHEN MATCHED THEN
UPDATE SET lat = $lat, lng = $lng, heading = $heading, velocityX = $velocity0, velocityY = $velocity1, velocityZ = $velocity2
WHEN NOT MATCHED THEN
INSERT (id, name, address, lat, lng, type, heading, velocityX, velocityY, velocityZ) VALUES ($id, 'bob', 'Poop Lane', $lat, $lng, 'Poop', $heading, $velocity0, $velocity1, $velocity2)
PHP's database libraries invariably have their various function calls return FALSE if anything failed during the call. Assuming you're on mysql_/mysqli_, then you shoudl be doing something like this:
$sql = "MERGE INTO ....";
$result = mysql_query($sql);
if ($result === FALSE) {
die(mysql_error());
}
It is poor practice to NOT check the return values from database calls. Even if the query string is 100% syntactically valid, there's far too many ways for a query to fail. Assuming everything works is the easiest way to get yourself into a very bad situation. As well, when things do fail, the lack of error handling will simply hide the actual reason for the error and then you end up on SO getting answers like this.
Oh, and before I forget... MySQL doesn't support "MERGE INTO...", so your whole query is a syntax error. Look into using "REPLACE INTO..." or "INSERT ... ON DUPLICATE KEY UPDATE ..." instead.