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());
}
Related
I am trying to build a sale invoice page that takes multiple products as input and also some information about the customer. It interacts with four MySQL tables (sales, sale_details, posting, and product_inventory). You'll get the idea of what will happen if a query fails. I want to avoid this. For this purpose I am trying to implement transactions feature of the InnoDB database engine using PHP and MySQL (PHPMyAdmin). Another problem is I've heard that autocommit is turned off by default do I need to turn it ON and then OFF every time I fire a query? Here is my PHP code snippet:
$sal_date = trim($_POST["sale_date"]);
$cust_id = trim($_POST["cust_id"]);
$book_no = trim($_POST["sal_book_no"]);
$rem = $_POST["sal_remarks"];
$st = trim($_POST["sub_total"]);
$disc = floatval($_POST["total_disc"]) + floatval($_POST["adj_disc"]);
$total = trim($_POST["grand_total"]);
$query1 = mysqli_query($link, "INSERT INTO sales
(cust_id, book_no, sale_date, sub_total, discount, total, remarks)
VALUES ('$cust_id', '$book_no', '$sal_date', '$st', '$disc', '$total', '$rem')") or die(mysqli_error($link));
$query2 = mysqli_query($link, "SELECT LAST_INSERT_ID() as last_row") or die(mysqli_error($link));
$sal_id = mysqli_fetch_array($query2);
$sal = intval($sal_id["last_row"]);
$the_query1 = mysqli_query($link, "INSERT INTO `posting`(`type`, `account_id`, `tr_id`, `tr_date`, `debit`) VALUES ('SI','$cust_id','$sal', '$sal_date', '$total')") or die(mysqli_error($link));
$the_query2 = mysqli_query($link, "INSERT INTO `posting`(`type`, `account_id`, `tr_id`, `tr_date`, `credit`) VALUES ('SI','10002','$sal', '$sal_date', '$total')") or die(mysqli_error($link));
for($count=0; $count<$_POST["total_item"]; $count++)
{
$prod_id = floatval(trim($_POST["product_name"][$count]));
$quantity = floatval(trim($_POST["qty"][$count]));
$disc = floatval(trim($_POST["disc"][$count]));
$query3 = mysqli_query($link, "INSERT INTO sale_details (sal_id, prod_id, quantity, discount) VALUES ('$sal', '$prod_id', '$quantity', '$disc')") or die(mysqli_error($link));
$query4 = mysqli_query($link, "INSERT INTO product_inventory (invoice_id, product_id, qty_out, in_date) VALUES ('$sal', '$prod_id', '$quantity', '$sal_date')") or die(mysqli_error($link));
}
I'll appreciate your suggestions.
You can use this method
mysqli_query($db, "START TRANSACTION");
$query1 = mysqli_query($db, "Query 1");
$query2 = mysqli_query($db, "Query 2");
$query3 = mysqli_query($db, "Query 3");
if($query1 && $query2 && $query3) {
mysqli_query($db, "COMMIT");
} else {
mysqli_query($db, "ROLLBACK");
}
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.
I'm a newbie to PHP and MySQL. I know there are lots of similar threads but I just can't seem to find one with my issue.
At the moment I have a table named 'movies' in my database. I have a search form to search for movies in that table. I'm using the code below to get the information from my database and display it.
$query = "SELECT * FROM movies WHERE titleid='$urlid'";
$result = $con->query($query);
if( !$result ) {
die('Query failed!<br>'.$con->error);
}
if( $result->num_rows == 0 ) {
}
while( $row = $result->fetch_assoc() ) {
echo $row['id'];
echo $row['title']; //this is not all of the columns just an example
}
What I want to do is:
If $urlid does not match 'titleid' then I want to add it to the database. At the moment I'm using the code below to add an entry:
$query = "INSERT IGNORE INTO movies (id, aka, ratio, budget, cast, fullcast, linkcast, castcharacter, linkcastcharacter, company, linkcompany, description, directors, linkdirectors, genre, mpaa, synopsis, poster, rating, releasedate, runtime, sound, officialsites, tagline, title, trailerlink, titleid, year)
VALUES (NULL, '$aka', '$ratio', '$budget', '$cast', '$fullcast', '$linkcast', '$castcharacter', '$linkcastcharacter', '$company', '$linkcompany', '$description', '$directors', '$linkdirectors', '$genre', '$mpaa', '$synopsis', '$poster', '$rating', '$releasedate', '$runtime', '$sound', '$officialsites', '$tagline', '$title', '$trailerlink', '$urlid')";
mysqli_query($con, $query);
How could I combine them so if the record does not exist it adds it and then displays the information it has added?
Thanks
Lee
$query = "SELECT * FROM movies WHERE titleid='$urlid'";
$result = $con->query($query);
if( !$result ) {
die('Query failed!<br>'.$con->error);
}
if( $result->num_rows == 0 ) {
$addQuery = "*your query here*";
$con->query($query);
echo "Movie added."
} else {
while( $row = $result->fetch_assoc() ) {
echo $row['id'];
echo $row['title']; //this is not all of the columns just an example
}
}
This will add it if there are no rows and otherwise show the results.
Only a supplement:
If your values are same order as in the 'movies' table, then you can use the shortest way:
$query = "INSERT IGNORE INTO movies VALUES (
NULL, '$aka', '$ratio', '$budget', '$cast', '$fullcast', '$linkcast', '$castcharacter', '$linkcastcharacter', '$company',
'$linkcompany', '$description', '$directors', '$linkdirectors', '$genre', '$mpaa', '$synopsis', '$poster', '$rating',
'$releasedate', '$runtime', '$sound', '$officialsites', '$tagline', '$title', '$trailerlink', '$urlid')";
mysqli_query($con, $query);
You can insert and then select again, like this code:
$query = "SELECT * FROM movies WHERE titleid='$urlid'";
$result = $con->query($query);
if( !$result ) {
die('Query failed!<br>'.$con->error);
}
if( $result->num_rows == 0 ) {
$insert_query = "INSERT IGNORE INTO movies (id, aka, ratio, budget, cast, fullcast, linkcast, castcharacter, linkcastcharacter, company, linkcompany, description, directors, linkdirectors, genre, mpaa, synopsis, poster, rating, releasedate, runtime, sound, officialsites, tagline, title, trailerlink, titleid, year)
VALUES (NULL, '$aka', '$ratio', '$budget', '$cast', '$fullcast', '$linkcast', '$castcharacter', '$linkcastcharacter', '$company', '$linkcompany', '$description', '$directors', '$linkdirectors', '$genre', '$mpaa', '$synopsis', '$poster', '$rating', '$releasedate', '$runtime', '$sound', '$officialsites', '$tagline', '$title', '$trailerlink', '$urlid')";
mysqli_query($con, $insert_query);
$result = $con->query($query);
if( !$result ) {
die('Query failed!<br>'.$con->error);
}
}
while( $row = $result->fetch_assoc() ) {
echo $row['id'];
echo $row['title']; //this is not all of the columns just an example
}
Also, I noticed that your INSERT statement may not be correct. Missing $year in values part.
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.
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