How to avoid Query doubles INSERT into database? - php

Problem:
I have made a simple form that uses PHP to pass information to my database via a INSERT query. However, every time I run it, it tries to put the information in twice. How can I avoid this?
Explanation:
I first insert the answers, into my answers table, save the AnswerID as a variable. Then do the save with my question table and lastly I use the two saved variables containing the ID's into my question_answers table.
My code:
if (isset($_POST['textinput1']) && !empty($_POST['textinput1'])) {
$text1 = mysqli_real_escape_string($conn, $_POST['textinput1']);
$text2 = mysqli_real_escape_string($conn, $_POST['textinput2']);
$q_text = mysqli_real_escape_string($conn, $_POST['textarea']);
$stmt = $conn->prepare("INSERT INTO answers (Answer1Text, Answer2Text) VALUES (?, ?)");
$stmt->bind_param('ss', $text1, $text2);
$stmt->execute();
$answerid = $stmt->insert_id;
$stmt = $conn->prepare("INSERT INTO question (QuestionText) VALUES (?)");
$stmt->bind_param('s', $q_text);
$stmt->execute();
$questionid = $stmt->insert_id;
if ($stmt->execute()) {
$stmt = $conn->prepare("INSERT INTO question_answers (AnswerID, QuestionID) VALUES (?, ?)");
$stmt->bind_param('ss', $answerid, $questionid);
$stmt->execute();
echo "<h2>Dit spørgsmål er nu lagt op på siden!</h2>";
echo "<h3>Tusinde tak for din interesse for SMIL - Skodfri Århus.</h3>";
}
else
{
echo "ERROR: Could not able to execute . " . mysqli_error($conn);
}
}
// close connection
mysqli_close($conn);
?>
My tables of importance:
question: QuestionID(PK), QuestionText
answers: AnswerID(PK), Answer1Text, Answer2Text
question_answers: QuestionAnswerID(PK), QuestionID(FK), AnswerID(FK)
Ps. I prefer not to use composite unique constraint as a solution.
Also a side-question, should $stmt->insert_id variables be mysqli_real_escape_string?

Your problem is that you have executed the second query TWICE
if (isset($_POST['textinput1']) && !empty($_POST['textinput1'])) {
$text1 = mysqli_real_escape_string($conn, $_POST['textinput1']);
$text2 = mysqli_real_escape_string($conn, $_POST['textinput2']);
$q_text = mysqli_real_escape_string($conn, $_POST['textarea']);
$stmt = $conn->prepare("INSERT INTO answers (Answer1Text, Answer2Text) VALUES (?, ?)");
$stmt->bind_param('ss', $text1, $text2);
$stmt->execute();
$answerid = $stmt->insert_id;
$stmt = $conn->prepare("INSERT INTO question (QuestionText) VALUES (?)");
$stmt->bind_param('s', $q_text);
$stmt->execute();
$questionid = $stmt->insert_id;
// THIS IS THE SECOND EXECUTION OF QUERY 2
if ($stmt->execute()) {
$stmt = $conn->prepare("INSERT INTO question_answers (AnswerID, QuestionID) VALUES (?, ?)");
$stmt->bind_param('ss', $answerid, $questionid);
$stmt->execute();
echo "<h2>Dit spørgsmål er nu lagt op på siden!</h2>";
echo "<h3>Tusinde tak for din interesse for SMIL - Skodfri Århus.</h3>";
}
else
{
echo "ERROR: Could not able to execute . " . mysqli_error($conn);
}
}
// close connection
mysqli_close($conn);
?>
Instead try this as the IF test
//if ($stmt->execute()) {
if ( isset($answerid,$questionid) ) {

if ($stmt->execute()) {
this runs one of your statements a second time. You should assign the return value to a variable if you need it for something later.

Related

Inserting data from forms to access by ODBC

I have try to use ODBC to insert data. However, it does not work
This is my code. How can I solve the problem?
<?php
if(isset($_POST['submit']))
{ $ContactPersonID=$_POST['ContactPersonID']
$FirstName=$_POST['First name'];
$LastName=$_POST['Last name'];
$PhoneNumber=$_POST['PhoneNumber'];
$RestaurantID=$_POST['RestaurantID'];
echo $ContactPersonID ." ".$FirstName." ".$LastName." ".$PhoneNumber." ".$PhoneNumber." ".$RestaurantID ;
$con=odbc_connect("Online Food Delivery Database","", "");
$sql="INSERT INTO RestaurantPeopleContact
(ContactPersonID,FirstName,LastName,PhoneNumber,RestaurantID)
VALUES ('$ContactPersonID','$FirstName','$LastName','$FirstName','$PhoneNumber','$RestaurantID')";
if(odbc_exec($con,$sql))
{
echo "Data saved.";
}
else
{
echo "Error";
}
}
?>
You are inserting twice the firstname.
By this reason, the columns declaration doesnt match with the number of variables
Consider using PHP's PDO for the MS Access connection, a better handler to pass parameters and raise needed exceptions and of course to avoid SQL injection especially from web input. You may need to initialize PDO in your .ini file.
Also, ContactPersonID and RestaurantID might be integer values but you look to be quoting them. Parameters help in defining needed data types without worrying about quote enclosures or messy string concatenation.
$ContactPersonID = $_POST['ContactPersonID']
$FirstName = $_POST['First name'];
$LastName = $_POST['Last name'];
$PhoneNumber = $_POST['PhoneNumber'];
$RestaurantID = $_POST['RestaurantID'];
$database = "C:\Path\To\Database\Online Food Delivery Database.accdb";
# PREPARED STATEMENT WITH PLACEHOLDERS
$sql = "INSERT INTO RestaurantPeopleContact
(ContactPersonID, FirstName, LastName, PhoneNumber, RestaurantID)
VALUES (?, ?, ?, ?, ?)";
try {
$dbh = new PDO("odbc:DSN=MS Access Database;DBq=$database;");
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sth = $dbh->prepare($sql);
# BIND PARAMETERS
$sth->bindParam(1, $ContactPersonID, PDO::PARAM_INT);
$sth->bindParam(2, $FirstName, PDO::PARAM_STR);
$sth->bindParam(3, $LastName, PDO::PARAM_STR);
$sth->bindParam(4, $PhoneNumber, PDO::PARAM_STR);
$sth->bindParam(5, $RestaurantID, PDO::PARAM_INT);
$sth->execute();
}
catch(PDOException $e) {
echo $e->getMessage()."\n";
}
# close the connection
$dbh = null;

mysql prepared statments insert issue

I am having a weird problem with a insert statment. What's happening is that if I insert into only one column, it works but anything greater than 1 column doesn't get inserted and there are no errors displayed
This works
$db = mysqli new('localhost','root','','db');
$stmt = $db->prepare("insert into test (id) values(?)");
echo $db->error;
$stmt->bind_param("s",$id);
$stmt->execute();
But not this:
$id = 1;
$name = "test";
$stmt = $db->prepare("insert into test (id,name) values(?,?)");
echo $db->error;
$stmt->bind_param("ss",$id, $name);
$stmt->execute();
Does anyone have a clue? Not sure if this is helpful but some of the columns don't have a value under collation tab and others have latin1_swedish_ci in the table
Try to bind parameters separately, Like below:
$stmt = $db->prepare("insert into test (id,name) values(:id, :name)");
echo $db->error;
$stmt->bind_param(":id", $id);
$stmt->bind_param(":name", $name);
$stmt->execute();

Inserting Multiple Values with PDO and a Loop

To give you some background, the flow is: Connect to a 3rd party API, pull data stored as json, convert to php and use the data in the below code.
I found this work originally but unable to figure out how to modify it to my needs. Perhaps one of you could understand it better?
I am doing 3 things here. First checking the ID of a house + last_update stamp to determine which houses need to be updated in my database. If they exist but details have changed, drop the current data and store it in a variable ready to be inserted. If the data does not exist, insert it.
Something to note: The script takes so long to execute that I have to set set_time_limit(0); which I realise is bad practise but I needed to force the script to complete.
I have cut my code down quite a lot given that I had over 40 different manually entered prepared statements for either:
Updating records
Deleting records
Inserting records
I have identified the expected outputs using screenshots so please ignore any open braces at this point as the main issue is refining the code to a more dynamic approach and making it quicker of course.
<?php
$update = '';
$add = '';
if (!empty($houses)) {
foreach($houses as $travel_Prop) {
$Prop = $travel_Prop['data'][0]; // Need to check this!
if ($Prop['id'] > '0') { // Ignore empty arrays
$sql= "SELECT * FROM travel_a_property WHERE travel_prop_id = :travel_prop_id";
$stmt = $extDb->prepare("$sql");
$stmt->bindParam(':travel_prop_id', $Prop['id'], PDO::PARAM_INT);
$stmt->execute();
$Result = $stmt->fetchAll(PDO::FETCH_ASSOC);
if (!empty($Result)) {
$travel_last_update = $Prop['last_update'];
$local_last_update = $Result[0]['last_update'];
if ($travel_last_update > $local_last_update) {
$update[] = $Prop;
echo 'Property ID: ' .$Prop['id'] .' Property modified: Updating Records.<br>';
} else {
echo 'Property ID: ' .$Prop['id'] .' Property details: Up to Date.<br>';
}
} else {
$add[] = $Prop;
echo 'Property ID: ' .$Prop['id'] .' Property Created: Adding to Records.';
}
}
}
NOTE: Code will carry on after screenshot output
# UPDATE
if (!empty($update)) {
//print_r($update);
foreach ($update as $PropUpdate) {
// Get all_prop_id
$sql= "SELECT * FROM travel_a_property WHERE travel_prop_id = :travel_prop_id";
$stmt = $extDb->prepare("$sql");
$stmt->bindParam(':travel_prop_id', $PropUpdate['id'], PDO::PARAM_INT);
$stmt->execute();
//$Result = $stmt->fetchAll(PDO::FETCH_ASSOC);
$obj = $stmt->fetchObject();
//echo $obj->filmName;
$all_prop_id = $obj->all_prop_id;
echo $all_prop_id;
// Update master db table a_property
$sql = "UPDATE travel_a_property SET last_update = :last_update
HERE all_prop_id = :all_prop_id";
$stmt = $extDb->prepare($sql);
$stmt->bindParam(':last_update', $PropUpdate['last_update'], PDO::PARAM_STR);
$stmt->bindParam(':all_prop_id', $all_prop_id, PDO::PARAM_INT);
$stmt->execute();
echo '<br>Prop Updated - all_prop_id : ' .$all_prop_id .'<br>';
# DELETe & INSERT
$sql = "DELETE FROM ot_b_address WHERE glob_prop_id = :glob_prop_id";
$stmt = $extDb->prepare($sql);
$stmt->bindParam(':glob_prop_id', $glob_prop_id, PDO::PARAM_INT);
$stmt->execute();
$sql = "INSERT INTO ot_b_address(glob_prop_id, address1, address2, city, state, zip_code,
country, latitude, longitude) VALUES ( :glob_prop_id, :address1, :address2, :city, :state,
:zip_code, :country, :latitude, :longitude)";
$stmt = $extDb->prepare($sql);
$stmt->bindParam(':glob_prop_id', $glob_prop_id, PDO::PARAM_INT);
$stmt->bindParam(':address1', $PropUpdate['address']['address1'], PDO::PARAM_STR);
$stmt->bindParam(':address2', $PropUpdate['address']['address2'], PDO::PARAM_STR);
$stmt->bindParam(':city', $PropUpdate['address']['city'], PDO::PARAM_STR);
$stmt->bindParam(':state', $PropUpdate['address']['state'], PDO::PARAM_STR);
$stmt->bindParam(':zip_code', $PropUpdate['address']['zip_code'], PDO::PARAM_STR);
$stmt->bindParam(':country', $PropUpdate['address']['country'], PDO::PARAM_STR);
$stmt->bindParam(':city', $PropUpdate['address']['city'], PDO::PARAM_STR);
// use PARAM_STR although a number
$stmt->bindParam(':latitude', $PropUpdate['address']['latitude'], PDO::PARAM_STR);
$stmt->bindParam(':longitude', $PropUpdate['address']['longitude'], PDO::PARAM_STR);
$stmt->execute();
echo 'Address Updated <br>';
$sql = "DELETE FROM travel_d_urls WHERE all_prop_id = :all_prop_id";
$stmt = $extDb->prepare($sql);
$stmt->bindParam(':all_prop_id', $all_prop_id, PDO::PARAM_INT);
$stmt->execute();
if (!empty($PropUpdate['urls'])) {
foreach($PropUpdate['urls'] as $row => $Url) {
$sql = "INSERT INTO travel_d_urls(all_prop_id, type, url)
VALUES ( :all_prop_id, :type, :url)";
$stmt = $extDb->prepare($sql);
$stmt->bindParam(':all_prop_id', $all_prop_id, PDO::PARAM_INT);
$stmt->bindParam(':type', $Url['type'], PDO::PARAM_STR);
$stmt->bindParam(':url', $Url['url'], PDO::PARAM_STR);
$stmt->execute();
echo 'URL '.$row .' Updated <br>';
}
}
}
} else {
echo 'no rates to Update <br>';
}
The output is pretty much just the same thing (whatever is being updated)
URL ADDED
URL ADDED
etc
The following code is the last if statement which tells the script to add the remaining properties if they do not exist.
} // end foreach $update
# INSERT ONLY
if (!empty($add)) {
foreach ($add as $PropAdd) {
$sql = "INSERT INTO travel_a_property(travel_prop_id, last_update)
VALUES ( :travel_prop_id, :last_update)";
$stmt = $extDb->prepare($sql);
$stmt->bindParam(':travel_prop_id', $PropAdd['id'], PDO::PARAM_INT);
$stmt->bindParam(':last_update', $PropAdd['last_update'], PDO::PARAM_STR);
$stmt->execute();
$all_prop_id = $extDb->lastInsertId(); // Use this ID in all the following record inserts
echo '<br>Prop Added - all_prop_id : ' .$all_prop_id .'<br>';
##########################
$sql = "INSERT INTO travel_b_address(all_prop_id, address1, address2, city, state, zip_code, country,
latitude, longitude) VALUES ( :all_prop_id, :address1, :address2, :city, :state, :zip_code, :country,
:latitude, :longitude)";
$stmt = $extDb->prepare($sql);
$stmt->bindParam(':all_prop_id', $all_prop_id, PDO::PARAM_INT);
$stmt->bindParam(':address1', $PropAdd['address']['address1'], PDO::PARAM_STR);
$stmt->bindParam(':address2', $PropAdd['address']['address2'], PDO::PARAM_STR);
$stmt->bindParam(':city', $PropAdd['address']['city'], PDO::PARAM_STR);
$stmt->bindParam(':state', $PropAdd['address']['state'], PDO::PARAM_STR);
$stmt->bindParam(':zip_code', $PropAdd['address']['zip_code'], PDO::PARAM_STR);
$stmt->bindParam(':country', $PropAdd['address']['country'], PDO::PARAM_STR);
// use PARAM_STR although a number
$stmt->bindParam(':latitude', $PropAdd['address']['latitude'], PDO::PARAM_STR);
$stmt->bindParam(':longitude', $PropAdd['address']['longitude'], PDO::PARAM_STR);
$stmt->execute();
echo 'Address Added <br>';
} // end foreach
} // end !empty
$extDb = null;
}
?>
So to reiterate, the question here is not to identify what is wrong with my code as other than the speed, it is actually working fine. I would like to know if someone could identify the best way to make this dynamic to avoid having to tediously write the code 40 + times?
If anything is unclear, please let me know.
Cheers,
bench.
You are creating the prepared statements inside the foreach loop. Try to create the prepared statement outside of it. The idea of a prepared statement is that you prepare the statement once and execute it multiple times with different parameter values. This way the database only have to compile and optimize the SQL query once, which is more efficient than doing it foreach iteration.
if (!empty($houses)) {
$stmt = $extDb->prepare("SELECT * FROM travel_a_property WHERE travel_prop_id = :travel_prop_id");
//$stmt2 = ...
foreach ($houses as $travel_Prop) {
$prop = $travel_Prop['data'][0]; // Need to check this!
if ($prop['id'] > '0') { // Ignore empty arrays
if ($stmt->execute(array(':travel_prop_id' => $prop['id']))) {
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
//Do something with $result
}
}
//$stmt2->execute(...);
}
}

How will I get mysqli last insert id

How will i get the last insert id in mysql following code?
All variable are set.
Insertion works!
$Restconnection = mysqli_connect("host","user","passwd","db ");
$query3 = mysqli_query($Rconnection, $strSQL3);
$stmt = $conn->prepare("INSERT INTO table (name, email, password) VALUES(?,?,?)");
$stmt->bind_param("sss", $name, $email, $password);
$stmt->execute();
$last_id = $conn->insert_id;
echo "Last inserted ID is: " . $last_id;
print mysqli_insert_id($Restconnection);
http://php.net/manual/de/mysqli.insert-id.php
Use mysqli_insert_id($connection)
Use the following:
$last_insert_id = mysqli_insert_id($Restconnection);

Inserting Multiple values into MySQL database using PHP

I'm wondering how to insert multiple values into a database.
Below is my idea, however nothing is being added to the database.
I return the variables above (email, serial, title) successfully. And i also connect to the database successfully.
The values just don't add to the database.
I get the values from an iOS device and send _POST them.
$email = $_POST['email'];
$serial = $_POST['serial'];
$title = $_POST['title'];
After i get the values by using the above code. I use echo to ensure they have values.
Now I try to add them to the database:
//Query Check
$assessorEmail = mysqli_query($connection, "SELECT ace_id,email_address FROM assessorID WHERE email_address = '$email'");
if (mysqli_num_rows($assessorEmail) == 0) {
echo " Its go time add it to the databse.";
//It is unqiue so add it to the database
mysqli_query($connection,"INSERT INTO assessorID (email_address, serial_code, title)
VALUES ('$email','$serial','$title')");
} else {
die(UnregisteredAssessor . ". Already Exists");
}
Any ideas ?
Since you're using mysqli, I'd instead do a prepared statement
if($stmt = mysqli_prepare($connection, "INSERT INTO assessorID (email_adress, serial_code, title) VALUES (?, ?, ?)"))
{
mysqli_stmt_bind_param($stmt, "sss", $email, $serial, $title);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
}
This is of course using procedural style as you did above. This will ensure it's a safe entry you're making as well.

Categories