I am trying to store the local time zone of the client on the hosting home page ut I am getting this error in my android Logcat You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 7 How can I do that? I tried it with date_default_timezone_set
I appreaciate any help.
<?php
$data = json_decode ( file_get_contents ( 'php://input', true ) );
$mac = $data->{'mac'};
$latitude = $data->{'latitude'};
$longitude = $data->{'longitude'};
$route = $data->{'route'};
$created_at = date_default_timezone_set("Europe/Berlin");
$con = new mysqli ( "domin.com", "username", "password", "ddatabase" );
// check whether route's table exist.
$results = $con->query ( "SHOW TABLES like 'bus' " ) or die ( mysqli_error () );
if (($results->num_rows) == 1) {$sql = "REPLACE INTO bus(mac, route, latitude, longitude, created_at)
VALUES( ?, ?, ? , ?, ? )";
$stmt = $con->prepare($sql);
if(false === $stmt){
echo "prepare() failed: ";
}
$rc = $stmt->bind_param("sssss",$mac,$route, $latitude,$longitude, $created_at );
echo $rc;
if ( false===$rc ) {
echo "bind_param() failed: ";
}
$rc = $stmt->execute();
if ( false===$rc ) {
echo "execute failed.";
}
$stmt->close();
} else {
$create = "CREATE TABLE bus
(id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
mac VARCHAR(30) NOT NULL UNIQUE,
route int(11) ,
latitude FLOAT(10,6) NOT NULL ,
longitude FLOAT(10,6) NOT NULL,
created_at TIMESTAMP NOT NULL" ;
$stmt = $con->prepare($create) or die ( $con->error );
$stmt->execute();
$stmt->close();
}
date_default_timezone_set returns a bool, not a date. You can use date without specifying a timestamp parameter to get the current client time. Make sure that the format of the date matches what your table expects.
Related
I am trying to use UUID's in postgres 13. I enabled the extension using the following code:
CREATE EXTENSION plpgsql;
CREATE EXTENSION "uuid-ossp";
Here is the code to create the table in postgres
CREATE TABLE IF NOT EXISTS customers.customers (
customer_id uuid DEFAULT uuid_generate_v4(),
title VARCHAR(10),
first_name VARCHAR(50) NOT NULL,
middle_name VARCHAR(50),
last_name VARCHAR(50) NOT NULL,
gender CHAR(1) NOT NULL,
date_of_birth date,
role_id INTEGER,
created_ts TIMESTAMP DEFAULT current_timestamp,
created_by VARCHAR(50) DEFAULT current_user,
updated_ts TIMESTAMP,
updated_by VARCHAR(50),
deleted_ts TIMESTAMP,
PRIMARY KEY (customer_id)
)
Here is the code I am using to insert the data into the table:
<?php
$uri = "POSTGRESQL_URI";
//$fields = parse_url($uri);
//echo $fields;
// build the DSN including SSL settings
$conn = "pgsql:";
$conn .= "host=" . '10.0.0.199'; //$fields["host"];
$conn .= ";port=" . '5432'; //$fields["port"];;
$conn .= ";dbname=savvywalletdb";
$conn .= ";sslmode=require"; // verify-ca:";
$conn .= ";sslcert=C:/MyData/Personal/Keys/client.crt";
$conn .= ";sslkey=C:/MyData/Personal/Keys/client.key";
$conn .= ";sslrootcert=C:/MyData/Personal/Keys/root.crt"; //ca.pem";
$db = new PDO($conn, "globoblanco", "Ntpxw!js9"); //$fields["user"], $fields["pass"]);
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
//SELECT * FROM pg_stat_ssl WHERE pid = pg_backend_pid()
foreach ($db->query("SELECT * FROM pg_stat_ssl") as $row) {
echo $row->version . PHP_EOL;
print($row->ssl . PHP_EOL);
}
$query = "SELECT uuid_generate_v4() as uuid";
$stmt = $db->prepare($query);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_OBJ);
echo $result->uuid;
$title = 'Mr';
$first_name = 'Gabriel';
$middle_name = 'S';
$last_name = 'Lobo-Blanco';
$gender = 'M';
$date_of_birth = '10/14/1961';
$query = "INSERT INTO customers.customers (customer_id, title, first_name, middle_name, last_name, gender, date_of_birth) ";
$query .= " VALUES(':customer_id', ':title', ':first_name', ':middle_name', ':last_name', ':gender', ':date_of_birth')";
$stmt = $db->prepare($query);
$stmt->bindValue(':customer_id', $result->uuid, PDO::PARAM_STR);
$stmt->bindValue(':title', $title, PDO::PARAM_STR);
$stmt->bindValue(':first_name', $first_name, PDO::PARAM_STR);
$stmt->bindValue(':middle_name', $middle_name, PDO::PARAM_STR);
$stmt->bindValue(':last_name', $last_name, PDO::PARAM_STR);
$stmt->bindValue(':gender', $gender, PDO::PARAM_STR);
$stmt->bindValue(':date_of_birth', $date_of_birth, PDO::PARAM_STR);
$result = $stmt->execute();
Executing this code produces the following output:
C:\WampServer\3.3.0\www\mysavvywallet (20230116 -> origin)
λ php test_db.php
TLSv1.3
1
TLSv1.3
1
6bbb3a88-4678-4ba3-aed2-4d18502106bb
Fatal error: Uncaught PDOException: SQLSTATE[HY093]: Invalid parameter number: :customer_id in C:\WampServer\3.3.0\www\mysa
vvywallet\test_db.php on line 49
PDOException: SQLSTATE[HY093]: Invalid parameter number: :customer_id in C:\WampServer\3.3.0\www\mysavvywallet\test_db.php
on line 49
Call Stack:
0.0003 425000 1. {main}() C:\WampServer\3.3.0\www\mysavvywallet\test_db.php:0
0.0304 428824 2. PDOStatement->bindValue($param = ':customer_id', $value = '6bbb3a88-4678-4ba3-aed2-4d18502106bb'
, $type = 2) C:\WampServer\3.3.0\www\mysavvywallet\test_db.php:49
The error in this output points to the following statement:
$stmt->bindValue(':customer_id', $result->uuid, PDO::PARAM_STR);
My assumption is that PHP does not support inserting UUID into postgres as I am not able to find a PDO type value I can use to match the table structure. I believe casting the UUID value generated to STRING type does not work because Postgres will check the value provided must match the column type which will cause the error.
I am thinking of a work around using stored procedures to perform the insert, but I was hoping to get a resolution to this issue without having to create that.
I am using PHP 8.2 and PostgreSQL 13.
Any suggestions anyone?
I tried using a PDO::PARAM_STR type to the bindValue() function but it does not seem to work.
The goal is to be able to execute the script and that it will perform a successful insert into the table.
I am trying to update my records with this code below but a new record is being inserted in my table every time. How can I specify the UNIQUE key to reach my aim?
This is the whole code I have in my php script plus the connection.php file, which just contains the connection statement. In my mysql I just have one database where the route_4 table is being created. My databe just consists of the route_4 table.
PHP script:
<?php
$json = '{"latitude":83.16898451,"longitude":31.16561387,"route":4}';
$data = json_decode ( $json );
$route = "route_" . $data->{'route'};
$latitude = $data->{'latitude'};
$longitude = $data->{'longitude'};
require 'connection.php';
// check whether route's table exist.
$results = $con->query ( "SHOW TABLES LIKE'" . $route . "'" ) or die ( mysqli_error () );
if (($results->num_rows) == 1) {
//"UPDATE MyGuests SET lastname='Doe' WHERE id=2"
$sql = "INSERT INTO ".$route."(id, latitude, longitude, created_at)
VALUES( id, ? , ? , NOW() )
ON DUPLICATE KEY
UPDATE latitude = VALUES(latitude)
, longitude = VALUES(longitude)";
$stmt = $con->prepare($sql) or die ( $con->error );
$stmt->bind_param("ss",$latitude,$longitude);
$stmt->execute();
$stmt->close();
echo "Table exist";
} else {
$create = "CREATE TABLE " . $route . "
(id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY UNIQUE,
latitude FLOAT(10,6) NOT NULL,
longitude FLOAT(10,6) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)" ;
$stmt = $con->prepare($create) or die ( $con->error );
$stmt->execute();
$stmt->close();
echo "table was created";
}
Make below changes in you table structure
1) Remove the existing Unique key for column id
2) Add unique for latitude and ''longitude``
ALTER TABLE `db_name`.`route_4` ADD UNIQUE (
`latitude` ,
`longitude`
)
Once you make both latitude and longitude as group of unique key then your sql query will update record on duplicate entry else will insert.
Hope this helps
I am trying to delete the last record in the table before update it but with the current state, a new one is being inserted if there are some changes in the following fiedls route, langitude, latitude. This is a database for bus tracker app where the ride can input the desired route to get it's location displayed in the google map.
I appreciate any help.
<?php
$json = '{"latitude":74.16898451,"longitude":18.16561387,"route":13}';
$data = json_decode ( $json );
$route = $data->{'route'};
$latitude = $data->{'latitude'};
$longitude = $data->{'longitude'};
require 'connection.php';
// check whether route's table exist.
$results = $con->query ( "SHOW TABLES like 'bus' " ) or die ( mysqli_error () );
if (($results->num_rows) == 1) {
//"UPDATE MyGuests SET lastname='Doe' WHERE id=2"
$sql = "REPLACE INTO bus(route, latitude, longitude)
VALUES( ?, ? , ? )";
$stmt = $con->prepare($sql) or die ( $con->error );
$stmt->bind_param("sss",$route, $latitude,$longitude);
$stmt->execute();
$stmt->close();
echo "Table exist";
} else {
$create = "CREATE TABLE bus
(id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
route int(11) NOT NULL UNIQUE,
latitude FLOAT(10,6) NOT NULL ,
longitude FLOAT(10,6) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)" ;
$stmt = $con->prepare($create) or die ( $con->error );
$stmt->execute();
$stmt->close();
echo "table was created";
}
I am implementing an app that creates the JSON String below. The app records the JSON data and send it in the background to the server every 60 seconds. The user can use the app to query the server for the buses locations, the result will be displayed in google map with marker.
The data of JSON will be first inserted in the bus table and then updated with INSERT INTO. In the bus table I do not have any UNIQUE key so I should add someone bus_id to the JSON string in the app to know which record must be updated so I am asking myself whether is it possible to generate it and then add it to the JSON string before sending it. How can I generate bus_id UNIQUE key in my case?
JSON object:
{
"latitude":84.16898451,
"longitude":3.16561387,
"route":45
}
PHP script.
<?PHP
$json = '{"bus_id": "gernerated value", "latitude":84.16898451,"longitude":3.16561387,"route":45}';
$data = json_decode ( $json );
$bus_id = "it should be generated in the app";
$route = $data->{'route'};
$latitude = $data->{'latitude'};
$longitude = $data->{'longitude'};
require 'connection.php';
// check whether route's table exist.
$results = $con->query ( "SHOW TABLES like 'bus' " ) or die ( mysqli_error () );
if (($results->num_rows) == 1) {
//"UPDATE MyGuests SET lastname='Doe' WHERE id=2"
$sql = "REPLACE INTO bus(bus_id, route, latitude, longitude)
VALUES( ?, ?, ? , ? )";
$stmt = $con->prepare($sql) or die ( $con->error );
$stmt->bind_param("ssss",$bus_id,$route, $latitude,$longitude);
$stmt->execute();
$stmt->close();
echo "Table exist";
} else {
$create = "CREATE TABLE bus
(id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
bus_id INT(11) NOT NULL UNIQUE,
route int(11) NOT NULL,
latitude FLOAT(10,6) NOT NULL ,
longitude FLOAT(10,6) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)" ;
$stmt = $con->prepare($create) or die ( $con->error );
$stmt->execute();
$stmt->close();
echo "table was created";
}
I have a script that creates a SQL table for me as below
if ($con = mysql_connect($host, $username, $password)) {
if (mysql_select_db($db_name)) {
$sql = "CREATE TABLE ".$ac_system."_credits (id INT NOT NULL
AUTO_INCREMENT , PRIMARY KEY (id) , account_nr CHAR(10) , credits CHAR(10))";
if (mysql_query($sql, $con)) {
$insertSuccessful = true;
} else {
echo $sql;
print_r($_POST);
echo "\n" . mysql_error($con);
echo "mysql err no : " . mysql_errno($con);
}
I would like to add another line/s to populate the above table with fixed information
ID - 1
Credits - 10
ACCOUNT_NR - 1
The above data is constant and doesn't need to be changed once the table is created I am not sure how to populate it in conjunction with the creation of the table. I can populate it from a seperate PHP script but need all to be done on one page
Maybe you should execute another one query just after successful table creation:
//some php code here
$insertSuccessful = true;
mysql_query( "INSERT INTO $ac_system ( account_nr, credits ) VALUES ( '1', '10' )", $sql );
// and here