Duplicate entries in SQL? - php

I keep getting duplicate posts in the SQL DB.
This is the code I am using to create the table and insert data into the DB..
$query = "SELECT * FROM '.$cname.' WHERE name='$itemname' and price='$price'";
$result = mysqli_query($db, $query);
$count = mysqli_num_rows($result);
if($count == 0){
//insert doesn't exist, continue
//insert sizes
$list = "";
$number = count($sizes);
$num = 0;
if($usesize == 'yes'){
$num = 1;
if($number > 0){
for($i=0; $i<$number; $i++){
if(trim($_POST["size"][$i] != '')){
if(empty($list)){
$list = $_POST["size"][$i];
}else{
$list .= ",".$_POST["size"][$i];
}
}
}
echo $list;
}
$quantitylist = "";
$quantitynumber = count($quantity);
if($quantitynumber > 0){
for($a=0; $a<$quantitynumber; $a++){
if(trim($_POST["quantity"][$a] != '')){
if(empty($quantitylist)){
$quantitylist = $_POST["quantity"][$a];
}else{
$quantitylist .= ",".$_POST["quantity"][$a];
}
}
}
echo $quantitylist;
}
}else{
$num = 0;
}
$colorlist = "";
$colornumber = count($colors);
$cnum = 0;
if($usecolors == 'yes'){
$cnum = 1;
if($colornumber > 0){
for($i=0; $i<$colornumber; $i++){
if(trim($_POST["colors"][$i] != '')){
if(empty($colorlist)){
$colorlist = $_POST["colors"][$i];
}else{
$colorlist .= ":".$_POST["colors"][$i];
}
}
}
echo $colorlist;
}
}else{
$cnum = 0;
}
$query = "INSERT INTO ".$cname." (name, description, imgpath, price, sold, usesize, usecolors) VALUES ('$itemname', '$description', '$insertloc"."$name', '$price', '0', '$num', '$cnum')";
if(mysqli_query($db, $query)){
//inserted successfully
echo "Inserted successfully!";
}else{
$uploadOk = 0;
echo mysqli_error($db);
}
$conn = mysqli_connect('localhost', 'grampmkn_gramsandpops', 'Grams123', 'grampmkn_shop_quantity');
if($conn){
$query = "CREATE TABLE `".$itemname."` (
id int NOT NULL AUTO_INCREMENT,
size varchar(500),
color varchar(500),
quantity int(100),
PRIMARY KEY(id),
UNIQUE(size)
);";
$array = explode(',', $list);
if(mysqli_query($conn, $query)){
mysqli_select_db($conn, $name);
$array = explode(',', $list);
foreach($array as $value){
$arrays = explode(':', $colorlist);
foreach($arrays as $values){
$arrays1 = explode(',', $quantitylist);
foreach($arrays1 as $values1){
$query = "INSERT INTO `".$itemname."` (size, color, quantity) VALUES ('$value', '$values', '$values1')";
if(mysqli_query($conn, $query)){
echo "Successfully inserted data into grampmkn_shop_quantity!";
}else{
echo mysqli_error($conn);
}
}
}
}
}else{
echo "Could not create table";
}
}else{
echo "Could not connect to shop quantity database!";
echo mysqli_errno($conn);
}
}else{
//insert already exists
echo "Insert already exists!";
$uploadOk = 0;
}
Image from DB.
If I remove the nested loops, then how would I get all the data in the arrays to insert into the sql database.
I am only creating the table once, I am just inserting multiple times to get all the data into the db.
Any help is appreciated.

Related

File path with '/' is not inserting in DB

I need to check duplicate files from a path and need to insert the file name in a table if it is new and then insert all records of it accordingly into another table. Do not insert or step forward if file already exists.
Here is my code where i can't bring the file path with '/' into the DB. Can anyone assist? Thanks in advance.
File Path with '/' is not passing using $open = fopen('$cont[$x]','r');
<?php
//include ("connection.php");
$conn = new mysqli('localhost','root','','demo');
$path = _DIR_ . DIRECTORY_SEPARATOR ."*.{txt}";
$cont = glob($path, GLOB_BRACE);
//print_r($content);
$arrlength = count($cont);
for($x = 0; $x < $arrlength; $x++){
// $sql = "INSERT INTO `file_record` (`file_name`) VALUES ('$cont[$x]') ";
$dup = mysqli_query($conn,"SELECT * FROM file_record WHERE file_name = '$cont[$x]' ");
if(mysqli_num_rows($dup)>0)
{
echo "File already Exists";
}
else {
$insert = "INSERT INTO `file_record` (`file_name`) VALUES ('$cont[$x]') ";
// $conn->query($insert);
if (mysqli_query($conn,$insert)) {
$open = fopen('$cont[$x]','r');
while (!feof($open))
{
$content = fgets($open);
$carry = explode(",",$content);
list($name,$city,$postcode,$job_title) = $carry;
$sql = "INSERT INTO `employee` (`name`, `city`, `postcode`, `job_title`) VALUES ('$name','$city','$postcode','$job_title')";
$conn->query($sql);
}
fclose($open);
echo 'inserted';
} else {
echo 'Not inserted';
}
}
}
?>

PHP - For loop only writing one submission to MySql

I'm currently working on a database where I would like the order_ID's to be put into two tables. This works but the issue I have is that the loop is only iterating once. If anyone could help and explain where I have gone wrong it would be greatly appreciated.
session_start();
echo $_SESSION['shop_id'];
$shopid = $_SESSION['shop_id'];
$username = $_SESSION['username'];
$con = mysqli_connect('localhost', 'root', '', 'aurora');
if (!isset($con)) {
echo "Connection to Aurora System failed.";
}
if (isset($_POST['items'])) {
echo "True";
} else {
echo "false";
}
$valid = true;
$date = date('l jS \of F Y h:i:s A');
$sql2 = "INSERT INTO orders_new (user_submitted, order_date, customer_ID) VALUES ('$username', '$date', '$shopid')";
if ($valid == true) {
$ordersubmit2 = mysqli_query($con, $sql2);
echo "Success!";
}
$count = $_POST['items'];
for ($i = 1; $i <= $count; $i++) {
$idinsert = mysqli_insert_id($con);
$product = $_POST['product'.$i];
$nicotine = $_POST['nicotine'.$i];
$qty = $_POST['qty'.$i];
echo $product;
$sql = "INSERT INTO orders_detail (orders_id ,product, variant, quantity) VALUES ('$idinsert', '".$product."', '".$nicotine."', '".$qty."')";
$ordersubmit = mysqli_query($con, $sql);
}
Was my own fault, the order_id was a primary key hence the loop stopping due to only allowing unique values.

multiple row saving to DB table

I have to save more than one row of data into database table.
I wrote this code for that. But when i run this code, two rows will be saved into two rows of db table, but every other row is same as the last row data.
i.e. that is the last row data is overwriting every other row data.
$values = array();
if (isset($_POST['sub_save'])) {
$row_count = $_POST['rowcount'];
while ($row_count > 0) {
for ($r = 1; $r <= 2; $r++) {
$val = $_POST['txt'.$row_count.$r];
$values[] = $val;
}
$row_count = $row_count - 1;
$sql = "insert into timesheet_entry (name, address) values ('$values[0]', '$values[1]')";
if (mysql_query($sql)) {
echo "inserted";
} else {
echo "fail";
}
}
}
You aren't resetting your values array inside the loop so values[0] and values[1] will always have the first to values.
if (isset($_POST['sub_save'])) {
$row_count = $_POST['rowcount'];
while ($row_count > 0) {
$values = array();
for ($r = 1; $r <= 2; $r++) {
$val = $_POST['txt'.$row_count.$r];
$values[] = $val;
}
$row_count = $row_count - 1;
$sql = "insert into timesheet_entry (name, address) values ('$values[0]', '$values[1]')";
if (mysql_query($sql)) {
echo "inserted";
} else {
echo "fail";
}
}
}
On a sidenote I would recommend looking into the PDO extension and parameterised queries as mysql_ is deprecated and the above code is vulnerable to SQL injection
You are mixing mysql and mysqli:
$conn = mysqli_connect("localhost", "root", "");
$db = mysqli_select_db("dbname");
if (mysqli_query($sql)) {
echo "inserted";
} else {
echo "fail";
}

Keeping a value in the database upon updating

This is my table in my database. It should only contain one row.
I have this code, that checks if there is no data , if there is not.. The data is inserted, else it's updated. The problem is, that if i update only Brevet, the value of Baccalaureabt will disappear from my database. Any help?
Code:
if(isset($_POST['submit']))
{ $brevet = $_POST['Brevet'];
$baccalaureatbt = $_POST['Baccalaureatbt'];
$sql1="SELECT Brevet,Baccalaureatbt FROM university";
if ($result=mysqli_query($con,$sql1))
{
$rowcount=mysqli_num_rows($result);
}
if($rowcount==0)
{
$sql="INSERT INTO university(Brevet,Baccalaureatbt) VALUES('$brevet','$baccalaureatbt')";
$result = mysql_query($sql);
}
else
{
$sql2 = "UPDATE university SET Brevet = '$brevet' , Baccalaureatbt = '$baccalaureatbt'";
$result2 = mysql_query($sql2);
}
The issue is that you are setting both values, if however either $baccalaureatbt or $brevet is empty, it will be updated with a empty value, i.e the original value will be deleted.
There are multiple ways to avoid this, but one way to do it is like so:
$sql2 = "UPDATE university SET ";
if(!empty($brevet)){
$sql2 .= "Brevet = '$brevet'";
$first = 1;
}
if(!empty($baccalaureatbt)){
$sql2 .= isset($first) ? ", Baccalaureatbt = '$baccalaureatbt'" : "Baccalaureatbt = '$baccalaureatbt' " ;
}
$result2 = mysql_query($sql2);
To update the values dynamically, use the following code. Just add the values you want in the values array.
if(isset($_POST['submit']))
{
$brevet = $_POST['Brevet'];
$baccalaureatbt = $_POST['Baccalaureatbt'];
$sql1="SELECT Brevet,Baccalaureatbt FROM university";
$result=mysqli_query($con,$sql1);
if ($result)
{
$rowcount=mysqli_num_rows($result);
}
if($rowcount==0)
{
$sql="INSERT INTO university(Brevet,Baccalaureatbt) VALUES('$brevet','$baccalaureatbt')";
$result = mysql_query($sql);
}
else
{
$values = array("brevet","baccalaureatbt");
$sql2 = "UPDATE university ";
$n = 0;
foreach($_POST as $key => $val) {
if(in_array($key, $values)) {
$sql2 += ($n !== 0 ? ", " : 0);
$sql2 += "SET".$key." = ".$val;
$n++;
}
if($n > 0) {
$result2 = mysql_query($sql2);
}
}
}
}

Records not inserting into mysql database

I am not getting any errors but the database does not get updated. Please render assistance. Here is my code.
<?php
ob_start();
include("dbinc.php");
$msg = "";
if($_SESSION['usertype'] != "admin"){
header("Location: index.php");
exit;
}
$pagetitle = "Sync Job Details";
include("header.php");
if(isset($_POST['Submitaccount'])){
$allowedusers = $_POST['users'];
$accountid = trim($_POST['accountid']);
if(!$_POST['copyperms']) $_POST['copyperms']='N';
if(!$_POST['allusers']) $_POST['allusers']='N';
if(!$_POST['enabled']) $_POST['enabled']='N';
if(!$_POST['servertime']) $_POST['servertime']='N';
if(!$_POST['delremovals']) $_POST['delremovals']='N';
unset($_POST['Submitaccount']);
unset($_POST['accountid']);
unset($_POST['users']);
// $qpart = "";
$notmust = array("email" , "skip" , "comments" , "firstmod");
foreach($_POST as $key=>$val){
if(!trim($val) && !in_array($key , $notmust)) {
$err = 1;
$empty = "$key";
break;
}
$qpart .= "`$key` = '".mysql_escape_string($val)."' , " ;
}
if($qpart) $qpart = substr($qpart , 0 , -2);
if(!$err){
$chk = mysql_num_rows(mysql_query("SELECT * from accounts WHERE name = '".mysql_escape_string($_POST['name'])."' and id <> '$accountid'"));
if($chk >0){
$err = 2;
}
}
if(!$err){
if(!$accountid){
$q = "INSERT into accounts SET $qpart ";
mysql_query($q) or die("Error inserting the record :".mysql_error()."<br>".$q);
$accountid = mysql_insert_id();
}else{
$q = "UPDATE accounts SET $qpart WHERE id = '$accountid'";
mysql_query($q) or die("Error updating the record :".mysql_error()."<br>".$q);
}
if($_POST['allusers']!= "Y" && is_array($allowedusers)){
mysql_query("DELETE from accountusers WHERE accountid = '$accountid'");
foreach($allowedusers as $userid){
list($alljobs) = mysql_fetch_row(mysql_query("SELECT alljobs from users WHERE id= '$userid'"));
if($alljobs != "Y") {
mysql_query("INSERT into accountusers SET userid = '$userid' , accountid = '$accountid'");
}
}
}else{
mysql_query("DELETE from accountusers WHERE accountid = '$accountid'");
}
header("location: accountslist.php?done=1");
exit;
}
}
// if(isset($_GET['id'])){
// $record = mysql_fetch_assoc(mysql_query("SELECT * from accounts WHERE id = '$_GET[id]'"));
// foreach($record as $key=>$val) $record[$key] = stripslashes($val);
// }
if(isset($_GET['id'])){
$record = mysql_fetch_assoc(mysql_query("SELECT * from accounts WHERE id = '$_GET[id]'"));
foreach($record as $key=>$val) $record[$key] = stripslashes($val);
}
// if($err ==1)
// {
// $record = $_POST;
// foreach($record as $key=>$val)
// $record[$key] = stripslashes($val);
// $msg ="Please fill the empty field";
// }
if( isset($err) && $err == 1 )
{
$record = $_POST;
foreach($record as $key=>$val) $record[$key] = stripslashes($val);
$msg ="Please fill the empty field";
}
if( isset($err) && $err == 2)
{
$msg = "The name has already been used.";
}
?>
I feel your frustration. If i could assist you i would. People in this forum are scared to answer you as they don't want to lose reputation points as the question was marked down to -4. I suggest do some more research and post your question eslewhere.

Categories