issues with mysqli_insert_id - php

I'm trying to use mysqli_insert_id in multiple queries, but I keep getting Cannot add or update a child row: a foreign key constraint fails. Below is my code:
$con=mysqli_connect("Stuff");
if(mysqli_connect_errno()){
echo "There was a mistake connecting". mysqli_connect_errno();
}
$First=mysqli_real_escape_string($con,$_POST["FirstName"]);
$Last=mysqli_real_escape_string($con, $_POST["LastName"]);
$Phone=mysqli_real_escape_string($con,$_POST["Number"]);
$Product=mysqli_real_escape_string($con,$_POST["Product"]);
$Quantity=mysqli_real_escape_string($con,$_POST["Quantity"]);
if(!empty($_POST["FirstName"]) && !empty($_POST["LastName"])){
$sql="INSERT INTO Customer(First,Last)
VALUE('$First', '$Last')";
$id = mysqli_insert_id($con);
if(!mysqli_query($con,$sql)) {
die("ERROR". mysqli_error($con));
}
}
if(!empty($_POST["Number"])){
$sql="INSERT INTO Customer_Number(Customer_ID,Number)
VALUE('$id','$Phone')";
if(!mysqli_query($con,$sql)) {
die("ERROR". mysqli_error($con));
}
}
if(!empty($_POST["Product"]) && !empty($_POST["Quantity"])){
$sql="INSERT INTO Product(Customer_ID,Product,Quantity)
VALUE('$id','$Product','$Quantity')";
if(!mysqli_query($con,$sql)) {
die("ERROR". mysqli_error($con));
}else{
echo "Special Order Added";
}
}
mysqli_close($con);
?>
I've also tried using Last_Insert_ID() as well, but that only works for one query, and then gives me the same error message when I try and add it to the 2nd one.

call mysqli_insert_id after the mysqli_query

Related

MySQL affected rows -1 when inserting data into database

I want to create a simple piece of code that will put data into the database form a PHP script, everything works fine except putting the data into the database! (I am running a server with PHP7)
The output of the affected rows shows -1 (strange), I double checked my code, compared it with others, tried searching for a common issue on the internet, even tried on a local server with no avail.
You can see it here:
https://leer.bosvision.nl/register.php
My code:
<?php
$conn = mysqli_connect("localhost", "-user-", "-pass-", "-db-");
if(!$conn) {
$msg = die('connection error');
} else {
$msg = 'Connection success.';
}
echo $msg;
?>
<?php
$query = 'INSERT INTO users_two (ID, username, password) VALUES (1, gfd, gfd)';
if(mysqli_query($conn, $query)) {
$result = 'Data saved';
} else {
$result = 'No data saved';
}
$affected = mysqli_affected_rows($conn);
echo $result . '.' . ' Affected rows: ' . $affected;
?>
To quote the documentation:
-1 indicates that the query returned an error.
And your insert statement indeed errors out, since you don't have a gfd column. If you meant to use that as a value, it should be surrounded by single quotes:
$query = "INSERT INTO users_two (ID, username, password) VALUES (1, 'gfd', 'gfd')";
# Here -------------------------------------------------------------^---^--^---^
<?php
$conn = mysqli_connect("localhost", "-user-", "-pass-", "-db-");
if(!$conn) {
$msg = die('connection error');
} else {
$msg = 'Connection success.';
}
echo $msg;
?>
<?php
$query = "INSERT INTO users_two (username, password) VALUES ('gfd', 'gfd')";
if($result= mysqli_query($conn, $query)) {
$result = 'Data saved';
} else {
$result = 'No data saved';
}
$affected = mysqli_affected_rows($conn);
echo $result . '.' . ' Affected rows: ' . $affected;
?>
One assumes ID is auto increment, so that doesn't need to be in there, or is it not and the issue you are encountering is that its a duplicate entry for key. Also you need to wrap your var data in ' '
I would guess that this is an SQL issue. Can you run your query directly on your database? That would give you the error.
Read this page for more info: PHP insert statement
$sql = "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('John', 'Doe', 'john#example.com')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
Normally you shouldn't be inserting an ID yourself because it should be auto increment.
try adding quotes to the string values, as in:
"INSERT INTO users_two (ID, username, password) VALUES (1, 'gfd', 'gfd')"

INSERT INTO doesnt work php

I'm new to php.I'm trying to build a signup webpage in which if email entered doesn't exist it should insert the values entered.The code works fine and it returns successful when a new mail is entered.But the problem is when I check my database the new values are not inserted.Is there any mistake in my code?
Thanks in advance.
<?php
session_start();
if(isset($_POST['signup'])){
include_once("db.php");
$email=strip_tags($_POST['emailid']);
$username=strip_tags($_POST['username']);
$password=strip_tags($_POST['password']);
if($email==NULL || $username== NULL || $password==NULL){
print "Missing one of the fields";
}
else{
$email=stripslashes($email);
$username=stripslashes($username);
$password=stripslashes($password);
$email=mysqli_real_escape_string($db,$email);
$username=mysqli_real_escape_string($db,$username);
$password=mysqli_real_escape_string($db,$password);
$query = "SELECT * FROM user WHERE email='$email'";
$result = mysqli_query($db,$query);
if($result && mysqli_num_rows($result) > 0 )
{
echo "Account already exists.Please login";
}
else{
$sql="INSERT INTO user (ID,email,username,password) VALUES
(NULL,'$email','$username','$password')";
if($sql)
{
echo "Account created successfully.";
}
else
{
echo "Error";
}
}
}
}
?>
You are not executing the insert query, it should look like:
$sql="INSERT INTO user (ID,email,username,password) VALUES
(NULL,'$email','$username','$password')";
$sql= mysqli_query($db,$sql); ///You are missing this
Change from:
$sql="INSERT INTO user (ID,email,username,password) VALUES
(NULL,'$email','$username','$password')";
if($sql)
{
echo "Account created successfully.";
}
To:
$sql="INSERT INTO user (ID,email,username,password) VALUES
(NULL,'$email','$username','$password')";
if(mysqli_query($db,$sql))
{
echo "Account created successfully.";
}
You need to execute the 2nd query ($sql)
$sql="INSERT INTO user (email,username,password) VALUES
('$email','$username','$password')";
if(mysqli_query($db,$sql))
{
echo "Account created successfully.";
}
Remove the null INSERT value it's not needed and should be auto generated if auto-incremental index.
execute the $sql statement a a MySQLi_query and then use the result of that in the IF statement.
Bonus: Use mysqli_error($db) to feed you back errors you will encounter, such as:
mysqli_query($db,$sql) or die("error: ".mysqli_error($db));

PHP SQL Query Fails to Execute

<?php
$db = new mysqli("localhost", "HIDDEN", "HIDDEN", "HIDDEN");
if ($db->connect_error) {
die("Failed to connect.");
}
if (isset($_POST["title"]) && isset($_POST["description"]) && isset($_POST["url"])) {
$title = $db->real_escape_string($_POST["title"]);
$description = $db->real_escape_string($_POST["description"]);
$url = $db->real_escape_string($_POST["url"]);
$sql = "INSERT INTO video (name, description, submission_date)
VALUES ('{$title}', '{$description}', CURDATE());
INSERT INTO video_source (video_id, url)
VALUES (LAST_INSERT_ID(), '{$url}');";
if ($db->query($sql) === TRUE) {
echo "Successfully added.";
} else {
echo "Query failed.<br><br>Data: {$title} {$description} {$url}";
}
} else {
echo "Data not set.";
}
$db->close();?>
Outputs "Query failed." with the data I entered. Replacing variables such as title with constants still has the same problem. I tried the query in PHPMyAdmin and it worked fine (with constants).
It seems to be unhappy with setting the value of video_id.
Anytime you're running multiple queries with MySQLi you should use multi_query():
$db->multi_query($sql)
In addition, LAST_INSERT_ID() in your second query is not returning any sort of value. If you're looking for the last inserted value of the 1st query you have to return that prior to running the second query.

nothing being added to the database

<?php
if(isset($_POST['sub']))
{
$mname=$_POST['sub'];
}
if(isset($_POST['pos']))
{
$pos=$_POST['pos'];
}
if(isset($_POST['rad1']))
{
$vis=$_POST['rad1'];
}
global $mname, $pos, $vis;
$q= "INSERT INTO subjects (menu_name, position, visible) VALUES ('$mname', '$pos', '$vis')";
$qs=mysql_query($q, $connection);
if($qs)
{
header("Location: content.php");
exit;
}
else{
echo mysql_error();
}
?>
I get sub, pos and rad1 from a form
my database's primary key is auto-incrementing but rows are empty
Where is the mistake?
It seems like your $_POST array is empty.
Do a
<?php
print_r($_POST);
exit();
?>
This way we can know if are you getting an empty $_POST.
Try this code it should be working properly
<?php
mysql_connect("localhost","root","");
mysql_select_db("test");
$mname='abc';
$pos='13';
$vis='true';
$q= "INSERT INTO subjects (`menu_name`, `position`, `visible`) VALUES ('".$mname."', '".$pos."', '".$vis."')";
$qs=mysql_query($q);
if($qs)
{
//header("Location: db.php");
exit;
}
else{
echo mysql_error();
}
?>

success/error message for insert into mysql database

when the info is successfully inserted, it's displaying the error message and saying that it's a duplicate entry for a primary key...I can't figure out why!
<?
$email=$_POST['email'];
$pw=$_POST['pw'];
mysql_connect('***','***','***');
#mysql_select_db('***') or die('Unable to select database');
$query = "INSERT INTO test_table VALUES ('','$email','$pw')";
mysql_query($query) or die(mysql_error());
if(mysql_query($query))
{
echo 'success';
}
else
{
echo 'failure' .mysql_error();
}
mysql_close();
?>
You are executing the query twice: first, in mysql_query($query) or die(mysql_error()); and second, in if(mysql_query($query)). So the second time the query executes the record is already there and thus the insertion fails.
You are executing same query twice.
$query_result = mysql_query($query) or die(mysql_error());
if ($query_result) {
echo 'success';
} else {
echo 'failure' . mysql_error();
}
Write this way, hope it will work.
Just delete this code from your php script and it will be fine.
if(mysql_query($query))
{
echo 'success';
}
else
{
echo 'failure' .mysql_error();
}
You make it running error twice in a time. You can also use mysql_affected_rows() to make sure the data is executed in database server. Return a string type value.
<?
$email=$_POST['email'];
$pw=$_POST['pw'];
mysql_connect('***','***','***');
#mysql_select_db('***') or die('Unable to select database');
$query = "INSERT INTO test_table VALUES ('','$email','$pw')";
if(mysql_query($query))
{
echo 'Data executed : '.mysql_affected_rows();
}
else
{
echo 'failure' .mysql_error();
}
mysql_close();
?>
Good luck and let me know the result.
$email=$_POST['email'];
$pw=$_POST['pw'];
$alerts = array();
if (trim($_POST['email']) == '') {
$alerts[] = "<div class='alert alert-danger' role='alert'> Enter your Email! </div>"; }
if (trim($_POST['pw']) == '') {
$alerts[] = "<div class='alert alert-danger' role='alert'> Enter your PW! </div>"; }
if (!count($alerts)) {
$query = "INSERT INTO test_table (email, pw) VALUES ('".$email."', '".$pw."')";
mysqli_query($this->conn, $query) or die (mysqli_connect_error());
return ['success' => true];
} else {
return ['success' => false, 'alert_m' => implode($alerts)."<br>"];
}

Categories