Some queries in PDO php executing and some are not - php

I am trying to enter a whole table in itself changing the city variable but when I create a temp table to store data the insert statement to insert data back in original statement not working. Here is the code
<?php
if(isset($_POST['btnsub'])){
$city=$_POST['city'];
$query= $conn->query("create table from_php like menuinstant;
insert into from_php select * from menuinstant where city='Kota';
update from_php set id = replace(id,'Kota','.$city.');
update from_php set city = replace(city,'Kota','.$city.');
insert into menuinstant select * from from_php;
drop table from_php
");
echo "table created";
}
?>
The insert into menuinstant is not executing even the drop query after that is also working. Help me out.

almost all database/sql wrappers will only allow exactly ONE query per call. so your $conn->query([5queries]) should be five $conn->query([1stquery]); $conn->query([2ndquery]); ...
update1:
You should/could also check for errors:
$result = $conn->query('[Your query here]');
if($result === false) {
die(print_r($conn->errorInfo(),true));
}
update2: please read up on mysql injections. for example http://php.net/manual/en/security.database.sql-injection.php

Related

using php to insert records in my database

I am trying to insert data into my database from a user form using php
I normally do not have any issues when doing this except this time and I believe it is because of the date type as explained below
Here is the code:
<?php
session_start();
$user = $_SESSION['who'];
if (!$_SESSION['who']){
header("location: login.php");
}
if (isset($_POST['submit'])){
require_once('dbconn.php');
$flightID = $_POST["flights"];
$sql= "INSERT INTO booking (flight_id,customer_id,checkedin,checkin_datetime, booking_datetime,baggage)
VALUES ('1', '1','0','10-10-10', '10-10-10','30')";
if($recordSet = $dbConn->query($sql)) {
echo "record set";
}
else
echo "not set";
}
?>
I will be using variables instead of hard coded values for my insert statement however I am just trying to get it to work.
Here are the attributes in my database table for booking
id, flight_id, customer_id, checkedin, checkin_datetime, booking_datetime, baggage
The ID is automatic which is why it is not in my sql statement
currently my page is displaying not set I think it may be due to the date field as I am not sure which format it may use.
UPDATE: I changed the date in my sql statement and it still is not working, no errors coming up as well.
You can Use
$sql= "INSERT into booking (flight_id,customer_id,checkedin,checkin_datetime, booking_datetime,baggage)
VALUES ('1', '1','0','2020-10-10', '2020-10-10','30')";
$sql= "INSERT INTO booking (flight_id,customer_id,checkedin,checkin_datetime, booking_datetime,baggage)
VALUES ('1', '1','0','2010-10-20', '2010-10-20','30')";
Note :
date format: YYYY-MM-DD
All id must be exists in the database (if you use Foreign Key for flight_id and customer_id).
Date format looks ok in the sql statement.
make sure ID field is auto increment in the database as you have not used in the sql statement.

Copy Row Get Last Insert ID

I am copying a row in one of the tables in my database and trying to get the last inserted ID. Copying the row works fine, and the AI field updates properly, but it is not returning the last insert ID (although it does return true - or if I echo something else out in its place that works fine as well).
Some of the other queries also use last insert ID and those work well.
I suspect it is something to do with the temporary table, but cannot find anything on SO about a similar problem with last insert ID and temporary tables. Does anyone know what is causing the problem or if there is a workaround?
public function duplicateItinRow($itineraryID){
$this->db->query("CREATE TEMPORARY TABLE temporary_itin_table AS SELECT * FROM itinerary_ref WHERE Itinerary_ID = $itineraryID;
UPDATE temporary_itin_table SET Itinerary_ID=NULL;
INSERT INTO itinerary_ref SELECT * FROM temporary_itin_table;
DROP TEMPORARY TABLE temporary_itin_table");
//Execute
if($this->db->execute()){
return $this->db->lastInsertId();
} else {
return false;
}
}
UPDATE:
Not the ideal solution I'm sure, but have got it working using the copy method detailed here: How to copy a row and insert in same table with a autoincrement field in MySQL?
I think lastInsertedId will be updated by your last "DROP TEMPORARY TABLE" statement.
Try to split the query into two separate queries instead:
<?php
public function duplicateItinRow($itineraryID) {
$this->db->query("CREATE TEMPORARY TABLE temporary_itin_table AS SELECT * FROM itinerary_ref WHERE Itinerary_ID = $itineraryID;
UPDATE temporary_itin_table SET Itinerary_ID=NULL;
INSERT INTO itinerary_ref SELECT * FROM temporary_itin_table;");
if(!$this->db->execute()) {
return false;
}
$lastId = $this->db->lastInsertId();
$this->db->query("DROP TEMPORARY TABLE temporary_itin_table");
if(!$this->db->execute()) {
return false;
}
return $lastId;
}
Also note that you have a SQL injection vulnerability when you add $itineraryID directly to the SQL query without using prepared statements. If the $itineraryID is populated from user input people can hack your website.

Insert id from from one table and insert it into another one. Mysql + PHP [duplicate]

This question already has answers here:
How to get the last field in a Mysql database with PHP?
(5 answers)
Closed 9 years ago.
I am working on a register user form and I have two tables in mysql. What I want to do is when a new user has registered, take the id (which primary key) of that user and insert it into another table. What is the best way to do that?
Thanks in advance.
You need to use mysql_insert_id for this purpose. Here is an example:
<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('mydb');
mysql_query("INSERT INTO mytable (product) values ('kossu')");
printf("Last inserted record has id %d\n", mysql_insert_id());
?>
First insert the user details into users table and get inserted user id using mysql_insert_id. and use that user id to insert into another table.
AS ON GETTING IT ON PHP
GET LAST INSERT ID HERE
BUT IF YOU INTEND TO GET IT USING MYSQL QUERY
use stored procedure to store last insert id to a variable then generete your second query
INSERT INTO T1 (col1,col2) VALUES (val1,val2);
SET #last_id_in_T1 = LAST_INSERT_ID();
INSERT INTO T2 (col1,col2) VALUES (#last_id_in_T1,val2);
or direct insert after your first insert
INSERT INTO T1 (col1,col2) VALUES (val1,val2);
INSERT INTO T2 (col1,col2) VALUES (LAST_INSERT_ID(),val2);
Use any of transaction query for writing:
Following is in CI pattern:
$this->db->trans_start();
$this->db->query('AN SQL QUERY...');
$this->db->query('AN SQL QUERY...');
if(!$this->db->trans_complete()){
$this->db->trans_rollback();
}
$query1= "INSERT INTO employee ( username, email,...)
VALUES ('".$_POST["username"]."', ...)";
if($result1 = mysql_query($query1))
{
$emp_id = mysql_insert_id(); // last created id by above query
$query2= "INSERT INTO dept ( emp_id, dept_name, ...)
VALUES ('".$emp_id."', '".$_POST["dept_name"]."',...)";
if($result2 = mysql_query($query2))
{
//success msg
}
}
Another neat way to do it at do it at Database level itself is to used Stored Procedure
Look at this solution to see an example of how to do it. You will have to check how Stored procedures work in your specific database to get the specific syntax. This makes it error free even if someone refactors or moves around the code and more efficient.
Using trigger the Mysql on database-level. For example, I have two tables:
user(id int primary key, nombre varchar(50));
replication(id_r int primary key, nombre_r varchar(50));
Using the trigger:
create trigger user_r after insert on user
for each row
insert into replication(id_r, nombre_r)
select u.id, u.nombre
from user u
where u.id=NEW.id and u.nombre=NEW.nombre;

If inputs exist, dont insert, else insert PHP mysql

I've just started with php, and i wondered if anyone can help.
i have this
$sql="INSERT INTO $tbl_name SET date='$mydate' , event='$myevent'";
$result=mysql_query($sql);
I need to know how to make it see if the event exists, and if it does i need it to do nothing, if it doesn't then insert it!
split it into 2 queries:
1) check if event exists. If yes then do nothing, else insert a new event
2) continue with your query. this way the event will allays exist when inserting your data
This is something that can be done through MySQL alone.
Setup a unique key for the event column by running the following MySQL Command on your table:
CREATE UNIQUE INDEX `i_event` ON `TABLE_NAME_GOES_HERE` (`event`);
For more information: http://dev.mysql.com/doc/refman/5.0/en/create-index.html
Do this for every possible table you expect to see in the $tbl_name variable.
Then, change your PHP Query:
$sql="INSERT IGNORE INTO $tbl_name SET date='$mydate' , event='$myevent'";
$result=mysql_query($sql);
For more information on INSERT IGNORE: http://dev.mysql.com/doc/refman/5.5/en/insert.html
INSERT IGNORE simply does as it states... it will try to insert the row unless it fails validation (in this case from an index that you declared HAS to be unique).
Try:
$query = mysql_query("SELECT $myevent from $tbl_name ")
$rows = mysql_num_rows($query)
if ($num_rows > 0) {
// do nothing
}
else {
$sql = "INSERT INTO $tbl_name SET date='$mydate' , event='$myevent'";
$result = mysql_query($sql);
}
As a sidenote: mysql_ functions are deprecated and it's recommended to switch to mysqli or PDO.

Search mysql database before inserting data

I cant quite think about how to do this with mysql and php. Basically I want to be able to submit data into a mysql database but before it is inserted, it will check to see if that entry already exists.
$guid=$_POST['guid'];
$name=$_POST['name'];
//Username
$user="webhost";
//Password
$pass="*******";
//IP To Host
$ip="***********";
//Database
$db="dayz2";
//Table
$table="whitelist";
//Database Connection
$con=#mysql_connect("$ip", "$user", "$pass")
or die(mysql_error());
//Select Database
$dbcon=#mysql_select_db($db, $con)
or die(mysql_error());
$dupesql = "SELECT * FROM $table where (name = '$name' AND guid = '$guid')";
$duperaw = mysql_query($dupesql);
if (mysql_num_rows($duberaw) > 0) {
echo "Entry Already Exists";
}
else {
//Query Data Into Whitelist Table
$sql="INSERT INTO $table (name, guid) VALUES ('$name', '$guid')";
//Submit Data into Whitelist Table
$result=#mysql_query($sql, $con) or die(mysql_error());
}
?>
You can do it in another way, instead of:
submit data into a mysql database but before it is inserted, it will
check to see if that entry already exists.
You can do:
INSERT data into a mysql database if not existed, else ignore them
Something like :
INSERT IGNORE INTO table
INSERT IGNORE INTO yourtablename
SET fieldname = 'blah'
,..
It depends what you are trying to do - what is the exact criteria for your query?
You have several options:
use INSERT IGNORE ... if you only want to insert new rows that don't have a duplicate primary key. See http://dev.mysql.com/doc/refman/5.5/en/insert.html.
use INSERT ... ON DUPLICATE KEY UPDATE to insert new rows and update rows where there is a primary key match.
See http://dev.mysql.com/doc/refman/5.5/en/insert-on-duplicate.html.
use a normal SQL SELECT ... to pull the results first before performing business logic on the results before deciding which to INSERT ... or UPDATE ... depending on your requirements.
It depends how you want to handle case when the entry exists.
I you want to throw some error then you can create table trigger for insert event and put some checks there, but it will be slow because every insert will do this check.

Categories