success/error message for insert into mysql database - php

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>"];
}

Related

Duplicate Data is Inserted

when i insert data my select query is not working and data is directly insert. My search query is not working but data is directly inserted.please help me.how my serach query is start please check the code.
session_start();
error_reporting(0);
include('includes/config.php');
if(strlen($_SESSION['alogin'])=="")
{
header("Location: index.php");
}
else{
if(isset($_POST['submit']))
{
$classname=$_POST['classname'];
$classnamenumeric=$_POST['classnamenumeric'];
$section=$_POST['section'];
$q="SELECT * FROM tblclasses Where (ClassName='$classname' AND Section='$section');";
$res=mysqli_query($dbh,$q);
if (mysqli_num_rows($res) > 0) {
$row = mysqli_fetch_assoc($res);
if($classname==$row['ClassName'] && $section==$row['Section'])
{
echo '<script>alert("already exists")</script>';
}
}else{
$sql="INSERT INTO tblclasses(ClassName,ClassNameNumeric,Section) VALUES(:classname,:classnamenumeric,:section)";
$query = $dbh->prepare($sql);
$query->bindParam(':classname',$classname,PDO::PARAM_STR);
$query->bindParam(':classnamenumeric',$classnamenumeric,PDO::PARAM_STR);
$query->bindParam(':section',$section,PDO::PARAM_STR);
$query->execute();
$lastInsertId = $dbh->lastInsertId();
if($lastInsertId)
{
$msg="Class Created successfully";
}
else
{
$error="Something went wrong. Please try again";
}
}
}
?>```

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));

After running a query, message of succes action

How to return a success/failure message after running the query and how to check for exist data in product_code data array before saving the data?
$query = mysql_query("INSERT INTO `produk2`
(product_code,product_name,product_desc,product_type,product_price,product_img,product_img_name)
VALUES ('$kod','$namaproduk','$spesifikasi','$jenis','$harga','$image','$name')");
}
I tried to run this code and doesn't seems to work. Any ideas? I've gone wrong?
$result=mysql_query($query);
if($result)
{
echo "<br/>Data uploaded.";
}
else
{
echo "<br/>Data not uploaded.";
}
You should use mysql_error() or mysql_errno().
See the manual
manual
Add if else condition to the return result of query.
$query = mysql_query("INSERT INTO `produk2`
(product_code,product_name,product_desc,product_type,product_price,product_img,product_img_name)
VALUES ('$kod','$namaproduk','$spesifikasi','$jenis','$harga','$image','$name')");
if($query)
{
echo "Data inserted";
}
else
{
echo "Sorry! Data not inserted";
}

empty field to mysql using php

i have code for save 3 textbox in one field in databse
no problem when i am enter 3 textbox , but when i fill 1 textbox and press ok
save another textbox in database as blank
i want just take the textbox is fulled and ignore the textbox empty
this is my code
<?php
include("connect.php");
$expert_name = trim($_POST['expert_name']);
$expert_name2 = trim($_POST['expert_name2']);
$expert_name3 = trim($_POST['expert_name3']);
// this is for arabic language.
mysql_query("SET NAMES utf8");
// Insert data into mysql
$sql="INSERT INTO experts(id,expert_name) VALUES(NULL, '$expert_name')";
$sql2="INSERT INTO experts(id,expert_name) VALUES(NULL, '$expert_name2')";
$sql3="INSERT INTO experts(id,expert_name) VALUES(NULL, '$expert_name3')";
$result=mysql_query($sql);
$result2=mysql_query($sql2);
$result3=mysql_query($sql3);
// if successfully insert data into database, displays message "Successful".
if($result){
echo "Successful";
echo "<BR>";
// echo "<a href='formadd.php'>Back to main page</a>";
}
else {
echo "ERROR";
echo "<br>";
// this for print error in insert process
echo mysql_error();
echo "<a href='expert_add.php'><br>Please try again </a>";
}
//mysql_close($con);
?>
back to form add
Execute your sql query only the variable value not equal to empty.
try this,
$expert_name = trim($_POST['expert_name']);
$expert_name2 = trim($_POST['expert_name2']);
$expert_name3 = trim($_POST['expert_name3']);
// this is for arabic language.
mysql_query("SET NAMES utf8");
// Insert data into mysql
if ($expert_name != "") {
$sql = "INSERT INTO experts(id,expert_name) VALUES(NULL, '$expert_name')";
$result = mysql_query($sql);
}
if ($expert_name2 != "") {
$sql2 = "INSERT INTO experts(id,expert_name) VALUES(NULL, '$expert_name2')";
$result2 = mysql_query($sql2);
}
if ($expert_name != "") {
$sql3 = "INSERT INTO experts(id,expert_name) VALUES(NULL, '$expert_name3')";
$result3 = mysql_query($sql3);
}
// if successfully insert data into database, displays message "Successful".
if ($result || $result2 || $result3) {
echo "Successful";
echo "<BR>";
// echo "<a href='formadd.php'>Back to main page</a>";
} else {
echo "ERROR";
echo "<br>";
// this for print error in insert process
echo mysql_error();
echo "<a href='expert_add.php'><br>Please try again </a>";
}
//mysql_close($con);
?>
back to form add
You should also check $result2 and $result3. I added that in this answer
try this
if ( !empty($_POST['expert_name']) ){
$sql="INSERT INTO experts(id,expert_name) VALUES(NULL, '$expert_name')";
$result=mysql_query($sql);
}
if ( !empty($_POST['expert_name2']) ){
$sql2="INSERT INTO experts(id,expert_name) VALUES(NULL, '$expert_name2')";
$result2=mysql_query($sql2);
}
if ( !empty($_POST['expert_name3']) ){
$sql3 ="INSERT INTO experts(id,expert_name) VALUES(NULL, '$expert_name3')";
$result3 =mysql_query($sql3 );
}
Then you might want to check if the variable is empty().
<?php
include("connect.php");
$expert_name = trim($_POST['expert_name']);
$expert_name2 = trim($_POST['expert_name2']);
$expert_name3 = trim($_POST['expert_name3']);
// this is for arabic language.
mysql_query("SET NAMES utf8");
// Insert data into mysql
if(!empty($expert_name)) {
$sql="INSERT INTO experts(id,expert_name) VALUES(NULL, '$expert_name')";
$result=mysql_query($sql);
}
if(!empty($expert_name2)) {
$sql2="INSERT INTO experts(id,expert_name) VALUES(NULL, '$expert_name2')";
$result2=mysql_query($sql2);
}
if(!empty($expert_name3)) {
$sql3="INSERT INTO experts(id,expert_name) VALUES(NULL, '$expert_name3')";
$result3=mysql_query($sql3);
}
// if successfully insert data into database, displays message "Successful".
if($result){
echo "Successful";
echo "<BR>";
// echo "<a href='formadd.php'>Back to main page</a>";
}
else {
echo "ERROR";
echo "<br>";
// this for print error in insert process
echo mysql_error();
echo "<a href='expert_add.php'><br>Please try again </a>";
}
Also note: You only check if $result is okay. If you only fill textbox 2 and leave 1 empty, the value of 2 it will get inserted but an error is shown.
I'd say your code need general review, but as it is for now you will have to do something like this each query:
if (!empty($expert_name2){
$result2=mysql_query($sql2)
}
But you should try to loop your queries in foreach rather than manually write every on query. And by the way:
if($result){
echo "Successful";
echo "<BR>";
// echo "<a href='formadd.php'>Back to main page</a>";
}
This code only return succes when 1st wuery success because you use $result which is set in 1st query only
The ID is probably NOT NULL AUTO_INCREMENT, so that won't accept NULL as value.
try sending blank value, such as:
$sql="INSERT INTO experts(id,expert_name) VALUES ('', '$expert_name')";
Also, build bulk insert, rather than multiple.
I will explain why, when you insert single insert into the database, the values being inserted, then, the DB engine flushes indexes (they written to disk), unless you have set delay_key_write=ALL in you my.cnf. Index flushing directly affects your db performance.
Please, check the reworked code out. The code adjusted for bulk insert, sql string escaping for security purposes and additional verification for post keys existence.
<?php
include("connect.php");
// this is for arabic language.
mysql_query("SET NAMES utf8");
$values = array();
$skipInsert = true;
$fields = array('expert_name', 'expert_name2', 'expert_name3');
$insert = "INSERT INTO experts(id,expert_name) VALUES ";
// Loop through predefined fields, and prepare values.
foreach($fields AS $field) {
if(isset($_POST[$field]) && !empty($_POST[$field])) {
$values[] = "('', '".mysql_real_escape_string(trim($_POST[$field]))."')";
}
}
if(0 < sizeof($values)) {
$skipInsert = false;
$values = implode(',', $values);
$insert .= $values;
}
if(false === $skipInsert) {
mysql_query($insert);
}
// if successfully insert data into database, displays message "Successful".
if($result){
echo "Successful","<BR>";
// echo "<a href='formadd.php'>Back to main page</a>";
} else {
echo "ERROR","<br>",mysql_error(),"<a href='expert_add.php'><br>Please try again </a>";
}
HTH,
VR
if(!empty($textbox1_value)) {
//DO SQL
}
You can repeat this for multiple boxes however you wish, the empty operator checks if its empty, so if its not empty the "//DO SQL" area will get run.

PHP query inserts 2 rows into the table

OK, here is the deal. I have 3 queries putting data in different tables. 2 of them are in included files. I've tried to put them into the main code, the result was the same. The first two queries inserts one row with the data and a blank row. The third works fine. Here is the code.
This in the main page:
<? $p=0;
if ($select2)
{
$event=$select2;
}
else
{
require_once("insert_gal_name.php5");
}
if ($select)
{
$folder=$select;
}
else
{
require_once("insert_folder.php5");
if (file_exists("Connections/".$folder))
{
}
else
{
mkdir("Connections/$folder",0777);
}
}
while($p<$number)
{
$p++;
$dir = 'Connections/'.$folder.'/'; // Директорията в която ще се записват файловете
copy($_FILES['file']['tmp_name'][$p],"$dir".$_FILES['file']['name'][$p]); //Копиране на файла
echo "Файлът бе качен успешно!<br>"; // Извеждане на съобщение показващо, че файла е качен
if($_FILES['file']['name'][$p])
{
$real_file_name = $dif_of_files.$_FILES['file']['name'][$p];
$nom_file = str_replace(" ", "", $real_file_name); }
$query = "INSERT INTO gallery (name, title, day, month, year) VALUES ('$nom_file', '$event', '$day', '$month', '$year')";
$result = mysql_query($query) or die(mysql_error());
}
if (!$result)
{
echo "Error";
}
else
{
echo "All data was uploaded successfuly.";
}
?>
And here are the includes in the order they are placed in the source
<? $query = "INSERT INTO gallery_names (name) VALUES ('$event')";
$result = mysql_query($query) or die(mysql_error());
if (!$result)
{
echo "Error";
}
else
{
echo "The gallery was created successfuly.";
}
?>
<? $query = "INSERT INTO folders (name) VALUES ('$folder')";
$result = mysql_query($query) or die(mysql_error());
if (!$result)
{
echo "Error";
}
else
{
echo "The folder was created successfuly.";
}
?>
<?
if($event!='')
{
$query1 = "INSERT INTO gallery_names (name) VALUES ('$event')";
$result1 = mysql_query($query1) or die(mysql_error());
if (!$result1)
{
echo "Error";
}
else
{
echo "The gallery was created successfuly.";
}
}
?>
If $select2 is false then this code will do two inserts. If $event is empty one of these will be an empty row which sounds like the problem you're having.
What are the values of $select2 and $event? Have you tried debugging them?

Categories