Isolating the fields that were updated - php

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

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

My MySQLi dosen't update only inserts? What's wrong with my script?

$check_verified_user = mysqli_query("SELECT * from user_verified where user_mail = '$payer_email'");
$user_verified = mysqli_fetch_array(mysqli_query($conDB, "SELECT * FROM user_verified where user_mail = '$payer_email'"));
if(mysqli_num_rows($check_verified_user) > 0) {
mysqli_query($conDB, "UPDATE user_verified SET total_paid = total_paid + '$payment_amount' where user_mail = '$payer_email'");
} else {
mysqli_query($conDB, "INSERT into user_verified (user_mail,total_paid) VALUES ('$payer_email', '$payment_amount')");
}
I don't know what's wrong with my script, it checks if the row exists, then if it exists it should update, but instead it inserts another row, which i don't understand...
Give this a try.
$query = "SELECT * FROM user_verified WHERE user_mail = $payer_email";
$check_verified_user = mysqli_query($conDB, $query);
You basically wasn't giving it the database connection, so it was always coming back as not being greater than 0 rows. Personally, I always put my query into its own variable first, and this will ensure that you don't forget params for the mysqli_query() function. It also makes it easier to read, and allows you to use the query in other places if needed.
You can do this method:
$sql = "SELECT * from user_verified where user_mail = '$payer_email'";
$result = mysqli_query($conDB, $sql) or trigger_error(mysqli_error($conDB));
if (mysqli_num_rows($result)) {
$sql = "UPDATE user_verified SET total_paid = total_paid + '$payment_amount' where user_mail = '$payer_email'";
}
else {
$sql = "INSERT into user_verified (user_mail,total_paid) VALUES ('$payer_email', '$payment_amount')";
}
mysqli_free_result($result);
mysqli_query($conDB, $sql) or trigger_error(mysqli_error($conDB));
If your user_mail is a UNIQUE KEY you would be able to use the option ON DUPLICATE KEY UPDATE in the INSERT. You can do everything in just 1 query.
$sql = "INSERT INTO user_verified (user_mail,total_paid) VALUES ('$payer_email',$payment_amount) ON DUPLICATE KEY UPDATE total_paid = total_paid + $payment_amount";
mysqli_query($conDB, $sql);
Check this example of a table using UNIQUE KEY.
http://sqlfiddle.com/#!2/4919e2/1/0

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!";
}

Check to Insert or Update table

See the code below, it check if the data exist in the table, if not exist then insert it or else update the table.
As you can see it look a bit messy - is there anyway to improve the code logic or something smaller? I have a few tables that need doing same thing.
foreach ($sheet as $data) {
// Get Phone ID
$dataPhoneID = mysql_escape_string($data['handset']['phone_id']);
if (isset($stocks[$dataPhoneID])) {
$stockPhone = $stocks[$dataPhoneID ];
$phoneName = mysql_escape_string($stockPhone['description']);
$stock = mysql_escape_string($stockPhone['stock']);
$SQL = "SELECT * FROM phone_affiliate WHERE affiliate_id = 1 AND affiliate_phone_id = '$dataPhoneID'";
$q = mysql_query($SQL);
if (mysql_num_rows($q) == 0) {
$SQLInsert = "INSERT INTO phone (name) VALUE('$phoneName')";
if (mysql_query($SQLInsert)) {
$phone_id = mysql_insert_id();
$SQLInsert = "INSERT INTO phone_affiliate (phone_id, affiliate_id, affiliate_phone_id, stock) ";
$SQLInsert .= "VALUE('$phone_id', '1', '$dataPhoneID', '$stock')";
mysql_query($SQLInsert) or die(mysql_error());
}
} else {
$row = mysql_fetch_assoc($q);
$phone_id = $row['phone_id'];
$SQLUpdate = "UPDATE phone_affiliate set stock = '$stock' WHERE affiliate_id = 1 AND phone_id = $phone_id";
mysql_query($SQLUpdate) or die(mysql_error());
}
// Similar code block above for other tables.
}
}
Note: I am aware about PDO but I don't have time to replace it on existing system.
Use mysql's REPLACE INTO or INSERT... ON DUPLICATE KEY UPDATE. For example:
foreach ($sheet as $data) {
// Get Phone ID
$dataPhoneID = mysql_escape_string($data['handset']['phone_id']);
if (isset($stocks[$dataPhoneID])) {
$stockPhone = $stocks[$dataPhoneID ];
$phoneName = mysql_escape_string($stockPhone['description']);
$stock = mysql_escape_string($stockPhone['stock']);
$SQLInsert = "INSERT INTO phone_affiliate (affiliate_id, affiliate_phone_id, stock) ";
$SQLInsert .= "VALUES ('1', '$dataPhoneID', '$stock') ";
$SQLInsert .= "ON DUPLICATE KEY UPDATE stock = '$stock'";
mysql_query($SQLInsert);
if (mysql_insert_id()) {
$SQLInsert = "INSERT INTO phone (name) VALUE('$phoneName')";
mysql_query($SQLInsert);
$phone_id = mysql_insert_id();
$SQLUpdate = "UPDATE phone_affiliate set phone_id = $phone_id WHERE affiliate_id = 1 AND affiliate_phone_id = $dataPhoneID_id";
}
}
}
Also you can use INSERT IGNORE construction

Categories