insert into mysql else update using select? - php

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']).");

Related

Isolating the fields that were updated

I'm trying to check whether an existing field have been changed and identify it so i can later add it into a changes table. Any idea on how to do so?
if (isset($_POST['submit']))
{
$sql = "SHOW COLUMNS FROM Employees";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result)){
$tempname = $row['Field'];
$sql2 = "UPDATE Employees SET ".$row['Field']."= '$_POST[$tempname]' WHERE AFNumber='".$_GET["af"]."'";
$result2 = mysqli_query($con,$sql2);
if ($con->query($sql2) === TRUE) {
} else {
echo "Error: " . $sql2 . "<br>" . $con->error;
echo '<script>swal("Error", "Something went wrong '.$con->error.'", "error");</script>';
}
First of all I think you have missed a ".$var." in this line:
$sql2 = "UPDATE Employees SET ".$row['Field']."= '$_POST[$tempname]' WHERE AFNumber='".$_GET["af"]."'";
it should be like this:
$sql2 = "UPDATE Employees SET ".$row['Field']."= '".$_POST[$tempname]."' WHERE AFNumber='".$_GET["af"]."'";
you could do a select query first to diff against the data you want to update
// get the rows that will be changed
$sqlOldData = "SELECT * FROM Employees WHERE AFNumber='".$_GET["af"]."' AND (".$row['Field']." NOT LIKE '".$_POST[$tempname]."')";
and then update the table.
Q: But one question, as for integrating it in the code, any help please, i'm just starting in this area:
$sql3 = "INSERT INTO Changes (Table, AFNumber, Attribute,DateChanged,HRUser,OldValue,NewValue) VALUES ('Employees', '".$_GET["af"]."', '".$row["Field"]."', '".date('dd/m/Y HH:mm:ss')."', '$login_session', '', '$_POST[$tempname]')";
NOTE: First of all you missed again some string breakouts:
'$login_session' --> '".$login_session."'
'$_POST[$tempname]' --> '".$_POST[$tempname]."'
so you get:
$sql3 = "INSERT INTO Changes (Table, AFNumber, Attribute,DateChanged,HRUser,OldValue,NewValue) VALUES ('Employees', '".$_GET["af"]."', '".$row["Field"]."', '".date('dd/m/Y HH:mm:ss')."', '".$login_session."', '', '".$_POST[$tempname]."')";
A: adoption $resultOldData is the result of $sqlOldData
this should work:
while($rowOldData = mysqli_fetch_array($result))
{
$sql3 = "INSERT INTO Changes (Table, AFNumber, Attribute,DateChanged,HRUser,OldValue,NewValue) VALUES ('Employees', '".$_GET["af"]."', '".$row["Field"]."', '".date('dd/m/Y HH:mm:ss')."', '".$login_session."', '".$rowOldData[$row['Field']]."', '".$_POST[$tempname]."')";
mysqli_query($con,$sql3);
}

How to update if exist, otherwise insert in php?

I want to check whether the data is existing or not. If data exists, update the table called "user_star_rate", otherwise insert the data into the table. Inserting is working properly, but the updating is not working.
Here is my code.
$jsqla7 = mysql_query("select * from user_star_rate where product_id='$product_id' and email='$visit_email'") or die(mysql_error());
$jfeta7 = mysql_fetch_assoc($jsqla7);
if($jfeta7 != null) {
$rate = "UPDATE user_star_rate SET rate_value='$rate_value' WHERE product_id='$product_id' and email='$visit_email'" ;
} else {
$rate = "INSERT INTO user_star_rate (email, product_id, rate_value) VALUES ('$visit_email','$product_id','$rate_value')" ;
}
If I understand what your saying, you should really be using a replace into and it would also decrease your code significantly.
Your code would become:
$query = "REPLACE INTO user_star_rate(product_id, email) VALUES('$product_id', '$visit_email')";
mysql_query($query) or die(mysql_error());
If it already exists then it will update it, else it will insert it. You should pay special attention to the docs in regards to foreign keys and auto incrementing ids.
Try this :
$tot = mysql_num_rows($jfeta7);
if($tot > 0){
$rate = "UPDATE user_star_rate SET rate_value='$rate_value' WHERE product_id='$product_id' and email='$visit_email'" ;
} else {
$rate = "INSERT INTO user_star_rate (email, product_id, rate_value) VALUES ('$visit_email','$product_id','$rate_value')" ;
}
Try:
$jsqla7 = mysql_query("select count(*) from user_star_rate where product_id='$product_id' and email='$visit_email'") or die(mysql_error());
$count = mysql_num_rows();
if($count) {
$rate = "UPDATE user_star_rate SET rate_value='$rate_value' WHERE product_id='$product_id' and email='$visit_email'" ;
} else {
$rate = "INSERT INTO user_star_rate (email, product_id, rate_value) VALUES ('$visit_email','$product_id','$rate_value')" ;
}

Inserting/updating data into MySql database using php

I am trying to insert/update the MySql database depending on whether a post already exists on the database (I am checking this with a unique user_id). The following works:
$select_query = "SELECT * ";
$select_query .= "FROM test ";
$select_query .= "WHERE user_id = '$user_id'";
$check_user_id = mysqli_query($connection, $select_query);
$query = "INSERT INTO test (";
$query .= " user_id, name, message";
$query .= ") VALUES (";
$query .= " '{$user_id}', '{$name}', '{$message}'";
$query .= ")";
$result = mysqli_query($connection, $query);
if ($result) {
echo "Success!";
} else {
die("Database query failed. " . mysqli_error($connection));
}
However, when I use the following code with an if/else statement, it does not work anymore, although the console reports "Success!" (meaning $result has a value). Any help would be greatly appreciated. Thanks.
$select_query = "SELECT * ";
$select_query .= "FROM test ";
$select_query .= "WHERE user_id = '$user_id'";
$check_user_id = mysqli_query($connection, $select_query);
if (!$check_user_id) {
$query = "INSERT INTO test (";
$query .= " user_id, name, message";
$query .= ") VALUES (";
$query .= " '{$user_id}', '{$name}', '{$message}'";
$query .= ")";
} else {
$query = "UPDATE test SET ";
$query .= "name = '{$name}', ";
$query .= "message = '{$message}' ";
$query .= "WHERE user_id = '{$user_id}'";
}
$result = mysqli_query($connection, $query);
if ($result) {
echo "Success!";
} else {
die("Database query failed. " . mysqli_error($connection));
}
As i understand your code. you are trying to check if the user_id is existing in your database..
i made a simple code and i think its works for me..
$select_query = mysql_query("SELECT * FROM test WHERE user_id = '$user_id'") or die (mysql_error());
$result = mysql_num_rows($select_query);
if(!$result){
$query = mysql_query("INSERT INTO test (user_id, name, message) VALUES ('$user_id', '$name', '$message')");
if($query){
echo "Success!";
}
else
{
die (mysql_error());
}
}
else{
$query2 = mysql_query("UPDATE test SET name='$name', message='$message' WHERE user_id = '$user_id'")
}
mysql_query returns the operation identifier, not the actual result. This is why $check_user_id is always true, so you are always trying to update (even not existing!) rows.
you have to "read" the result ofmysql_queryby for example using
$check_user_id = mysql_num_rows( mysql_query($connection, $select_query) );
now it returns 0 (false) iff there were no results for q $select_query
This statement is giving you a resource to the result
$check_user_id = mysqli_query($connection, $select_query);
next you are checking for if(!$check_user_id) : this condition evaluates to false because of the negation !. Thus your condition goes to the else part and and never enters the if.
The $result always has value because you are calling it towards the end of the script.
Since you previously know the user_id, and assuming that is a primary key in the table, you could use "ON DUPLICATE KEY UPDATE" clause:
$query = mysql_query("INSERT INTO test (user_id, name, message)
VALUES ('$user_id', '$name', '$message')
ON DUPLICATE KEY
UPDATE name='$name', message='$message';
");
Same result with only one query.
Ref: http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
Use Code for data inserting in mysql.
$query = mysql_query("INSERT INTO test set user_id = '$user_id', name = '$name', message = '$message'");
if($query){
echo "Success!";
}

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