Ajax update, comparing and insert data to mysql - php

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.

Related

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

insert into database with condition

When I update the book_Status from table book to AVAILABLE I do not succeed to change reserve_Status to RESERVED. What's wrong with my script ?
reserve.php:
<?php
include 'dbconnect.php';
$query1 ="
SELECT b.book_Status, r.reserve_Status
FROM book b
JOIN reservations r
ON r.book_Accession = b.book_Accession
";
$result1 = mysql_query($query1) or die('SQL error');
$row1 = mysql_fetch_array($result1, MYSQL_ASSOC);
if ($row1['book_Status'] == 'Available')
{
$Reserved = "Reserved";
}
$query2 = "INSERT INTO reservations
WHERE reserve_Status = '$Reserved' ";
?>
You need a update query. and move that query into your if statement
if ($row1['book_Status'] == 'Available')
{
$Reserved = "Reserved";
$query2 = "UPDATE reservations SET reserve_status = 'reserved' WHERE book_Status='Available'";
}
The problem is that you changed the value of the variable $Reserved but you did not query the database to perform the update.

PHP MySQL array error [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am having trouble with a function for a PHP/MySQL instant messaging system. A variable ($sql) is defined as a MySQL query, which is then queried, and returns a resource ID. However, the following while statement returns 'Array' instead of its supposed contents.
<?php
// Fetches a summary of the conversations.
function fetch_conversation_summary(){
$sql = "SELECT
`conversations`.`conversation_id`,
`conversations`.`conversation_subject`,
MAX(`conversations_messages`.`message_date`) AS `conversation_last_reply`,
MAX(`conversations_messages`.`message_date`) > `conversations_members`.`conversation_last_view` AS `conversation_unread`
FROM `conversations`
LEFT JOIN `conversations_messages` ON `conversations`.`conversation_id` = `conversations_messages`.`conversation_id`
INNER JOIN `conversations_members` ON `conversations`.`conversation_id` = `conversations_messages`.`conversation_id`
WHERE `conversations_members`.`user_id` = {$_SESSION['user_id']}
AND `conversations_members`.`conversation_deleted` = 0
GROUP BY `conversations`.`conversation_id`
ORDER BY `conversation_last_reply` DESC";
$result = mysql_query($sql);
$conversations = array();
while (($row = mysql_fetch_assoc($result)) !== false){
$conversations[] = array(
'id' => $row['conversation_id'],
'subject' => $row['conversation_subject'],
'last_reply' => $row['conversation_last_reply'],
'unread_messages' => ($row['conversation_unread'] == 1),
);
}
return $conversations;
}
// Fetches all of the messages in the given converstion.
function fetch_conversation_messages($conversation_id){
$conversation_id = (int)$conversation_id;
$sql = "SELECT
`conversations_messages`.`message_date`,
`conversations_messages`.`message_date` > `conversations_members`.`conversation_last_view` AS `message_unread`,
`conversations_messages`.`message_text`,
`users`.`user_name`
FROM `conversations_messages`
INNER JOIN `users` ON `conversations_messages`.`user_id` = `users`.`user_id`
INNER JOIN `conversations_members` ON `conversations_messages`.`conversation_id` = `conversations_members`.`conversation_id`
WHERE `conversations_messages`.`conversation_id` = {$conversation_id}
AND `conversations_members`.`user_id` = {$_SESSION['user_id']}
ORDER BY `conversations_messages`.`message_date` DESC";
$result = mysql_query($sql);
echo $result;
$messages = array();
while (($row = mysql_fetch_assoc($result)) !== false){
$messages[] = array(
'date' => $row['message_date'],
'unread' => $row['message_unread'],
'text' => $row['message_text'],
'user_name' => $row['user_name'],
);
}
var_dump( $messages );
}
// Sets the last view time to the current time for the given conversation.
function update_conversation_last_view($conversation_id){
$conversation_id = (int)$conversation_id;
$time = time() + 18000;
$sql ="UPDATE `conversations_members`
SET `conversation_last_view` = {$time}
WHERE `conversation_id` = {$conversation_id}
AND `user_id` = {$_SESSION['user_id']}";
mysql_query($sql);
}
// Creates a new conversation, making the given users a member.
function create_conversation($user_ids, $subject, $body){
$subject = mysql_real_escape_string(htmlentities($subject));
$body = mysql_real_escape_string(htmlentities($body));
mysql_query("INSERT INTO `conversations` (`conversation_subject`) VALUES ('{$subject}')");
$conversation_id = mysql_insert_id();
$sql = "INSERT INTO `conversations_messages` (`conversation_id`, `user_id`, `message_date`, `message_text`)
VALUES ({$conversation_id}, {$_SESSION['user_id']}, UNIX_TIMESTAMP(), '{$body}')";
mysql_query($sql);
$values = array("({$conversation_id}, {$_SESSION['user_id']}, UNIX_TIMESTAMP(), 0)");
foreach ($user_ids as $user_id){
$user_id = (int)$user_id;
$values = array("({$conversation_id}, {$_SESSION['user_id']}, UNIX_TIMESTAMP(), 0)"); }
$sql = "INSERT INTO `conversations_members` (`conversation_id`, `user_id`, `conversation_last_view`, `conversation_deleted`)
VALUES " . implode(", ", $values);
mysql_query($sql);
}
// Checks to see if the given user is a member of the given conversation.
function validate_conversation_id($conversation_id){
$conversation_id = (int)$conversation_id;
$sql = "SELECT COUNT(1)
FROM `conversations_members`
WHERE `conversation_id` = {$conversation_id}
AND `user_id` = {$_SESSION['user_id']}
AND `conversation_deleted` = 0";
$result = mysql_query($sql);
return(mysql_result($result, 0) == 1);
}
// Adds a message to the given conversation.
function add_conversation_message($conversation_id, $text){
$conversation_id = (int)$conversation_id;
$text = mysql_real_escape_string(htmlentities($text));
$sql = "INSERT INTO `conversations_messages` (`conversation_id`, `user_id`, `message_date`, `message_text`)
VALUES ({$conversation_id}, {$_SESSION['user_id']}, UNIX_TIMESTAMP(), '{$text}')";
mysql_query($sql);
mysql_query("UPDATE `conversations_members` SET `conversation_deleted` = 0 where `conversation_id = {$conversation_id}");
}
// Deletes (or marks as deleted) a given conversation.
function delete_conversation($conversation_id){
$conversation_id = (int)$conversation_id;
$sql = "SELECT DISTINCT `conversation_deleted`
FROM `conversations_members`
WHERE `user_id` != {$_SESSION['user_id']}
AND `conversation_id` = {$conversation_id}";
$result = mysql_query($sql);
//if (mysql_num_rows($result) == 1 && mysql_result($result, 0) == 1){
if (mysql_num_rows($result) == 0){
mysql_query("DELETE FROM `conversations` WHERE `conversation_id` = {$conversation_id}");
mysql_query("DELETE FROM `conversations_members` WHERE `conversation_id` = {$conversation_id}");
mysql_query("DELETE FROM `conversations_messages` WHERE `conversation_id` = {$conversation_id}");
}else{
$sql = "UPDATE `conversations_members`
SET `conversation_deleted` = 1
WHERE `conversation_id` = {$conversation_id}
AND `user_id` = {$_SESSION['user_id']}";
mysql_query($sql);
}
}
?>
I have tried echoing the error, $messages (as you can see from the code). In addition, I have echoed the result of the SQL query.
Update: I did the mentioned var_dump and my result was:
Resource id #16array(0) { } Array ( )
Sure it prints Array because that is what $messages is. If you want to print the contents of $messages you can use var_dump or print_r.
Similar reason for $result. $result is a resource type (at least as long as the query is successful). Printing it does not make sense since it is an internal reference. You have to pass it to a function like mysql_fetch_assoc or mysql_fetch_array or similar that can process such a resource.
Regarding your updated question: This output tells you that your array is empty and does not contain any elements. Are you sure your SQL-Query returns any rows?

insert into mysql else update using select?

Can someone please help, I'm trying to make this script select the values from my mysql table where appropriate and update them if they exist, and if they don't exist then to insert them instead.
Can someone show me where I'm going wrong thanks.
<?php
require_once("session.php");
require_once("functions.php");
require('_config/connection.php');
session_start();
include '_config/connection.php';
$height_ft = $_POST['height_ft'];
$height_in = $_POST['height_in'];
$weight_st = $_POST['weight_st'];
$weight_lb = $_POST['weight_lb'];
$result = mysql_query("SELECT height_ft FROM ptb_stats WHERE id=".$_SESSION['user_id']."");
$result2 = mysql_query("SELECT height_in FROM ptb_stats WHERE id=".$_SESSION['user_id']."");
$result3 = mysql_query("SELECT weight_st FROM ptb_stats WHERE id=".$_SESSION['user_id']."");
$result4 = mysql_query("SELECT weight_lb FROM ptb_stats WHERE id=".$_SESSION['user_id']."");
if( !$result ) {
echo "The username you entered does not exist";
} else if( $height_ft != mysql_result( $result, 0 ) ) {
echo "";
$sql = mysql_query("UPDATE ptb_stats SET height_ft='$height_ft' WHERE id=".$_SESSION['user_id']."");
$sql = mysql_query("UPDATE ptb_stats SET height_in='$height_in' WHERE id=".$_SESSION['user_id']."");
$sql = mysql_query("UPDATE ptb_stats SET weight_st='$weight_st' WHERE id=".$_SESSION['user_id']."");
$sql = mysql_query("UPDATE ptb_stats SET weight_lb='$weight_lb' WHERE id=".$_SESSION['user_id']."");
mysql_query("INSERT INTO ptb_stats (user_id, height_ft) VALUES (".$_SESSION['user_id'].", ".$height_ft.")");
mysql_query("INSERT INTO ptb_stats (user_id, height_in) VALUES (".$_SESSION['user_id'].", ".$height_in.")");
mysql_query("INSERT INTO ptb_stats (user_id, weight_st) VALUES (".$_SESSION['user_id'].", ".$weight_st.")");
mysql_query("INSERT INTO ptb_stats (user_id, weight_lb) VALUES (".$_SESSION['user_id'].", ".$weight_lb.")");
}
if( $sql ) {
$_SESSION['edit_done']="<div class=\"infobox-edit-done\"><strong>Thank You -</strong> Your Details were changed.</div>";
header("Location: {$_SERVER['HTTP_REFERER']}");
} else {
$_SESSION['edit_done2']="<div class=\"infobox-edit-done\"><strong>Oooops! -</strong> That didn't work. Try again.</div>";
header("Location: {$_SERVER['HTTP_REFERER']}");
}
?>
There is an option in MySQL for an update or insert using ON DUPLICATE KEY UPDATE which may more concisely solve your question.
http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
For you query would look something like:
$sql=mysql_query("INSERT INTO ptb_stats (user_id, height_ft)
VALUES (".mysql_real_escape_string($_SESSION['user_id']).", "
.mysql_real_escape_string($height_ft).")
ON DUPLICATE KEY UPDATE user_id = ".mysql_real_escape_string($_SESSION['user_id']).");

Categories