Form submitting duplicate comments to mysql table - php

I have made a comment section to my pages which stores the comments in a mysql database. However when I click send, it sends duplicates of the same comment into the database. I can't see where I may have sent the query twice however.
<?php
if (!empty($_POST) && !empty($_POST['name']) && !empty($_POST['message'])) {
$name = strip_tags($_POST['name']);
$message = strip_tags($_POST['message']);
$name = mysqli_real_escape_string($db, $name);
$message = mysqli_real_escape_string($db, $message);
$query = "SELECT COUNT(*) AS count FROM comments";
$result = $db->query($query);
$data = $result->fetch_assoc();
$query = "INSERT INTO `comments` (`work_id`, `sender_ name`, `message`) VALUES ('".$id."','".$name."','".$message."')"; //id comes from a $_GET at the top of the page
$db->query($query);
$result = $db->query($query);
$query = "INSERT INTO `comment_work` (`comment_id`,`work_id`) SELECT `comments`.`id`, `comments`.`work_id` FROM `comments` WHERE `comments`.`sender_ name` = '".$name."' AND `comments`.`message` = '".$message."'";
$db->query($query);
$result = $db->query($query);
if ($result) {
echo "<p>Comment submitted!</p>";
} else {
echo "SQL Error: " . $db->error;
}
}
?>

Here
$query = "INSERT INTO `comments` (`work_id`, `sender_ name`, `message`) VALUES ('".$id."','".$name."','".$message."')"; //id comes from a $_GET at the top of the page
$db->query($query);//one query - **YOU must remove this line!**
$result = $db->query($query);//second query
To
$query = "INSERT INTO `comments` (`work_id`, `sender_ name`, `message`) VALUES ('".$id."','".$name."','".$message."')"; //id comes from a $_GET at the top of the page
$result = $db->query($query);
And here
$query = "INSERT INTO `comment_work` (`comment_id`,`work_id`) SELECT `comments`.`id`, `comments`.`work_id` FROM `comments` WHERE `comments`.`sender_ name` = '".$name."' AND `comments`.`message` = '".$message."'";
$result = $db->query($query);

Cause is simple:
Look at these code lines:
$query = "INSERT INTO `comments` (`work_id`, `sender_ name`, `message`) VALUES ('".$id."','".$name."','".$message."')"; //id comes from a $_GET at the top of the page
$db->query($query);
$result = $db->query($query);
$query = "INSERT INTO `comment_work` (`comment_id`,`work_id`) SELECT `comments`.`id`, `comments`.`work_id` FROM `comments` WHERE `comments`.`sender_ name` = '".$name."' AND `comments`.`message` = '".$message."'";
$db->query($query);
$result = $db->query($query);
Well, here you are executing a query with $db->query and then with $result = $db->query you executing another time the same query.
Replace this:
$query = "INSERT INTO `comment_work` (`comment_id`,`work_id`) SELECT `comments`.`id`, `comments`.`work_id` FROM `comments` WHERE `comments`.`sender_ name` = '".$name."' AND `comments`.`message` = '".$message."'";
$db->query($query);
$result = $db->query($query);
With:
$query = "INSERT INTO `comment_work` (`comment_id`,`work_id`) SELECT `comments`.`id`, `comments`.`work_id` FROM `comments` WHERE `comments`.`sender_ name` = '".$name."' AND `comments`.`message` = '".$message."'";
$result = $db->query($query);
And this:
$query = "INSERT INTO `comments` (`work_id`, `sender_ name`, `message`) VALUES ('".$id."','".$name."','".$message."')"; //id comes from a $_GET at the top of the page
$db->query($query);
$result = $db->query($query);
With:
$query = "INSERT INTO `comments` (`work_id`, `sender_ name`, `message`) VALUES ('".$id."','".$name."','".$message."')"; //id comes from a $_GET at the top of the page
$result = $db->query($query);
So should work.

Related

Updating beginning and ending values in mysql

I want to update the values of beginning and ending if the user enter an existing product. Is there something wrong in my update query? Thanks!
if(isset($_POST['status2'])){
$rowValues = explode("//", $_POST['status2']);
$orderId = $rowValues[0];
$dateReceivedNo = $rowValues[1];
$receivedDate = $_POST[$dateReceivedNo];
mysqli_query(connect(), "UPDATE `order` SET `status` = 'RECEIVED' WHERE `order_id` = '$orderId'");
$product = mysqli_query(connect(), "SELECT * FROM `order` WHERE `order_id` = '$orderId' AND branch_name = '$name' ");
$product2 = mysqli_fetch_assoc($product);
$cate = $product2['cat_name'];
$item = $product2['item_name'];
$prodName = $product2['product_name'];
$quantity = $product2['quantity'];
mysqli_query(connect(), "INSERT INTO `logs`(`log_id`, `branch_name`, `activity`, `date`) VALUES ('', '$name', 'RECEIVED ITEM ".$prodName. " ". $quantity ."', now())");
$count = mysqli_query(connect(), "SELECT count(invbranch_id) AS 'countItems' FROM `inventorybranch` WHERE `cat_name` = '$cate' AND `item_name` = '$item' AND `product_name` = '$prodName'");
$count2 = mysqli_fetch_assoc($count);
if($count2['countItems'] > 0){
mysqli_query(connect(), "UPDATE `inventorybranch` SET `beginning` = (`beginning` + '$quantity'), `date` = NOW() WHERE `cat_name` = '$cate' AND `item_name` = '$item' AND `product_name` = '$prodName' AND `status` = 'DELIVERED'");
mysqli_query(connect(), "UPDATE `inventorybranch` SET `quantity` = (`quantity` + '$quantity'), `date` = NOW() WHERE `cat_name` = '$cate' AND `item_name` = '$item' AND `product_name` = '$prodName' AND `status` = 'DELIVERED'");
}
else{
mysqli_query(connect(), "INSERT INTO `inventorybranch` VALUES ('','','$cate','','$item','','$prodName','$name','$quantity','$quantity','','','', now())");
}
mysqli_query(connect(), "UPDATE `inventoryho` SET quantity = (quantity-'$quantity') WHERE cat_name = '$cate' AND item_name = '$item' AND product_name = '$prodName'");
mysqli_query(connect(), "UPDATE `order` SET `date_receive` = now() WHERE `order_id` = '$orderId'");
}

Sending information from a newly created record to a different MySQL table

I'm making a form that submits a story into a MySQL table called 'work'. I want to later take the id of the newly created record and put the information into a different table.
But when I submit the story, it says:
$workid is undefined.
I can't see the problem though because I believe I've defined it?
<?php
if (!empty($_POST) && !empty($_POST['title']) && !empty($_POST['story']) && !empty($_POST['genre']) && !empty($_POST['rating'])) {
$title = strip_tags($_POST['title']);
$story = strip_tags($_POST['story']);
$title = mysqli_real_escape_string($db, $title);
$story = mysqli_real_escape_string($db, $story);
$genre = $_POST['genre'];
$rating = $_POST['rating'];
$query = "SELECT COUNT(*) AS count FROM works WHERE Title = '".$title."'";
$result = $db->query($query);
$data = $result->fetch_assoc();
if ($data['count'] > 0) {
echo "<p>Story already exists!</p>";
} else {
$query = "INSERT INTO works (author_id, login_id, Title, Story, Genre, Rating) VALUES ('".$userid."','".$authorid."','".$title."','".$story."','".$genre."','".$rating."')";
$query = "SELECT `id` FROM `works` WHERE `Title` = '".$title."'";
if ($result = $db->query($query)) {
while ($row = $result->fetch_assoc())
$workid = $row["id"]; //workid is written here but still considered undefined
}
$query = "INSERT INTO `author_work` (`author_id`) VALUES ('".$authorid."')";
$result = $db->query($query);
$query = "INSERT INTO `author_work` (`work_id`) VALUES ('".$workid."')";
$result = $db->query($query);
$query = "INSERT INTO `login_work` (`work_id`) VALUES ('".$workid."')";
$result = $db->query($query);
$query = "INSERT INTO `login_work` (`login_id`) VALUES ('".$userid."')";
$result = $db->query($query);
if ($result) {
echo "<p>Story submitted!</p>";
} else {
echo "SQL Error: " . $db->error;
}
}
}
?>
You never did a $db->query() on your INSERT INTO... query string, so it was never inserted, and was overwritten by your SELECT id ... query.
$query = "INSERT INTO works (author_id, login_id, Title, Story, Genre, Rating) VALUES ('".$userid."','".$authorid."','".$title."','".$story."','".$genre."','".$rating."')";
$db->query($query); // Missing this $db->query()
$query="SELECT `id` FROM `works` WHERE `Title` = '".$title."'";
if ($result = $db->query($query)) {
while ($row= $result->fetch_assoc())
$workid = $row["id"];}
Your $workid might not be initialized, depending on your condition and the result of your SQL query: so try to avoid next operations that will causes warnings/errors by using continue or else

Get data from 2 tables and insert into another

I need your help..
I am I trying to retrieve data from two tables and insert into another using php +mysql, but it doesn't work. It shows me this message (Query got problem).
This is my code:
$emp_id = $_SESSION['emp_id'];
$from= "select department.name from department,employee where emp_id='$emp_id' and department.dept_id = employee.dept_id ";
$result_form = mysql_query($from);
$dept_from = mysql_fetch_assoc($result_form);
$dept_name = $dept_from['department.name'];
$query = "INSERT INTO Student (date, description, from, emp_id, to)
VALUES
(now(),'$_POST[description]','$dept_name','$emp_id','$_POST[to]')";
$result = mysql_query($query);
if(!$result)
{die("Query got problem").(mysql_error());}
else{
Try this:
Your mysql query in not proper use like given below:
$emp_id = $_SESSION['emp_id'];
$from= "SELECT d.name FROM department d LEFT JOIN employee e ON d.dept_id = e.dept_id WHERE emp_id = '$emp_id' ";
$result_form = mysql_query($from);
$dept_from = mysql_fetch_assoc($result_form);
$dept_name = $dept_from['name'];
$query = "INSERT INTO Student (`date`, `description`, `from`, `emp_id`, `to`) VALUES (now(),'".$_POST[description]."','".$dept_name."','".$emp_id."','".$_POST[to]."')";
$result = mysql_query($query);
Let me know if you need further help.
Backticks might do the trick here.
$query = "INSERT INTO Student (`date`, `description`, `from`, `emp_id`, `to`)
VALUES
(now(),'$_POST[description]','$dept_name','$emp_id','$_POST[to]')";
Try this
$query = "INSERT INTO Student (date, description, from, emp_id, to)
VALUES
(now(),' " . $_POST['description'] ."','$dept_name','$emp_id','". $_POST['to']. "')";
Working Code below
$emp_id = 1;
$from= "select department.name from test.department,test.employee where emp_id='$emp_id' and department.dept_id = employee.dept_id ";
$result_form = mysql_query($from);
$dept_from = mysql_fetch_assoc($result_form);
$dept_name = $dept_from['name'];
$date = date("Y-m-d H:i:s");
$description = isset($_POST[description])?$_POST[description]:"none";
$to = isset($_POST[to])?$_POST[to]:"none";
$query = sprintf("INSERT INTO `test`.`test`
(`date`,
`description`,
`from`,
`emp_id`,
`to`)
VALUES
(
'%s',
'%s',
'%s',
'%s',
'%s'
);
",
$date,$description,$dept_name,$emp_id,$to);
$result = mysql_query($query);
if(!$result)
{
die("Query got problem").(mysql_error());
}

Ajax update, comparing and insert data to mysql

Good day,
As mention in the topic, I'm creating a ajax function where the php will directly update the status then if the status is 1 (or approve), it will compare between 2 table (tblcompany and tblinternapplication) and doing insert new company if the company not in the list. I tried test one by one it function well but after combine it doesn't add any new company when the person application approved (or set to 1) even the status in tblinternapplication updated. Below is my code.
<?php require_once("../includes/session.php"); ?>
<?php require_once("sessioncourse.php"); ?>
<?php confirm_logged_in(); ?>
<?php require_once("../includes/connection.php") ?>
<?php require_once("../includes/functions.php") ?>
<?php
$id = $_GET['id'];
$status =$_GET['status'];
$sql="UPDATE tblinternapplication set status_approval =
".mysql_real_escape_string($status) ." WHERE id = " .mysql_real_escape_string($id);
$result = mysql_query($sql);
$querysel = "SELECT i.company_code, c.company_name as cn, i.company_name as ic,
c.company_branch as cb, i.company_branch as ib, FROM tblcompany c,
tblinternapplication i WHERE i.id = '$id' ";
$resultsel = mysql_query($querysel, $connection);
$queryselc = "SELECT
company_name, company_branch,
company_address, post_code,
company_city, company_state,
company_country,
company_phone, company_fax,
company_url FROM tblinternapplication WHERE id = '$id' ";
$resultselc = mysql_query($queryselc, $connection);
if ($status == 1){
while($rowsel = mysql_fetch_array($resultsel)){
if($rowsel['company_code'] == NULL){
if(($rowsel['cn'] != $rowsel['ic']) OR ($rowsel['ib'] != $rowsel['cb'])){
while($rowselc = mysql_fetch_array($resultselc)){
$query = "INSERT INTO tblcompany (
company_name, company_branch,
company_address, post_code,
company_city, company_state, company_country,
company_phone, company_fax,
company_url
) VALUES (
'{$rowselc['company_name']}', '{$rowselc['company_branch']}',
'{$rowselc['company_address']}','{$rowselc['post_code']}',
'{$rowselc['company_city']}','{$rowselc['company_state']}',
'{$rowselc['company_country']}',
'{$rowselc['company_phone']}','{$rowselc['company_fax']}',
'{$rowselc['company_url']}'
)";
$resultc = mysql_query($query, $connection);
}
}
}
}
}
?>
Just to share the answer using my own method. Basically I remove 2-level nested while and make the first query row match then the second is to search for result. Hope this will help others.
<?php
$id = $_GET['id'];
$status = $_GET['status'];
$sql="UPDATE tblinternapplication set status_approval =
".mysql_real_escape_string($status) ." WHERE id = " .mysql_real_escape_string($id);
$result = mysql_query($sql);
$querysel = "SELECT i.company_code, i.company_name, i.company_branch, c.company_name,
c.company_branch FROM tblinternapplication i, tblcompany c WHERE i.company_name =
c.company_name AND i.company_branch = c.company_branch AND i.id = '$id' ";
$resultsel = mysql_query($querysel, $connection);
$queryselc = "SELECT * FROM tblinternapplication where id = '$id'";
$resultselc = mysql_query($queryselc, $connection);
if ($status == 1){
if(mysql_num_rows($resultsel) == 0){
while($rowselc = mysql_fetch_array($resultselc)){
$query = "INSERT INTO tblcompany (
company_name, company_branch,
company_address, post_code,
company_city, company_state, company_country,
company_phone, company_fax,
company_url
) VALUES (
'{$rowselc['company_name']}', '{$rowselc['company_branch']}',
'{$rowselc['company_address']}','{$rowselc['post_code']}',
'{$rowselc['company_city']}','{$rowselc['company_state']}',
'{$rowselc['company_country']}',
'{$rowselc['company_phone']}','{$rowselc['company_fax']}',
'{$rowselc['company_url']}'
)";
$resultc = mysql_query($query, $connection);
}
}
}
?>
if anyone have recommendation welcome to leave comments.
Thank you.

Data is not being stored in the database

My code is getting the ID from another, after I get that ID I will insert it to another table. The thing is it's not working, any idea why?
<?php
session_start();
include("Connection.php");
if (isset($_POST['submit'])){
$name = $_POST['customerName'];
mysql_query("INSERT INTO `starbucks`.`orders` (
`ID` ,
`NAME` ,
`TOTAL_PRICE` ,
`TOTAL_ITEMS` ,
`TIME`
)
VALUES (
'' , '$name', '', '',NOW())");
$_SESSION['user'] = $name;
}
$dTime = time();
$myValue = isset($_REQUEST['dValue']) ?$_REQUEST['dValue'] : '';
echo "The time is: {$dTime}<br/>
The choice is {$myValue} ";
$sql = "Select * from product where NAME = '{$myValue}'";
$result = mysql_query($sql);
while ($row = mysql_fetch_assoc($result)){
$price = $row['PRICE'];
$id = $row['ID'];
echo $id;
$sql2 ="INSERT INTO starbucks`.order_details (ID, ORDER_ID, PRODUCT_ID, QTY) VALUES ('', '', '$id', '1')";
$result2 = mysql_query($sql2);
}
?>
extra back tick in the INSERT, either add another or remove

Categories