how to avoid duplicate data with php - php

How do I avoid duplicate data when we enter the same data again? instead, I want to issue a warning:
sorry your username has been used
I'm using php script, I have done it to overcome duplicate data but the results have unexpected errors.
This is my code, please correct it if you wish. thanks
<?php
if (isset($_POST['submit'])) {
$npm_siswa = $_POST['npm_siswa'];
$nama_siswa = $_POST['nama_siswa'];
$bidangst_siswa = $_POST['bidangst_siswa'];
$ipk_siswa = $_POST['ipk_siswa'];
$query ="INSERT INTO class(npm_siswa, nama_siswa, bidangst_siswa, ipk_siswa) VALUES('$npm_siswa','$nama_siswa','$bidangst_siswa','$ipk_siswa')";
$insert_data = mysqli_query($con, $query);
$goto = header('location: input_data.php');
if (headers_sent($goto) == true) {
exit();
}
}
$checking = "SELECT * FROM class WHERE npm_siswa ='$npm_siswa'";
$process = mysqli_query($con, $checking) or die(mysqli_error());
while($row_filter = mysqli_fetch_assoc($process)) {
$kelasId = $row_filter['kelasId'];
$npm_siswa = $row_filter['npm_siswa'];
$nama_siswa = $row_filter['nama_siswa'];
$bidangst_siswa = $row_filter['bidangst_siswa'];
$ipk_siswa = $row_filter['ipk_siswa'];
}
if (mysqli_num_rows($process) > 0) {
echo "maaf nama anda sudah digunakan";
} else {
$data = "INSERT INTO class(npm_siswa, nama_siswa, bidangst_siswa, ipk_siswa) VALUES('$npm_siswa','$nama_siswa','$bidangst_siswa','$ipk_siswa')";
$check = mysqli_query($con, $data);
}
?>

The easy way is to first select rows from mysql using a select statement, and then check if the array is empty.
$checking = "SELECT * FROM class WHERE npm_siswa ='$npm_siswa'";
$process = mysqli_query($con, $checking) or die(mysqli_error());
if(empty($process)) {
echo "maaf nama anda sudah digunakan";
} else {
$data = "INSERT INTO class(npm_siswa, nama_siswa, bidangst_siswa, ipk_siswa) VALUES('$npm_siswa','$nama_siswa','$bidangst_siswa','$ipk_siswa')";
$check = mysqli_query($con, $data);
}

Another solution: make sure that it is the DBMS that controls the uniqueness, with a UNIQUE constraint. Then test your mysqli_query's return value to handle the error.
$process = mysqli_query($con, $checking);
if (!$process)
{
// Handle your error
}
Pros : Only one query
Cons : The error is not necessarily due to the UNIQUE constraint

Related

Php webservice inserting data to a database

In my Authentication.php class I hava a code like below;
public function prepareTicket($data){
if(array_key_exists('tickettype', $data))
$this->tickettype = $data['tickettype'];
if(array_key_exists('ticketinfo', $data))
$this->ticketinfo = $data['ticketinfo'];
}
function createTicket(){
$sql = "INSERT INTO ticket_test (tickettype, ticketinfo) VALUES ('$this->tickettype','$this->ticketinfo')";
$result = mysqli_query($this->DB_CONNECTION,$sql);
}
function createTicketControl(){
$sql = "SELECT * FROM `ticket_test` WHERE tickettype = '".$this->tickettype."'AND ticketinfo ='".$this->ticketinfo."'";
$result = mysqli_query($this->DB_CONNECTION,$sql);
if(mysqli_num_rows($result) >0){
return true;
}else{
return false;
}
}
and in the other php file I have a code like this;
<?php
include_once 'Authentication.php';
use user\Authentication;
$auth = new Authentication();
$auth->prepareTicket($_POST);
$ticketStatus = $auth->createTicketControl();
if($ticketStatus){
$json['success'] = 1;
$json['message'] = 'Destek kaydı oluşturuldu';
}else{
$json['success'] = 0;
$json['message'] = 'Error!';
}
echo json_encode($json);
Now my problem is that whenever I try to insert data to my database it returns 'success' = '0' , 'message' = 'Error' and the data couldnt be inserted on the database.I mean the service is not working properly.Any help is appreciated...
P.S.= I am aware of sql injection threat on this code bu it is for android app so no need to worry about it.
Found the solution.I realised that in CreateTicket.php I didint call createTicket function from Authentication.php :/

Resource id #6 error, Not sure how to fix it

I keep getting a 'Resource id # 6' failure when submitting a script on my website. The code I'm using is the same type of code I use for registering for the website and that works but this script doesn't work at all. What my code does is send a booking request with the fields as shown to the database. I keep getting a Resource id#6 error , and I've googled what that is but I can't seem to figure out whats wrong. I am a beginner at php , so any tips on whats to look for to avoid a resource id # 6 error would be a lot of help
<?php
//$pattern="/^.+#.+/.com/";
//error_reporting(0);
if(isset($_POST["submit"])){
$Name_of_Person = $_POST['Name_of_Person'];
$Name_of_Group = $_POST['Name_of_Group'];
$room = $_POST['room'];
$How_Many_People = $_POST['How_Many_People'];
$Date_of_Booking = $_POST['Date_of_Booking'];
$End_time = $_POST['End_time'];
$Purpose = $_POST['Purpose'];
$Contact_Number = $_POST['Contact_Number'];
$Contact_Email = $_POST['Contact_Email'];
$Alcohol = $_POST['Alcohol'];
$Security = $_POST['Security'];
$Projector = $_POST['Projector'];
$Extra_Chairs = $_POST['Extra_Chairs'];
$Extra_Info = $_POST['Extra_Info'];
$Activated = '0';
$con = mysql_connect('localhost','root','test123') or die("couldn't connect");
mysql_select_db('bookerdb') or die("couldn't connect to DB");
//if(filter_var($email, FILTER_VALIDATE_EMAIL)){//(preg_match($pattern, $_POST['Contact_Email'])){
$query = mysql_query("SELECT * FROM `booking_table` WHERE Date_of_Booking='".$Date_of_Booking."' AND room='".$room."'");
$numrows = mysql_num_rows($query);
echo $query;
if($numrows==0){
$sql="INSERT INTO `booking_table` (Name_of_Person,Name_of_Group,room,How_Many_People,Date_of_Booking,End_time,Purpose,Contact_Number,Contact_Email,Alcohol,Security,Projector,Extra_Chairs,Extra_Info, Activated) VALUES ('$Name_of_Person','$Name_of_Group','$room','$How_Many_People','$Date_of_Booking','$End_time','$Purpose','$Contact_Number','$Alcohol','$Security','$Projector','$Extra_Chairs','$Extra_Info',$Activated)";
$result = mysql_query($sql);
if($result){
echo "Sent to be approved";
$redirect_page = '../ASC.php';
$redirect = true;
if($redirect==true){
header('Location: ' .$redirect_page);
}
}else{
echo "Failed";
}
}else{
echo"There is already a requested booking on that date & time";
$redirect_page = '../EAR.php';
$redirect = true;
if($redirect==true){
header('Location: ' .$redirect_page);
}
}
/*}else{
echo "error";
$redirect_page = '../EWF.php';
$redirect = true;
if($redirect==true){
header('Location: ' .$redirect_page);
}
}*/
}
?>
You have error in your second SQL query. You try to insert 14 values into 15 columns (in values you forgot $Contact_Email).
$sql="INSERT INTO `booking_table` (Name_of_Person,Name_of_Group,room,How_Many_People,Date_of_Booking,End_time,Purpose,Contact_Number,Contact_Email,Alcohol,Security,Projector,Extra_Chairs,Extra_Info, Activated) VALUES ('$Name_of_Person','$Name_of_Group','$room','$How_Many_People','$Date_of_Booking','$End_time','$Purpose','$Contact_Number','$Contact_Email','$Alcohol','$Security','$Projector','$Extra_Chairs','$Extra_Info',$Activated)";
Than remove echo $query from your code, line 30.
In $query isn't query, but mysql result object. You can't work with that by this way, you can't echo it.

Disable updating data when database is empty

I am having a problem when I want to echo "The stock is less than what you want". The problem is the user still can update the cart when the stock in my database less that what the user wants. It should show an error "The stock is less than what you want".
This is my code.
<?php session_start();
require("config.php");
$user = $_SESSION['userlogin'];
$cek = mysql_query("SELECT * FROM transaksitbl WHERE username = '$user' AND status ='0'") or die(mysql_error());
$result = mysql_num_rows($cek);
$data = mysql_fetch_array($cek);
if ($result > 0)
{
$faktur =$data['notransaksi'];
for ($i=1; $i<=$_POST['n']; $i++)
{
$idp = $_POST['id'.$i];
$cari2 = mysql_query("SELECT * FROM barangtbl WHERE id='$idp'") or die(mysql_error());
$row2 = mysql_fetch_array($cari2);
$har = $row2['harga'];
$stock = $row2['stock'];
if($_POST['n'] <= $row2['stock'])
{
echo "The stock is less than what you want";
}
if ($cari2)
{
$jmlubah = $_POST['jumlah'.$i];
$beratnew = $jmlubah*$row2['berat'];
$totubah = $jmlubah*$har;
$query = mysql_query("UPDATE transaksirincitbl SET jumlah = $jmlubah, jumlah_berat = $beratnew, total_berat = $beratnew, subtotal=$totubah
WHERE id ='$idp' and username = '$user' And notransaksi =$faktur") or die(mysql_error());
}
}
}
header ("location:shopping_cart.php");
?>
If i understood you properly the
if($cari2){}
function is executing?
All you are checking there is if the $cari2 variable is true.
Simply make a else statement out of the if($cari2){} statement so that if the stock is less than you wan't the second if statement won't get executed.
So, like this:
if($_POST['n'] <= $row2['stock']){
echo "The stock is less than you want";
}
else {
if($scari2){
$jmlubah = $_POST['jumlah'.$i];
$beratnew = $jmlubah*$row2['berat'];
$totubah = $jmlubah*$har;
$query = mysql_query("UPDATE transaksirincitbl SET jumlah = $jmlubah, jumlah_berat = $beratnew, total_berat = $beratnew, subtotal=$totubah
WHERE id ='$idp' and username = '$user' And notransaksi =$faktur") or die(mysql_error());
} else {
die('Woop, there seems to be a problem with the $scari2 variable. The value is:' . $scari2);
} // END OF INNER ELSE
} // END OF ELSE
And one more thing NEVER forget to use the mysql_real_escape_string() function on a variable before submiting it's value to the database.

php mysql insert and update

Hy there, I guess I've tried everything I could. Somehow my form doesn't work.
I get an ID through the URL - Which I try to use to update the MySQL table
I use the same Form also to input a new Record and there is no problem. But to update it doesn't work at all.
if (true !=$fehler)
{
if ($clientid == 'new')
{
$qy = 'INSERT INTO tbl_clientdb (
clientid,
c_update,
c_Uupdate,
c_Gender,
c_IDNumber,
c_Name,
c_Firstname,
c_Middlename,
c_idCity,
c_idCountry,
c_idLanguage,
c_Phone,
c_Cellphone,
c_Email,
c_Note,
c_idCompany
)
VALUES (
NULL,
NOW(),
"'.$c_Uupdate.'",
"'.$c_Gender.'",
"'.$c_IDNumber.'",
"'.$c_Name.'",
"'.$c_Firstname.'",
"'.$c_Middlename.'",
"'.$c_idCity.'",
"'.$c_idCountry.'",
"'.$c_idLanguage.'",
"'.$c_Phone.'",
"'.$c_Cellphone.'",
"'.$c_Email.'",
"'.$c_Note.'",
"'.$c_idCompany.'"
)';
} else {
$qy = 'UPDATE
tbl_clientdb
SET
c_update = NOW(),
c_Uupdate = "'.$c_Uupdate.'",
c_Gender = "'.$c_Gender.'",
c_IDNumber = "'.$c_IDNumber.'",
c_Name = "'.$c_Name.'",
c_Firstname = "'.$c_Firstname.'",
c_Middlename = "'.$c_Middlename.'",
c_idCity = "'.$c_idCity.'",
c_idCountry = "'.$c_idCountry.'",
c_idLanguage = "'.$c_idLanguage.'",
c_Phone = "'.$c_Phone.'",
c_Cellphone = "'.$c_Cellphone.'",
c_Email = "'.$c_Email.'",
c_Note = "'.$c_Note.'",
c_idCompany = "'.$c_idCompany.'"
WHERE
clientid = '.$clientid.'
LIMIT 1';
}
if ($res = mysql_query($qy))
{
echo 'Your data has been saved successfully';
}
else
{
echo mysql_error();
$meld = 'Please try again';
}
}`
anybody an idee what could be the trouble?
thx a lot for any inputs.
$qy = 'SELECT
clientid,
c_update,
c_Uupdate,
c_Gender,
c_IDNumber,
c_Name,
c_Firstname,
c_Middlename,
c_idCity,
c_idCountry,
c_idLanguage,
c_Phone,
c_Cellphone,
c_Email,
c_Note,
c_idCompany
FROM tablename WHERE id='$id' LIMIT 1";
$query = mysqli_query($yourConnection, $qy) or die (mysqli_error());
While ($row = mysqli_fetch_array($query)) {
/* Create a variable to hold all the data */
$c_update = $row['c_update'];
/* Do same for the rest */
}
Mysqli_free_result($query);
?>
Hope this helps

Array objects not being printed in input fields and sql query not receiving the id value

I am getting the id from another page but i am not being able to pass it to the sql query. If i define any value to $id instead of 0 then the query works but otherwise it fails.
Secondly, i would like to display the values of the array in respective input fields. I tried using
<?php
echo $result_array['institutename'][0];
?>
in the body part but it didnt work out.
My rest code is as follows:
(I know the mysql functions are deprecated but i would move on to mysqli as soon as i have solved this problem)
<?php
include 'connect.php';
$id=0;
$result_array=array();
if(isset($_REQUEST['id'])){
$id=(int)$_REQUEST['id'];
//$uid=$id;
if(!empty($id)){
$sql = "SELECT * FROM institute WHERE id =$id";
$result = mysql_query($sql);
while($row = mysql_fetch_assoc($result)){
$result_array[]=$row;
}
}
}
if ($_SERVER['REQUEST_METHOD'] == 'POST' && $_POST['form_institutedetails'] == 'saveinstitutedetails')
{
$mysql_table='institute';
$institutename = $_POST['institutename'];
$established = $_POST['established'];
$regno = $_POST['reg_no'];
$branch = $_POST['branch'];
$initials = $_POST['initials'];
$address=$_POST['address'];
$pin=$_POST['pin'];
$contact1=$_POST['contact1'];
$contact2=$_POST['contact2'];
$contact3=$_POST['contact3'];
$fax1=$_POST['fax1'];
$fax2=$_POST['fax2'];
$email=$_POST['email'];
$website=$_POST['website'];
if(isset($_POST['head_office'])){
$head_office=$_POST['head_office'];
}
else{
$head_office="Branch";
}
if (!preg_match("/^.+#.+\..+$/", $email))
{
$error_message = 'Email is not a valid email address. Please check and try again.';
}
if (empty($error_message))
{
$newinstitutename = mysql_real_escape_string($institutename);
$newestablished = mysql_real_escape_string($established);
$newregno = mysql_real_escape_string($regno);
$newbranch = mysql_real_escape_string($branch);
$newaddress = mysql_real_escape_string($address);
$newpin = mysql_real_escape_string($pin);
$newemail = mysql_real_escape_string($email);
$newwebsite = mysql_real_escape_string($website);
$ho = mysql_real_escape_string($head_office);
include 'connect.php';
$sql = "UPDATE `".$mysql_table."` SET `institutename`='$newinstitutename', `established`='$newestablished', `regno`='$newregno', `branch`='$newbranch', `initials`='$initials', `address`='$newaddress', `pin`='$newpin', `contact1`='$contact1', `contact2`='$contact2', `contact3`='$contact3', `fax1`='$fax1', `fax2`='$fax2', `email`='$newemail', `website`='$newwebsite', `head_office`='$ho' WHERE `id`=$id";
$result = mysql_query($sql, $db);
mysql_close($db);
$error_message='Updated Successfully!.';
}
}
?>
When you are unsure about the structure of an array, you can always do a print_r during development.
print_r($result_array);
In this case, it is an index array of associative arrays.
To access the first record's institutename (and probably the only record since it looks like you used an unique key in your query), you can use
echo $result_array[0]['institutename'];

Categories