Php mysql prepared statements wont insert - php

I have a weird issue that's driving me crazy.
The first time I insert data into a mysql table, it works. It fails silently after that.
This is the table:
$students =
'CREATE TABLE IF NOT EXISTS students (
student_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
nombre VARCHAR(255) NOT NULL,
apellido VARCHAR(255) NOT NULL,
natalicio INT NOT NULL,
cuil INT UNIQUE NOT NULL,
trabajador_teatro TINYINT NOT NULL,
ocupacion VARCHAR(255),
derivado_ministerio TINYINT NOT NULL,
ex_alumno TINYINT NOT NULL,
intereses VARCHAR(255),
matricula VARCHAR(255) NOT NULL,
estudios_formales VARCHAR(255),
domicilio VARCHAR(255),
mail VARCHAR(255) NOT NULL,
mail_confirmation_key VARCHAR(255) ,
created INT,
tel INT NOT NULL,
active TINYINT NOT NULL
)';
This is the method that inserts the data, remember, first insert works well:
/
/Insert user data
public function insertStudent($options, $db_object) {
$sql='INSERT INTO students (nombre, apellido, natalicio, cuil, trabajador_teatro, ocupacion,
derivado_ministerio, ex_alumno, intereses, matricula, estudios_formales, domicilio, mail, mail_confirmation_key,
created, tel, active)
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)';
if (is_array($options) ) {
$nombre = $options['nombre'];
$apellido = $options['apellido'];
$natalicio = $options['natalicio'];
$cuil = $options['cuil'];
$trabajador_teatro = $options['trabajador_teatro'];
$ocupacion = $options['ocupacion'];
$derivado_ministerio = $options['derivado_ministerio'];
$ex_alumno = $options['ex_alumno'];
$intereses = $options['intereses'];
$estudios_formales = $options['estudios_formales'];
$domicilio = $options['address'];
$mail = $options['mail'];
$tel = $options['tel'];
}//End if
$mail_confirmation_key = $this->mailConfKey();
$date = new DateTime();
$created = $date->getTimestamp();
$active = 0;
$matricula = 'TAE'."-".ceil((substr($cuil, 4)+$created)/5);
/* Prepare statement */
$stmt = $db_object->prepare($sql);
if($stmt === false) {
trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $db_object->error, E_USER_ERROR);
}//End if
/* Bind parameters. TYpes: s = string, i = integer, d = double, b = blob */
$stmt->bind_param('ssiiisiissssssiii',$nombre, $apellido, $natalicio, $cuil, $trabajador_teatro, $ocupacion, $derivado_ministerio,
$ex_alumno, $intereses, $matricula, $estudios_formales, $domicilio, $mail, $mail_confirmation_key, $created, $tel, $active);
/* Execute statement */
$stmt->execute();
echo $stmt->insert_id;
echo $stmt->affected_rows;
$stmt->close();
}//End insertStudent
There are no apache2 log errors. These are mysql logs, the first query that works, and the subsequent one that does not work.
First Query
61 Prepare INSERT INTO students (nombre, apellido, natalicio, cuil, trabajador_teatro, ocupacion,
derivado_ministerio, ex_alumno, intereses, matricula, estudios_formales, domicilio, mail, mail_confirmation_key,
created, tel, active)
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
61 Execute INSERT INTO students (nombre, apellido, natalicio, cuil, trabajador_teatro, ocupacion,
derivado_ministerio, ex_alumno, intereses, matricula, estudios_formales, domicilio, mail, mail_confirmation_key,
created, tel, active)
VALUES ('Diego','Lopez',1395975600,20218976543,1,'Surfer',1,0,'Volar','TAE-280617849','primario','20 1122','test#test.com','jtvSRLYfU8uyiHVh6gPp',1394$
61 Close stmt
Second query
72 Prepare INSERT INTO students (nombre, apellido, natalicio, cuil, trabajador_teatro, ocupacion,
derivado_ministerio, ex_alumno, intereses, matricula, estudios_formales, domicilio, mail, mail_confirmation_key,
created, tel, active)
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
72 Close stmt
72 Quit
I fetch data from $_POST and use it. It's just a beta, I know it's not properly sanitized.
$nombre = stripcslashes($_POST['nombre']);
$apellido = stripcslashes($_POST['apellido']);
$natalicio = $core->formatTimeToUs($_POST['birthday']);
$mail = $_POST['mail'];
$address = stripcslashes($_POST['address']);
$tel = stripcslashes($_POST['tel']);
$cuil = stripcslashes($_POST['cuil']);
$curso = stripcslashes($_POST['curso']);
$niv_educ = stripcslashes($_POST['niv_educ']);
$trabajador_teatro = stripcslashes($_POST['trabajador_teatro']);
$ocupacion = stripcslashes($_POST['ocupacion']);
$derivado_ministerio = stripcslashes($_POST['derivado_ministerio']);
$ex_alumno = stripcslashes($_POST['ex_alumno']);
$intereses = stripcslashes($_POST['intereses']);
$estudios_formales = stripcslashes($_POST['niv_educ']);
$student = new student();
$student_user_array = array('nombre'=>$nombre, 'apellido'=>$apellido , 'natalicio' => $natalicio, 'cuil'=>$cuil, 'mail' => $mail, 'address' => $address, 'tel' => $tel,
'curso'=>$curso, 'niv_educ'=>$niv_educ, 'trabajador_teatro' => $trabajador_teatro, 'ocupacion' => $ocupacion,
'ex_alumno' => $ex_alumno, 'intereses'=>$intereses, 'estudios_formales'=> $estudios_formales, 'derivado_ministerio'=>$derivado_ministerio);
$student->insertStudent($student_user_array, $conn);
Hope someone can point me in the right direction.
Thanks in advance.
Sebastian

Related

Calling mysql procedure from php with in and out paramenter

Please help me out. I'm trying to insert the records in 2 tables, in 1st table I can insert but for the second table I can't.
I have 3 stored procedures
HotelInsert
GetAccommodationByName
AvailbiltyInsert
It seems like the 1st stored procedure is okay as I can get output in the first table but in the second table I can't get the last inserted id.
First stored procedure
DELIMITER $$
CREATE DEFINER=`kno`#`localhost` PROCEDURE `HotelInsert`(IN `ZIP` BIGINT, IN `Ammn` VARCHAR(255), IN `HotelName` VARCHAR(255), IN `Add1` VARCHAR(255), IN `Add2` VARCHAR(255), IN `Det` VARCHAR(255), IN `ContactPer` VARCHAR(255), IN `Contact` VARCHAR(255), IN `CEmail` VARCHAR(255), IN `Image` VARCHAR(255), IN `StarCateg` TINYINT)
NO SQL
DETERMINISTIC
INSERT INTO Accommodation(
AccommodationId,
AccommodationTypeId,
ZipId,
PackageId,
Amenities,
Name,
AddressOne,
AddressTwo,
AccommodationStatus,
Details,
ContactPerson,
StarCategory,
ImageGallery,
ContactPhone,
ContactEmail
)
VALUES(
NULL,
1,
ZIP,
4,
Ammn,
HotelName,
Add1,
Add2,
1,
Det,
ContactPer,
StarCateg,
Image,
Contact,
CEmail
)$$
DELIMITER ;
Second stored procedure:
DELIMITER $$
CREATE DEFINER=`kno`#`localhost` PROCEDURE `GetAccomodationIdByName`(IN `AccommodationName` VARCHAR(255), OUT `AccId` INT)
NO SQL
DETERMINISTIC
SELECT AccommodationId into AccId from Accommodation where Name=AccommodationName$$
DELIMITER ;
Third stored procedure:
DELIMITER $$
CREATE DEFINER=`kno`#`localhost` PROCEDURE `AvailabilityInsert`(IN `AccId` INT, IN `RTypeId` INT, IN `AvailableRooms` INT, IN `Charges` BIGINT, IN `AvailDate` DATE)
NO SQL
INSERT INTO AccommodationAvailabilty (AvailableId, AccommodationId, RoomTypeId, Available, Price, AvailableDate) VALUES (NULL, AccId, RTypeId, AvailableRooms, Charges, AvailDate)$$
DELIMITER ;
PHP code:
$sql = $db->prepare('CALL HotelInsert(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');
$sql->bind_param('dssssssssss', $ZipId, $Amenities, $Name, $AddressOne, $AddressTwo, $Details, $ContactPerson, $ContactPhone, $ContactEmail , $target_path, $StarCategory);
$sql->execute();
$select = $db->query('SELECT #ZIP,#Ammn, #HotelName, #Add1, #Add2, #Det, #ContactPer,#Contact,#CEmail,#Image, #StarCateg');
$result = $select->fetch_assoc();
$ZipId = $result['#ZIP'];
$Amenities = $result['#Ammn'];
$AccommodationName = $result['#HotelName'];
$AddressOne = $result['#Add1'];
$AddressTwo = $result['#Add2'];
$Details = $result['#Det'];
$ContactPerson = $result['#ContactPer'];
$ContactPhone = $result['#Contact'];
$ContactEmail = $result['#CEmail'];
$target_path = $result['#Image'];
$StarCategory = $result['#StarCateg'];
//Hotel Calling AccommodationId by AccommodationName with GetAccomodationIdByName(); stored procedure.
$sql = $db->prepare('CALL GetAccomodationIdByName(?)');
$sql->bind_param('s', $AccommodationName);
$sql->execute();
$select = $db->query('SELECT #AccId');
$result = $select->fetch_assoc();
$AccommodationId = $result['#AccId'];
//Hotel Insert RoomType by calling AvailabilityInsert(); Store procedure.
$sql = $db->prepare('CALL AvailabilityInsert(?,?,?,?,?)');
$sql->bind_param('iiids', $AccommodationId, $RoomTypeId, $Available, $Price, $AvailableDate);
$sql->execute();
$select = $db->query('SELECT #AccId,#RTypeId, #AvailableRooms, #Charges, #AvailDate');
$result = $select->fetch_assoc();
$AccommodationId = $result['#AccId'];
$RoomTypeId = $result['#RTypeId'];
$Available = $result['#AvailableRooms'];
$Price = $result['#Charges'];
$AvailableDate = $result['#AvailDate'];
header("Location: ../hotel-all.php?id=$Name");
exit();

How to get values from stores and insert into products table?

I am new to statements, so please come slowly on me. I have checked questions asked by others but didnt see a solution to solve my issue.
I am trying to create a userpage with prepared statements so they can add products to their stores.
I would like to get store_id from stores and insert into produtcs on an insert product form.
I have tried several methods but they didnt work.
Here are my attempts:
Connection
$mysqli = new mysqli(host, dbase, username, password);
First method prepare statements: I have tried this method without bind_result too.
if ($stmt = $mysqli->prepare("INSERT INTO products (user_id, cat_id, store_id, item_name, item_code, item_description, item_qtty, item_price, item_seo_url, item_image, item_date) SELECT store_id FROM stores WHERE user_id = ?")) {
$stmt->bind_param("i", $user_id);
$user_id = filterString($_SESSION['id']);
$stmt->execute();
$stmt->bind_result($store_id);
if($stmt->fetch()){
echo " Records created successfully. Redirect to landing page";
header("location: index.php");
exit();
} else{
echo "Something went wrong. Please try again later.";
}
}
$stmt->close();
Second method sql prepare statements: I have tried this too but didnt work:
$sql = "INSERT INTO products (user_id, cat_id, store_id, item_name, item_code, item_description, item_qtty, item_price, item_seo_url, item_image, item_date) SELECT ?, store_id FROM stores WHERE user_id = ?";
if($stmt = $mysqli->prepare($sql)){
$stmt->bind_param("iiisiisiisss", $user_id, $cat_id, $store_id, $item_name, $item_code, $item_description, $item_qtty, $item_price, $item_seo_url, $item_image, $item_date);
$user_id = $_SESSION['id'];
$cat_id = $cat_id;
$store_id = $store_id;
$item_name = $item_name;
$item_code = $item_code;
$item_description = $item_description;
$item_qtty = $item_qtty;
$item_price = $item_price;
$store_seo_url = seo_url($item_name);
$item_image = $vtyol;
$item_date = $date;
if($stmt->execute()){
echo " Records created successfully. Redirect to landing page";
header("location: index.php");
exit();
} else{
echo "Something went wrong. Please try again later.";
}
}
$stmt->close();
Didnt have a chance to get store_id from stores, I echo store ID in page to see if I get it, its empty.
how can I make it work ?
Do I need to declare all values in bind_param in first method ? (I tried and didnt work).
if so, how to add clause $stmt->bind_param("i", $user_id);.
I really dont know what else to try, need your advice and helps.
Gtg to hospital now be back in 1 hour, will answer your questions and answers.
Thank you all
Last example I tried with the code from #Michael Eugene Yuen it keep saying something went wrong, because of cant get $store_id from stores table.
My codes were to long so I shortened them and tried getting same result.
Here is last example not wroking:
$sql = "INSERT INTO products (
user_id, store_id, name, salary
)
SELECT ?, ?, ?, ?,
`store_id` FROM stores WHERE user_id = ?";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("iisii", $user_id, $store_id, $name, $salary, $user_id);
$user_id = $user_id;
$store_id = $store_id;
$name = $name;
$salary = $salary;
if($stmt->execute()){
header("location: index.php");
exit();
} else{
echo "Something went wrong. Please try again later.";
}
$stmt->close();
Database struckter for both tables:
CREATE TABLE IF NOT EXISTS `products` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` varchar(100) NOT NULL,
`store_id` varchar(100) NOT NULL,
`name` varchar(255) NOT NULL,
`salary` int(10) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
CREATE TABLE IF NOT EXISTS `stores` (
`store_id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` varchar(100) NOT NULL,
`name` varchar(255) NOT NULL,
`salary` int(10) NOT NULL,
PRIMARY KEY (`store_id`)
) ENGINE=MyISAM AUTO_INCREMENT=3 DEFAULT CHARSET=latin1;
INSERT INTO `stores` (`store_id`, `user_id`, `name`, `salary`) VALUES
(1, '12', 'aaaaaaaaaaad', 12),
(2, '12', 'sada', 1234656);
Your were trying to insert data into 11 columns but only 1 value was passed into your statements
Your statement should look like this:
$sql = "INSERT INTO products (
user_id, cat_id, item_name, item_code, item_description,
item_qtty, item_price, item_seo_url, item_image, item_date,
store_id
)
SELECT ?, ?, ?, ?, ?,
?, ?, ?, ?, ?,
`store_id` FROM stores WHERE user_id = ?";
$stmt = $mysqli->prepare($sql);
Bind your $user_id twice. The first one is for your first placeholder and the last one is for your sub-select statement (bind_param)
$stmt->bind_param("iisisiisssi", $user_id, $cat_id, $item_name, $item_code, $item_description, $item_qtty, $item_price, $item_seo_url, $item_image, $item_date, $user_id);
$user_id = $_SESSION['id'];
$cat_id = $cat_id;
$item_name = $item_name;
$item_code = $item_code;
$item_description = $item_description;
$item_qtty = $item_qtty;
$item_price = $item_price;
$store_seo_url = seo_url($item_name);
$item_image = $vtyol;
$item_date = $date;
if($stmt->execute()){
echo " Records created successfully. Redirect to landing page";
$stmt->close();
header("location: index.php");
exit();
} else{
echo "Something went wrong. Please try again later.";
}
And based on your newly added Example 2, the number of columns, placeholders mismatch the number of bind_param again. Also, when you look at your stores table, you have two records under the same user_id. So which store_id you expect to insert to your store table?
I have used LIMIT 1 for now but certainly this is not the correct approach.
$sql = "INSERT INTO products (
user_id, name, salary, store_id
)
SELECT ?, ?, ?, `store_id` FROM stores WHERE user_id = ? LIMIT 1";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("isii", $user_id, $name, $salary, $user_id);
$user_id = 12;
$name = 'john';
$salary = 1200;
if($stmt->execute()){
header("location: index.php");
exit();
} else {
echo "Something went wrong. Please try again later.";
}
$stmt->close();
This is an sql statement with hardcoded values:
$sql = "INSERT INTO products (
user_id, name, salary, store_id
)
SELECT 12, 'john', 1200,
`store_id` FROM stores WHERE user_id = 12 LIMIT 1";
This is same statement with variables:
$sql = "INSERT INTO products (
user_id, name, salary, store_id
)
SELECT $user_id, $name, $salary,
`store_id` FROM stores WHERE user_id = $user_id LIMIT 1";
This is same statement with placeholders:
$sql = "INSERT INTO products (
user_id, name, salary, store_id
)
SELECT ?, ?, ?,
`store_id` FROM stores WHERE user_id = ? LIMIT 1";
$stmt->bind_param("isii", $user_id, $name, $salary, $user_id);
$user_id = 12;
$name = 'john';
$salary = 1200;

Complicated SQL insert-update with inner select

I have to make a query, which inserts-or-updates in 1 line.
EDIT: I add the WORKING SQL query here.
$this->sqlSavePlot = $this->db->prepare(
"INSERT OR REPLACE INTO plots (id, level, X, Z, name, owner, helpers, denied, biome) VALUES
((select id from plots where level = :level AND X = :X AND Z = :Z),
:level, :X, :Z, :name, :owner, :helpers, :denied, :biome);"
);
Theoretically i want the same stuff in prepared MySQL statements
Currently the mess looks like this:
$this->sqlSavePlot = $this->db->prepare(
"INSERT INTO plots (`id`, `level`, `X`, `Z`, `name`, `owner`, `helpers`, `denied`, `biome`)
VALUES(id = (SELECT id FROM plots WHERE level = level AND X = VALUES(X) AND Z = VALUES(Z)), level = ?, X = ?, Z = ?, name = ?, owner = ?, helpers = ?, denied = ?, biome = ?)
ON DUPLICATE KEY UPDATE
id = VALUES(id),
level = VALUES(level),
X = VALUES(X),
Z = VALUES(Z),
name = VALUES(name),
owner = VALUES(owner),
helpers = VALUES(helpers),
denied = VALUES(denied),
biome = VALUES(biome);"
);
As you see, quite chaotic.
This is how the database looks like:
So in theory, if the user executes the savePlot function, several fields are replaced, like you can see in the PHP code. "sqlSavePlot" is the query i showed above
For some deeper explanation some PHP code:
public function savePlot(Plot $plot): bool{
print "------------------------------------------------------".PHP_EOL;
$this->db->ping();
$helpers = implode(',', $plot->helpers);
$denied = implode(',', $plot->denied);
if ($plot->id <= 0){
$stmt = $this->sqlSavePlot;
$stmt->bind_param('siisssss', $plot->levelName, $plot->X, $plot->Z, $plot->name, $plot->owner, $helpers, $denied, $plot->biome);
} else{
$stmt = $this->sqlSavePlotById;
$stmt->bind_param('isiisssss', $plot->id, $plot->levelName, $plot->X, $plot->Z, $plot->name, $plot->owner, $helpers, $denied, $plot->biome);
}
$result = $stmt->execute();
var_dump($stmt);
var_dump($result);
var_dump($plot);
$this->lastSave = time();
if ($result === false){
$this->plugin->getLogger()->error($stmt->error);
return false;
}
$this->cachePlot($plot);
return true;
}
A plot's id can either be -1 if "empty", or have an ID which is fetched from the savePlot function
I know that the messed up part is around the first "Values":
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 '?, X = ?, Z = ?, name = ?, owner = ?, helpers = ?, denied = ?,
biome = ?)
' at line 2
Could someone explain me what i could put instead?
EDIT: as requested, SHOW CREATE TABLE
CREATE TABLE `plots` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`level` text COLLATE utf8_unicode_ci,
`X` int(11) DEFAULT NULL,
`Z` int(11) DEFAULT NULL,
`name` text COLLATE utf8_unicode_ci,
`owner` text COLLATE utf8_unicode_ci,
`helpers` text COLLATE utf8_unicode_ci,
`denied` text COLLATE utf8_unicode_ci,
`biome` text COLLATE utf8_unicode_ci,
PRIMARY KEY (`id`),
KEY `XZ` (`X`,`Z`)
) ENGINE=InnoDB AUTO_INCREMENT=3609 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
I think you want something more like this:
INSERT INTO plots (`id`, `level`, `X`, `Z`, `name`, `owner`, `helpers`, `denied`, `biome`)
SELECT id, p.level, p.X, p.Z, ?, ?, ?, ?
FROM plots p
WHERE p.level = ? AND X = ? AND Z = ?
ON DUPLICATE KEY
UPDATE name = VALUES(name),
owner = VALUES(owner),
helpers = VALUES(helpers),
denied = VALUES(denied),
biome = VALUES(biome);
You need to be careful about the order of the arguments. I am guessing that id is the primary key and (X, Z, level) is declared as unique (how you identify duplicates). You only specify that you want to change name in the event of a collision, but this sets all the values (as in your version).
Fixed up my Query with the answer provided by #Gordon Linoff
Turns out i even had a logical issue.. i mixed up the "saveByID" and "saveByXZ"..
public function savePlot(Plot $plot): bool{
$this->db->ping();
$helpers = implode(',', $plot->helpers);
$denied = implode(',', $plot->denied);
if ($plot->id >= 0){
$stmt = $this->sqlSavePlotById;
$stmt->bind_param('isiisssss', $plot->id, $plot->levelName, $plot->X, $plot->Z, $plot->name, $plot->owner, $helpers, $denied, $plot->biome);
} else{
$stmt = $this->sqlSavePlot;
$stmt->bind_param('siisiisssss', $plot->levelName, $plot->X, $plot->Z, $plot->levelName, $plot->X, $plot->Z, $plot->name, $plot->owner, $helpers, $denied, $plot->biome);
}
$result = $stmt->execute();
$this->lastSave = time();
if ($result === false){
$this->plugin->getLogger()->error($stmt->error);
return false;
}
$this->cachePlot($plot);
return true;
}
The fixed up query:
$this->sqlSavePlot = $this->db->prepare(
"INSERT INTO plots (`id`, `level`, `X`, `Z`, `name`, `owner`, `helpers`, `denied`, `biome`)
VALUES((SELECT id
FROM plots p
WHERE p.level = ? AND X = ? AND Z = ?),?,?,?,?,?,?,?,?)
ON DUPLICATE KEY
UPDATE name = VALUES(name),
owner = VALUES(owner),
helpers = VALUES(helpers),
denied = VALUES(denied),
biome = VALUES(biome);"
);
$this->sqlSavePlotById = $this->db->prepare(
"UPDATE plots SET id = ?, level = ?, X = ?, Z = ?, name = ?, owner = ?, helpers = ?, denied = ?, biome = ? WHERE id = VALUES(id);"
);
Thanks alot to everyone! Hope this helps others in the future!

Define UNIQUE key constraint for the table

I have implemented this code to insert and update the data in my database but when I try it a new row's data is always being inserted in the table and it is not being updated How can I define the unique key in my case to get it to work? I have the primary key id.
<?php
$json = '{"latitude":53.86898451,"longitude":10.66561387,"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."(latitude, longitude, created_at)
VALUES( ? , ? , 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 craeted";
}
UPDATE
This is what I'm trying now
$sql = "INSERT INTO ".$route."(id, latitude, longitude, created_at)
VALUES( id, ? , ? , NOW() )
ON DUPLICATE KEY
UPDATE latitude = VALUES(latitude)
, longitude = VALUES(longitude)";
Which variable should I add in the VALUES braces for id?
You are not specifying a value for id in your INSERT INTO statement, so there will never be a duplicate key.
Instead, it is auto-generating the next available ID.
To solve this, specify the value of the pre-existing ID (if any).

php- data not entered to database

I am trying to enter 3 different data to a mysql database 'pages'
The first 2 data is submitted to the database but the third 'dname' is not.
The $_SESSION['dname'] contains the value to be added to the column 'dname'
The php looks like:
if (isset($_POST['submit']))
{
$menulabel = $_POST['menulabel'];
$content = $_POST['content'];
$dname = $_SESSION['dname'];
$query = "INSERT INTO pages (menulabel, content, dname) VALUES (?, ?, ?)";
$statement = $databaseConnection->prepare($query);
$statement->bind_param('sss', $menulabel, $content, $dname);
$statement->execute();
$statement->store_result();
if ($statement->error)
{
die('Database query failed: ' . $statement->error);
}
$creationWasSuccessful = $statement->affected_rows == 1 ? true : false;
if ($creationWasSuccessful)
{
header ("Location: index.php");
}
else
{
echo 'Failed';
}
}
The mysql table:
$query_pages = "CREATE TABLE IF NOT EXISTS pages (id INT NOT NULL AUTO_INCREMENT, menulabel VARCHAR(50), content TEXT, dname VARCHAR(50), PRIMARY KEY (id))";
$databaseConnection->query($query_pages);
The php successfully adds the 'menulabel' and 'content' to the table and continues leaving the 'dname' NULL.
Please help, this is my first time with php.
Here you go buddy. This should fix your issue. Instead of throwing the object into the params, utilize it in the query instead.
$menulabel = $_POST['menulabel'];
$content = $_POST['content'];
$dname = $_SESSION['dname'];
$query = "INSERT INTO pages (menulabel, content, dname) VALUES (?, ?, '$dname')";
$statement = $databaseConnection->prepare($query);
$statement->bind_param('ss', $menulabel, $content);
$statement->execute();
$statement->store_result();

Categories