mysql_insert_id(); keeps returning '0' - php

I'm trying to grab the id after a query using mysql_insert_id();, but I'm still getting 0 despite the fact that
I've placed it after the query itself and
I've made sure that the id (called P_Id) has AUTO_INCREMENT.
Code below:
$con=mysqli_connect(-connectiondetails-);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO clients (Name, Email, Address, Phone, Date, Service, ExtraOne, ExtraTwo, ExtraThree, ExtraFour, ExtraFive) VALUES ('$_POST[name]','$_POST[email]','$_POST[address]','$_POST[phone]','$_POST[date]','$_POST[service]','$_POST[extra1]','$_POST[extra2]','$_POST[extra3]','$_POST[extra4]','$_POST[extra5]')";
$idit = mysql_insert_id();
echo $idit;
if (mysqli_query($con,$sql))
{
}
else
{
echo "Error message goes here: " . mysqli_error($con);
}
Thinking "Oh okay maybe I have to actually query it first", I did the following but came up with the same result:
$con=mysqli_connect(-connectiondetails-);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO clients (Name, Email, Address, Phone, Date, Service, ExtraOne, ExtraTwo, ExtraThree, ExtraFour, ExtraFive) VALUES ('$_POST[name]','$_POST[email]','$_POST[address]','$_POST[phone]','$_POST[date]','$_POST[service]','$_POST[extra1]','$_POST[extra2]','$_POST[extra3]','$_POST[extra4]','$_POST[extra5]')";
if (mysqli_query($con,$sql))
{
$idit = mysql_insert_id();
echo $idit;
}
else
{
echo "Error message goes here: " . mysqli_error($con);
}
Any idea where I went wrong? I've gone through other threads but nothing seems to be working for me. Thanks in advanced.
EDIT: I have changed mysql_insert_id(); to mysqli_insert_id(); and this time it didn't even return a 0, just blank.
EDIT 2: Thank you mbouzahir - your solution worked :)

Tried using mysqli_insert_id($con) instead of mysql_insert_id() in your second example?

Your query is vulnerable to SQL injection. You should be using prepared statements with parameter binding. Try this (and yes, I'm using the OOP API because it's a damn site cleaner)
$con = new mysqli(-connectiondetails-);
if ($con->connect_errno) {
throw new Exception($con->connect_error, $con->connect_errno);
}
$stmt = $con->prepare(
'INSERT INTO clients (Name, Email, Address, Phone, Date, Service, ExtraOne, ExtraTwo, ExtraThree, ExtraFour, ExtraFive)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');
if ($stmt === false) {
throw new Exception($con->error);
}
// you should probably check here that all required POST params are present
$stmt->bindParam('sssssssssss',
$_POST['name'],
$_POST['email'],
$_POST['address'],
$_POST['phone'],
$_POST['date'],
$_POST['service'],
$_POST['extra1'],
$_POST['extra2'],
$_POST['extra3'],
$_POST['extra4'],
$_POST['extra5']);
if (!$stmt->execute()) {
throw new Exception($stmt->error);
}
echo $con->insert_id;

Try this one
$con=mysqli_connect(-connectiondetails-);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO clients (Name, Email, Address, Phone, Date, Service, ExtraOne, ExtraTwo, ExtraThree, ExtraFour, ExtraFive) VALUES ('$_POST[name]','$_POST[email]','$_POST[address]','$_POST[phone]','$_POST[date]','$_POST[service]','$_POST[extra1]','$_POST[extra2]','$_POST[extra3]','$_POST[extra4]','$_POST[extra5]')";
if (mysqli_query($sql,$con))
{
$idit = mysqli_insert_id();
echo $idit;
}
else
{
echo "Error message goes here: " . mysql_error($con);
}

Related

I'm trying to do Signup and Login with PHP and MySQL

I'm trying to do Signup and Login with PHP and MySQL.. but when I enter the same email it shows me error... When I try to enter the same email.. already registered, it shows me an error. It should redirect straight to signup-success.html, but instead it shows an error on line 45.. i tried replacing it with
but even this didn't help..
I'm new to php so I'm following the tutorial I'm using to do this... https://www.youtube.com/watch?v=5L9UhOnuos0
{
$stmt->execute();
} catch (mysqli_sql_exception $e) {
if ($e->getCode() == 1062) {
die("email address is already taken");
}
}
--------------------------------------------------------------------------
$password_hash = password_hash($_POST["password"], PASSWORD_DEFAULT);
$mysqli = require __DIR__ . "/database.php";
$sql = "INSERT INTO user (name, email, password_hash)
VALUES (?, ?, ?)";
$stmt = $mysqli->stmt_init();
if ( ! $stmt->prepare($sql)) {
die("SQL error: " . $mysqli->error);
}
$stmt->bind_param("sss",
$_POST["name"],
$_POST["email"],
$password_hash);
if ($stmt->execute()) {
header("Location: signup-success.html");
exit;
} else {
if ($mysqli->errno === 1062) {
die("email already taken");
} else {
die($mysqli->error . " " . $mysqli->errno);
}
}
This is what website shows..
Fatal error: Uncaught mysqli_sql_exception: Duplicate entry 'email#seznam.cz' for key 'email' in D:\Programy\XAMPP\XAMPP\htdocs\login01\process-signup.php:45 Stack trace: #0 D:\Programy\XAMPP\XAMPP\htdocs\login01\process-signup.php(45): mysqli_stmt->execute() #1 {main} thrown in D:\Programy\XAMPP\XAMPP\htdocs\login01\process-signup.php on line 45
Your call to ->execute() is throwing an exception when you attempt to do your INSERT and it fails due to a duplicate value. (The rules about exception throwing changed in php version 8.) Exceptions are a bit of a pain in php; it's tricky to catch them and handle them completely without logging them.
Here's what to do about that.
Change your query to say INSERT IGNORE.
$sql = "INSERT IGNORE INTO user (name, email, password_hash)
VALUES (?, ?, ?)";
Check whether the insert succeeded using affected_rows with code like this:
$result = $stmt->execute();
if ($result && $mysqli->affected_rows === 1) {
header("Location: signup-success.html");
exit;
} else if ($result && $mysqli->affected_rows !== 1)
die("email already taken");
} else {
die($mysqli->error . " " . $mysqli->errno);
}
This will let you control your logic without relying on error numbers except for when your SQL statement crashes and burns, not when you get a UNIQUE INDEX collision.

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')"

Unable to insert data on mysql using php

I am getting error
Undefined variable: company_name.
but some fields are inserted in database.
<?php
$con=mysqli_connect("localhost","root","","vdl");
// Check connection
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if(isset($_POST['submit'])){ // Fetching variables of the form which travels in URL
$Company_name = $_POST['company_name'];
$since = $_POST['since'];
$strength = $_POST['strength'];
$head_quarter = $_POST['head_quarter'];
if($company_name !=''||$since !=''){
mysqli_query($con,"insert into digital_library(company_name, since, strength, head_quarter) values ('$company_name', '$since', '$strength', '$head_quarter')");
mysqli_close($con);
}
else{
echo "<p>Insertion Failed <br/> Some Fields are Blank....!!</p>";
}
}
?>
First of all, mysql_* functions are deprecated as of PHP 5.5, and have been completely removed as of PHP 7.0.
Staying up to date with whats new and good now you reguarly want to update things aswell as PHP. Knowing that the mysql_* functions are deprecated (not under active development) we should not use them anymore (we can't even use them anymore if you have updated your php). Anyways back to the point you should not use mysql_* functions especially not now you are new to programming because you will have to update your php someday meaning you will have to change all of your code.
As of the code below:
This is mysqli_* mysqli.php
I have added a check on the db connection checking if that is actually working since you did not check the connection. Because even without that connection working that if loop would still return you your echo.
In mysqli_* you also have to add the connection in the query string.
<?php
$con=mysqli_connect("localhost","root","","vd1");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if(isset($_POST['submit'])){ // Fetching variables of the form which travels in URL
$company_name = $_POST['company_name'];
$since = $_POST['since'];
$strength = $_POST['strength'];
$head_quarter = $_POST['head_quarter'];
if($company_name !=''||$since !=''){
mysqli_query($con,"insert into digital_library(company_name, since, strength, head_quarter) values ('$company_name', '$since', '$strength', '$head_quarter')");
mysqli_close($con);
}
}
?>
First of all mysql is deprecated. Don't use mysql. Use either mysqli or pdo.
In your given code,
Add condition after $query statement to get exact error.
if (!$query) {
$message = 'Invalid query: ' . mysql_error() . "\n";
die($message);
}
else {
echo "<br/><br/><span>Data Inserted successfully...!!</span>";
}
You should trace all errors that may occur. I suggest to use prepared statement, try this:
<?php
$sql = new mysqli("localhost", "root", "", "vdl");
if($sql->connect_errno)
return printf("MySQL Connection Error #%d: %s", $sql->connect_errno, $sql->connect_error);
// I'd recommend to not use $_POST['submit'], it'd be better to check all the fields (company_name, since, strength, head_quarter) using the strlen() function
// for example: if(strlen($company = $_POST["company_name"]) && strlen($since = $_POST["since"])) ... etc.
if(isset($_POST["submit"]))
{
if(!$sm = $sql->prepare("INSERT INTO `digital_library` (`company_name`, `since`, `strength`, `head_quarter`) VALUES (?, ?, ?, ?)"))
return printf("Unable to prepare statement. Error #%d: %s", $sm->errno, $sm->error);
if(!$sm->bind("ssss", $_POST["company_name"], $_POST["since"], $_POST["strength"], $_POST["head_quarter"]))
return printf("Unable to bind parameters. Error #%d: %s", $sm->errno, $sm->error);
if(!$sm->execute())
return printf("MySQL Query Error #%d: %s", $sm->errno, $sm->error);
printf("The query has successfully executed!");
} else
printf("There's nothing to see, get outta here");
?>
If you don't want to use prepared statement, do this:
<?php
$sql = new mysqli("localhost", "root", "", "vdl");
if($sql->connect_errno)
return printf("MySQL Connection Error #%d: %s", $sql->connect_errno, $sql->connect_error);
if(
strlen( $company = $sql->real_escape_string($_POST["company_name"]) )
&& strlen( $since = $sql->real_escape_string($_POST["since"]) )
&& strlen( $strength = $sql->real_escape_string($_POST["strength"]) )
&& strlen( $head_quarter = $sql->real_escape_string($_POST["head_quarter"]) )
) {
$query = sprintf("INSERT INTO `digital_library` (`company_name`, `since`, `strength`, `head_quarter`) VALUES ('%s', '%s', '%s', '%s')", $company, $since, $strength, $head_quarter);
if(!$q = $sql->query($query))
return printf("MySQL Query Error #%d: %s", $sql->errno, $sql->error);
printf("The query has successfully executed!");
} else
printf("There's nothing to see, get outta here");
?>
Do one thing and It will be easy for you to debug-
Change this
$query = mysql_query("insert into digital_library(company_name, since, strength, head_quarter) values ('$company_name', '$since', '$strength', '$head_quarter')");
echo "<br/><br/><span>Data Inserted successfully...!!</span>";
to
echo "insert into digital_library(company_name, since, strength, head_quarter) values ('$company_name', '$since', '$strength', '$head_quarter')";
Now when you submit you get the original query in response.
Now run this query in phpmyadmin manually and see the results. Correct the issues phpmyadmin gives you and update your query in your script accordingly.

PHP MYSQL long query fails in php but works in mysql

ok so I have written some code that is doing a backup of configuration items. This script runs fine for everything else, but fails when it gets to this long query for this specific configuration item.
for sanity purposes I am just going to include the code for this section.
function writepool($pool, $device){
$pooltext = implode('', $pool['list']);
$sql = "INSERT into pools (deviceid, name, config) VALUES (
'".$device."',
'".$pool['pool']."',
'".addslashes($pooltext)."'
)";
echo $sql;
$addpool = insertdb($sql);
}
function insertdb($sql){
include('/var/www/db_login.php');
$conn = new mysqli($db_host, $db_username, $db_password, "F5");
// check connection
if ($conn->connect_error) {
trigger_error('Database connection failed: ' . $conn->connect_error, E_USER_ERROR);
}
if($conn->query($sql) === false) {
trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $conn->error, E_USER_ERROR);
} else {
$last_inserted_id = $conn->insert_id;
$affected_rows = $conn->affected_rows;
}
$result["lastid"] = $last_inserted_id;
$result["affectedrow"] = $affected_rows;
return $result;
$conn->close();
}
The error message I get is as follows
Fatal error: Wrong SQL: INSERT into pools (deviceid, name, config) VALUES ( '71', 'shopping.a.prod_pool_53601', 'ltm pool /Common/shopping.a.prod_pool_53601 { load-balancing-mode weighted-least-connections-node members { /Common/10.216.26.55:53601 { address 10.216.26.55 priority-group 1 } /Common/10.216.26.57:53601 { address 10.216.26.57 priority-group 1 } /Common/10.216.26.58:53601 { address 10.216.26.58 priority-group 1 } /Common/10.216.26.59:53601 { address 10.216.26.59 priority-group 1 } /Common/10.216.26.60:53601 { address 10.216.26.60 priority-group 1 } /Common/10.216.26.61:53601 { address 10.216.26.61 priority-group 1 } /Common/10.216.26.62:53601 { address 10.216.26.62 priority-group 1 } /Common/10.216.26.66:53601 { in /var/www/html/functions.php on line 2286
Note the query is extremely long. This particular configuration item is huge. I am storing this inside a BLOB in MYSQL.
If I echo the $sql variable I can see my entire query string. The query is too long to place here.
'If I copy the query string to MYSQL it works.
Also if I copy the query string from my echo. and use a test page and put $sql= to the string echo'd by my failed script. it works. I wish I could post the query but it is too long due to blob data.
****** UPDATE *********
I did what tadman suggested, I moved to a prepared statement. However, now I am not getting any data input into the blob in my table.
function writepool($pool, $device){
$pooltext = implode('', $pool['list']);
/*
$sql = "INSERT into pools (deviceid, name, config) VALUES (
'".$device."',
'".$pool['pool']."',
'".addslashes($pooltext)."'
)";
*/
#$addpool = insertdb($sql);
include('/var/www/db_login.php');
$mysqli = new mysqli($db_host, $db_username, $db_password, "F5");
// Check connection
if($mysqli === false){
die("ERROR: Could not connect. " . $mysqli->connect_error);
}
// Prepare an insert statement
$sql = "INSERT into pools (deviceid, name, config) VALUES (?, ?, ?)";
if($stmt = $mysqli->prepare($sql)){
// Bind variables to the prepared statement as parameters
$stmt->bind_param("ssb", $db_device, $db_pool, $db_text);
// Set parameters
$db_device = $device;
$db_pool = $pool['pool'];
$db_text = addslashes($pooltext);
// Attempt to execute the prepared statement
if($stmt->execute()){
#echo "Records inserted successfully.";
} else{
echo "ERROR: Could not execute query: $sql. " . $mysqli->error;
}
} else{
echo "ERROR: Could not prepare query: $sql. " . $mysqli->error;
}
// Close statement
$stmt->close();
// Close connection
$mysqli->close();
}
$db_text is a section of configuration data generated by a system file. I was storing this as a blob since it is huge (1600+ lines long).

Can't write to the database using INSERT INTO

I have written a form with server side validation using php and now my aim is to insert all the input's from my form into my database (which already has its tables). Below is my syntax:
//Example of one of my validations (for postcode input)
if (empty($_POST["postcode"])) {
$postcodeErr = "";
} else {
$postcode = test_input($_POST["postcode"]);
if(!preg_match("/^[0-9]*$/", $postcode)) {
$postcodeErr = "Only numeric characters";
}
else if (strlen($postcode) != 4) {
$postcodeErr = "Must be 4 digits in length";
}
}
}
//Connect to database server
$conn = mysql_connect("localhost", "-----", "------");
mysql_select_db("-------", $conn)
or die ('Database not found ' . mysql_error() );
// The SQL statement is built
$sql = "INSERT INTO Customer (name, address, suburb, state, postcode)
VALUES ('$_POST[name]', '$_POST[address]', '$_POST[suburb]', '$_POST[$state]', '$_POST[postcode]')";
if (!mysql_query($sql,$conn))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($conn)
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?> //end of my php tag
When I run my form, I get a parse error saying that I have an unexpected T_FUNCTION. I know there is a lot above (tried to make it as simple as I can) but I can't seem to word around fixing the error and if I do, I just get another error. Am I writing the code correctly? Normally it's best when other people look at your work. Help will be much appreciated!
The quotes for $_POST['name'] and all other variables was missing in the post variable.
Try with
$name=$_POST['name'];
$address=$_POST['address'];
$suburb=$_POST['suburb'];
$state=$_POST['$state'];
$postcode=$_POST['postcode'];
$sql = "INSERT INTO Customer (name, Address, suburb, state, postcode)
VALUES ('$name', '$address', '$suburb', '$state', '$postcode')";
you also have one extra brace above database connection, use mysqli prepared statements for better security.
$db = new mysqli('localhost', 'root', '', 'database');
if ($db->connect_errno) {
echo "failed to connect to the database"; die();
}
$name=$_POST['name'];
$address=$_POST['address'];
$suburb=$_POST['suburb'];
$state=$_POST['$state'];
$postcode=$_POST['postcode'];
$stmt = $db->prepare("insert into `Customer` (name, Address, suburb, state, postcode) VALUES (?,?,?,?,?)";
$stmt->bind_param('sssss', $name, $address, $suburb, $state, $postcode);
$stmt->execute();
echo $stmt->affected_rows."record added";
mysql_close($conn) Needs to have a ; after it...
That's why the function after it is unexpected
Agreed with Fred, there seems to be an extra ending brace just above //Connect to database server which is breaking the code.
If that doesn't fix it, please copy/paste your full error message.
EDIT:
else if (strlen($postcode) != 4) {
needs to be
} else if (strlen($postcode) != 4) {
And there are two extra braces at the end of that if statement (just above the //Connect to database server)

Categories