PHP to mySQL - duplicating entry when finding insert ID - php

I'm having an issue with my PHP form submission to MySQL - it's a multi_query insert that is supposed to feed two tables. Everything was working fine, but I recently set up a foreign key relationship and something in the process of getting the mysqli_insert_id for the entry to the parent table causes the first entry to be entered twice in that table - to use the table names from my code below, the master table entry is being inserted twice, and the local table entry is inserted once with the $master_id of the first master entry. I really only have a functional understanding of PHP - can someone explain why this is happening and how I can fix it so that the entry is inserted only once into each table?
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$date = $_POST['date'];
$time = $_POST['time'];
$latitude = $_POST['latitude'];
$longitude = $_POST['longitude'];
$accuracy = $_POST['accuracy'];
$species = $_POST['species'];
$sql = "INSERT INTO master (date, time, latitude, longitude, accuracy, species, source)
VALUES ('$date', '$time', '$latitude', '$longitude', '$accuracy', '$species', 'source A');";
mysqli_query($conn, $sql);
$master_id = mysqli_insert_id($conn);
$sql .= "INSERT INTO local (Master_ID, date, time, latitude, longitude, accuracy, species)
VALUES ('$master_id', '$date', '$time', '$latitude', '$longitude', '$accuracy', '$species');";
if ($conn->multi_query($sql) === TRUE) {
$conn->close();
header("Location:http://d-bird.org/thank%20you.html");
}
else {
echo "Error: " . $sql . "<br>" . $conn->error;
}

$sql .= "INSERT INTO local (Master_ID, date, time, latitude, longitude, accuracy, species)
VALUES ('$master_id', '$date', '$time', '$latitude', '$longitude', '$accuracy', '$species');";
should be
$sql = "INSERT INTO local (Master_ID, date, time, latitude, longitude, accuracy, species)
VALUES ('$master_id', '$date', '$time', '$latitude', '$longitude', '$accuracy', '$species');";
without the dot concatenation for $sql

You are adding the second insert to the first.
changing
$sql .= "INSERT INTO local (Master_ID, date, time, ...
to
$sql = "INSERT INTO local (Master_ID, date, time, ...
should fix your issue.

Related

Inserting data into multiple different data tables

I was trying to insert data into multiple data tables. It's only working for single data tables, I'm just wondering how I would be able to insert data into two data tables. I've been struggling with this issue for the past few hours and can't seem to get to the bottom of it. If anyone has any advice please let me know. :)
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost","ivodatat","","");
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Inputs for security
$fname = mysqli_real_escape_string($link, $_REQUEST['fname']);
$sname = mysqli_real_escape_string($link, $_REQUEST['sname']);
$address = mysqli_real_escape_string($link, $_REQUEST['address']);
$email = mysqli_real_escape_string($link, $_REQUEST['email']);
$phone = mysqli_real_escape_string($link, $_REQUEST['phone']);
$mac = mysqli_real_escape_string($link, $_REQUEST['mac']);
$installer = mysqli_real_escape_string($link, $_REQUEST['installer']);
$status = mysqli_real_escape_string($link, $_REQUEST['status']);
// Insert Query
$sql1 = "INSERT INTO leadlist (fname, sname, address, email, phone, mac, installer, status) VALUES ('$fname', '$sname', '$address', '$email', '$phone', '$mac', '$installer', '$status')";
$sql2 = "INSERT INTO $installer (fname, sname, address, email, phone, mac, installer, status) VALUES ('$fname', '$sname', '$address', '$email', '$phone', '$mac', '$installer', '$status')";
if (mysqli_multi_query($link, $sql1, $sql2)){
mysqli_close($conn);
header("Location: installercontrol.php");
exit;
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Close The Connection
mysqli_close($link);
?>
To use mysqli_multi_query you need to append the queries to each other as it only takes one query argument. From the manual:
Executes one or multiple queries which are concatenated by a semicolon.
Try this instead:
mysqli_multi_query($link, $sql1 . ';' . $sql2)
You should probably also update your error message:
echo "ERROR: Could not able to execute $sql1;$sql2. " . mysqli_error($link);

How can I write information to two database tables from one "if "statement?

I wish to post the users entered information into two different tables in the same data base. However my code does not seem to work, it only writes into the second table that I have asked it to write to. Why wont it write to the first table as well?
if ($_POST['entereddetail']) {
$sql = "INSERT INTO firsttable (thedetail, date)
VALUES ('". $_POST['entereddetail'] ."', NOW())";
$sql = "INSERT INTO secondtable (thedetail, code, branch, user, date)
VALUES ('". $_POST['entereddetail'] ."','". $_POST['codedetail'] ."', '', '', NOW())";
if(mysqli_query($conn, $sql)){
echo "Records inserted successfully.";
} else{
echo "ERROR: Could not execute $sql. " . mysqli_error($link);
}
}
I know my code could be subject to SQL injection. I am only learning the basics at the moment and then I deal with security after as I am only new to SQL and databases. My branch and users field are also left blank as I will be dealing with them later.
That's because you're overwriting your $sql variable.
Adapt your code like this:
$sql = "INSERT INTO firsttable (thedetail, date)
VALUES ('". $_POST['entereddetail'] ."', NOW());";
$sql .= "INSERT INTO secondtable (thedetail, code, branch, user, date)
VALUES ('". $_POST['entereddetail'] ."','". $_POST['codedetail'] ."', '', '', NOW());";
Notice: If you look closely, you'll see a ; at the of the sql-statements. The .= will combine the two $sql variables into one string of two MySQL-statements.
Your only executing the second query...
if ($_POST['entereddetail']) {
$sql = "INSERT INTO firsttable (thedetail, date)
VALUES ('". $_POST['entereddetail'] ."', NOW())";
if ( mysqli_query($conn, $sql) ) {
$sql = "INSERT INTO secondtable (thedetail, code, branch, user, date)
VALUES ('". $_POST['entereddetail'] ."','". $_POST['codedetail'] ."', '', '', NOW())";
if(mysqli_query($conn, $sql)){
echo "Records inserted successfully.";
} else{
echo "ERROR: Could not execute $sql. " . mysqli_error($link);
}
}
else{
echo "ERROR: Could not execute $sql. " . mysqli_error($link);
}

MySQL not able to execute INSERT INTO [table]. Column count doesn't match value count at row 1

I'm trying to pull information from an HTML form and put this into a database using the following code:
$link = mysqli_connect("localhost", "user", "password", "MyDB");
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$sql = "INSERT INTO interest (name, email, dob, address)
VALUES ('$fullname', '$email', '$dob' '$addr')";
if(mysqli_query($link, $sql)){
echo "Records added successfully.";
}else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
mysqli_close($link);
It was working, and I've managed to get 2 test runs in, but now I'm getting the following error at the top of my submission page
ERROR: Could not able to execute INSERT INTO MyDB (name, email, dob,
address) VALUES ('test name', 'test#email.com', '2003-02-01'
'address'). Column count doesn't match value count at row 1
I have another variant of this which sends a PHP email, which is the file I'm using to base this database connection on.
There is also an autoincrement on ID column which is set as the primary key in the database if that makes a difference? SQL isn't my strong point unfortunately!
Given the syntax error you have in your query, being a missing comma in '$dob' '$addr'; you are open to an SQL injection and should be using a prepared statement.
Therefore, I am submitting this complementary answer for your own safety.
Here is an example of a prepared statement using the MySQLi API.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect('localhost', 'xxx', 'xxx', 'my_db');
if (!$link) {
die('Connect Error: ' . mysqli_connect_error());
}
// assuming these are the POST arrays taken from your HTML form if you're using one.
$fullname = $_POST['fullname'];
$email = $_POST['email'];
$dob = $_POST['dob'];
$addr = $_POST['addr'];
$sql = ("INSERT INTO interest (name, email, dob, address) VALUES (?, ?, ?, ?)");
$stmt = $link->prepare($sql) or die("Failed Execution");
$stmt->bind_param('ssss', $fullname, $email, $dob, $addr);
$stmt->execute();
echo $stmt->error;
echo "SUCCESS";
exit();
References:
How can I prevent SQL injection in PHP?
http://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php
http://php.net/pdo.prepared-statements
Foonotes:
If using the following failed because of the AI'd column:
$sql = ("INSERT INTO interest (name, email, dob, address) VALUES (?, ?, ?, ?)");
You may also try: (I used id as the AI'd column as an example)
$sql = ("INSERT INTO interest (id, name, email, dob, address) VALUES ('', ?, ?, ?, ?)");
This could be the case, as I have seen this type of SQL failure behaviour before.
You have missed comma here:
VALUES ('$fullname', '$email', '$dob' '$addr')
Thus (as it was clearly said in error text) column count doesn't mach values count.
It should be
VALUES ('$fullname', '$email', '$dob', '$addr')
You missed a comma
$sql = "INSERT INTO interest (name, email, dob, address)
VALUES ('$fullname', '$email', '$dob', '$addr')";
^here
You missed a comma:
VALUES ('$fullname', '$email', '$dob' '$addr')

PHP process page does not work

Hi guys my process page does not work, my code is
<?php
$id = $_POST['item_id'];
$qty = $_POST['item_qty'];
$name = $_POST['item_name'];
$con = mysqli_connect ("localhost", "name", "password", "db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "INSERT INTO Temp (id, qty, name)
VALUES
('$_POST[id]', '$_POST[qty]', '$_POST[name]')";
if (!mysqli_query($con, $sql))
{
die('Error: ' . mysqli_error());
}
header('Location: http://url.com/');
mysqli_close($con);
?>
Should be all correct, just copy from w3school,
The problem is, the db only get 0,
ie. my $id is 4, $qty is 12, $name is "Hello", after the process page, the table only get two 0s in id and qty, name is void.
The values should be processed to this process page successfully, bc I have tried
echo $id, $qty, $name;
All are the same as I typed in before.
Could anyone help me? thanks :-)
this line:
INSERT INTO Temp (id, qty, name) VALUES ('$_POST[id]', '$_POST[qty]', '$_POST[name]')";
should be:
INSERT INTO Temp (id, qty, name) VALUES ('$id', '$qty', '$name')";
If the form is from your previous question, you dont need:
$id = $_POST['item_id'];
$qty = $_POST['item_qty'];
$name = $_POST['item_name'];
I agree it looks like you left out item_. You might want to sanitize your data first.
$id=mysqli_real_escape_string($_POST['item_id']);
$qty=mysqli_real_escape_string($_POST['item_qty']);
$name=mysqli_real_escape_string($_POST['item_name']);
$sql = "INSERT INTO Temp (id, qty, name)
VALUES ('$id', '$qty', '$name')";

PHP/mySQLi not querying

<?php
$ip = $_SERVER['REMOTE_ADDR'];
$date = date("d/m/y : H:i:s", time());
$dbc = mysqli_connect('localhost', 'root', 'derp', 'derpdb')
or die("Database connection fried.");
$query = "INSERT INTO ipstore (tstamp, ip), " .
"VALUES ('$date', '$ip')";
mysqli_query($dbc, $query);
mysqli_close($dbc);
?>
Can anyone tell me what's wrong with this code? It's meant to store the users IP/date they requested the page in the database. I've tried replacing localhost with 127.0.0.1, no luck. It doesn't bring a message, so it must be connected, however when it comes to querying it just doesn't do it. And it doesn't give a warning. I've checked the DB, nothings there.
Also don't worry, nothing sensitive is there ;)
Thanks
$query = "INSERT INTO ipstore (tstamp, ip), " . "VALUES ('$date', '$ip')";
You are not supposed to use a comma after specifying columns - try
$query = "INSERT INTO ipstore (tstamp, ip) VALUES ('$date', '$ip')";
try it this way
$query = mysql_query("INSERT INTO ipstore (tstamp,ip) VALUES ('$date', '$ip')") or die(mysql_error()); if($query) {echo 'Success'; esle { echo 'Failed'; }
And you will get success for sure

Categories