Duplicate Data is Inserted - php

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";
}
}
}
?>```

Related

particular query not running in php on Godaddy hosting

I am trying to run Insert query on my php page but its not executing and takes me to else part.
I have checked query on MySQL its fine. Also I have couple of select queries on the same page, and those works fine. So I am sure there is no issue with the connection or accessing DB. Heres my code:
<?php
session_start();
include './db_config.php';
if ((!isset($_SESSION['first_name']) == true)) {
unset($_SESSION['first_name']);
}
$logged = $_SESSION['first_name'];
if ((!isset($_SESSION['id']) == true)) {
unset($_SESSION['id']);
}
$id = $_SESSION['id'];
if ((!isset($_SESSION['email']) == true)) {
unset($_SESSION['email']);
}
$email= $_SESSION['email'];
$query1 = "select * from user_master where id='$id'";
$result1 = mysqli_query($con, $query1);
$num1 = mysqli_num_rows($result1);
if ($num1 > 0) {
while ($data = $result1->fetch_assoc()) {
$branch_name = $data['branch_name'];
}
}
if(isset($_POST['save'])){
$cust_id=$_POST['cust_id'];
$meter_no=$_POST['meter_no'];
$lock_no=$_POST['lock_no'];
$customer_name=$_POST['customer_name'];
$customer_type=$_POST['customer_type'];
$customer_zone=$_POST['customer_zone'];
$status=$_POST['status'];
$phoneno=$_POST['phoneno'];
$city=$_POST['city'];
$address=$_POST['address'];
$houseno=$_POST['houseno'];
$ownership=$_POST['ownership'];
$landmark=$_POST['landmark'];
$opening_reading=$_POST['opening_reading'];
$opening_reading_date=$_POST['opening_reading_date'];
$branch_name=$_POST['branch_name'];
$created_on=$_POST['created_on'];
$created_by=$_POST['created_by'];
$email=$_POST['email'];
$consumption=0;
$current_reading=$opening_reading;
$status1="True";
$total_bill=0;
$total_paid=0;
$total_dues=0;
$select="insert into meter(cust_id,meter_no,lock_no,customer_name,customer_type,customer_zone,status,phoneno,city,address,houseno,ownership,landmark,opening_reading,opening_reading_date,created_on,branch_name,created_by,email)
VALUES('$cust_id','$meter_no','$lock_no','$customer_name','$customer_type','$customer_zone','$status','$phoneno','$city','$address','$houseno','$ownership','$landmark','$opening_reading','$opening_reading_date','$created_on','$branch_name','$created_by','$email')";
if ($r = mysqli_query($con, $select)) {
else {
echo '<script language="javascript">';
echo 'alert("Information Not Inserted!!!");';
//echo 'window.location.href="bill_generation.php";';
echo '</script>';
}
}
I have Checked on Godaddy HERE that one need just Localhost as host name.
I know I have pasted a long piece of code, however dont know where the issue is.
You have a typo at the end of your code.
if ($r = mysqli_query($con, $select)) {
echo 'data inserted successfully !';
// do something ?
} // this one is missing
else {
echo '<script language="javascript">';
echo 'alert("Information Not Inserted!!!");';
//echo 'window.location.href="bill_generation.php";';
echo '</script>';
}

Update profile using php

I'm doing project and i want to update user profile using php mysql when i click
on update button it show that there are error in line 17. please help to find the error.
<?php
session_start();
if(!isset($_SESSION["n"]))
{
header("location:error.php");
}
if(isset($_POST["s"]))
{
$name=$_POST["nm"];
$lname=$_POST["lnm"];
$address=$_POST["ad"];
$u=$_SESSION["un"];
$query = "SELECT * FROM signup";
$result=mysqli_query($result,$query) or die(mysqli_connect_error());
$i=0;
while($row=mysqli_fetch_array($result))
{
$roll[$i]=$row['rollno'];
$i++;
}
$total_elmt=count($roll);
require_once("vars.php");
$conn=mysqli_connect(host,uname,pass,db) or die(mysqli_connect_error());
$query="update signup set name='$nm',lname='$lnm',address='$ad' where user_id='$value'";
$execute=mysqli_query($conn,$query);$r=mysql_affected_rows();
mysqli_close($conn);
$msg="Your information is submitted successfully";
}
?>
you need to open the database first to run the select query.
move this line to the top:
$conn=mysqli_connect(host,uname,pass,db) or die(mysqli_connect_error());
you are using mysqli_query function wrong. it should be
$result=mysqli_query($conn,$query) or die(mysqli_connect_error());
Now i have updated your code
<?php
session_start();
if(!isset($_SESSION["n"]))
{
header("location:error.php");
}
if(isset($_POST["s"]))
{
$name = $_POST["nm"];
$lname = $_POST["lnm"];
$address = $_POST["ad"];
$u = $_SESSION["un"];
$conn = mysqli_connect(host,uname,pass,db) or die(mysqli_connect_error());
$query = "SELECT * FROM signup";
$result = mysqli_query($conn, $query);
$i=0;
while($row=mysqli_fetch_array($result))
{
$roll[$i]=$row['rollno'];
$i++;
}
$total_elmt=count($roll);
require_once("vars.php");
$query="update signup set name='$nm',lname='$lnm',address='$ad' where user_id='$value'";
$execute=mysqli_query($conn,$query);
$r=mysql_affected_rows();
mysqli_close($conn);
$msg="Your information is submitted successfully";
}
?>

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

How to update values in table

I cannot update the values in my table with this code, if the update is successful the page should redirect in ('Location:ui.php'), how can this be achieved?
<?php
ob_start();
include('dbconnect.php');
$code=$_GET['stallcode'];
if(isset($_POST['submit']))
{
$pcost = $_POST['pcost'];
$tcost = $_POST['tcost'];
$cash = $_POST['cash'];
$change = $_POST['change'];
if (($cash == '0'))
{
$pstatus="0";
}
else
{
$pstatus="1";
}
$updated=mysql_query("UPDATE tbl_stallowner SET
paymentstatus='$pstatus', penaltycost='$pcost', totalcost='$tcost', cash='$cash', change='$change'
WHERE stallcode='$code'")or die();
if($updated)
{
$msg="Successfully Updated!!";
header('Location:ui.php');
}
} //update ends here
ob_end_flush();
?>
As you redirects users by checking if($updated) is true, this will not work, you should check the number of affected rows instead using mysql_num_rows.
Also remember to exit; after header() to stop the execution.
$num_rows = mysql_num_rows($updated);
if($num_rows > 0)
{
$msg="Successfully Updated!!";
header('Location:ui.php');
exit;
}
Tip: You should not be using MySQL as it has already been deprecated, use MySQLi instead.
You want to use mysqli, not it's predecessor, mysql. Mysql is vulnerable and open to exploitation, here's what you should write in each of your files:
dbconnect.php
<?php
$conn = mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
updatestallowner.php (or whatever you named it)
<?php
ob_start();
require('dbconnect.php');
$code = mysqli_real_escape_string($conn, $_GET['stallcode']);
if(isset($_POST['submit'])){
$pcost = mysqli_real_escape_string($conn, $_POST['pcost']);
$tcost = mysqli_real_escape_string($conn, $_POST['tcost']);
$cash = mysqli_real_escape_string($conn, $_POST['cash']);
$change = mysqli_real_escape_string($conn, $_POST['change']);
if ($cash == '0') {
$pstatus="0";
} else{
$pstatus="1";
}
$sql = "UPDATE tbl_stallowner SET paymentstatus='$pstatus', penaltycost='$pcost', totalcost='$tcost', cash='$cash', change='$change' WHERE stallcode='$code';";
$result = mysqli_query($conn, $sql);
if($result) {
$msg="Successfully Updated!!";
header('Location: ui.php');
exit;
} else {
die("Error updating!");
}
}
?>
Good luck!

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