Update mysql without replacing empty fields - php

I'm trying to do an update without replace the empty fields, for examplo, if i have field number 1 and it is empty nothing happens in database but if field number 2 has some content i want it to be updated. the thing happens is when i do it the empty field goes to the database and REPLACE the content of the field for an empty value.
I need an example of how can i do it.
PD: I am using PHP OOP.
This is my query:
$conio = "UPDATE affiliates SET nickname = '$nickname', fullname = '$fullname' , email = '$email', skype = '$skype', country = '$country', address = '$address', city = '$city', zip = '$zip', bankname = '$bankname', bankaccount = '$bankaccount', beneficiary = '$beneficiary', username = '$username', password = '$password', whene = '$whene' WHERE id = '$users'";
mysqli_query($this->link, $conio) or die (mysqli_error($this->link));

Example: If you want to update the input where the value is not null.
<?php
...
$sql = "UPDATE affiliates SET ";
$sql_where = "WHERE id = '$users'";
$sql_set = "";
$firstName = $_POST['firstName'];
if(!empty($firstName))
$sql_set .= "firstName = '$firstName',";
$lastName = $_POST['lastName'];
if(!empty($lastName))
$sql_set .= "lastName = '$lastName',";
and the same thing for all the other inputs ...
...
mysql_query($sql.$sql_set.$sql_where);
Of course there are better ways of writing this code (ex: using for loop on elements of $_POST), but that's the concept, ...

Related

PHP - MYSQLI - UPDATE DATABASE

I want users to UPDATE any field(s) they want in d database - table but I don't want the UPDATE .. SET to erase existing records with empty submission if they submit without changing all the fields.. but changed only the ones they want to..
$sql = "UPDATE table SET username = '$username', email = '$email',
fname = '$fname', lname = '$lname', address = '$address', city = '$city',
country = '$country', phone = '$phone', aboutme = '$aboutme' WHERE email = '$email'";
If the user only updates address and phone then submits his entry.. this instruction erases other fields that is not filled in the form.... I don't want that to happen. Kindly look into this. Thanks
Please I have tried your suggestion but its not working for me.. may I am doing something wrong -- I am new to PHP - Here is my code below:
$sql = "UPDATE user_profile SET ";
if ($username!="")
$sql ."username = '$username',"
if ($fname!="")
$sql ."fname = '$fname',"
if ($lname!="")
$sql ."lname = '$lname',"
if ($address!="")
$sql ."address = '$address',"
if ($city!="")
$sql ."city = '$city',"
if($country!="")
$sql ."country = '$country', "
if($phone!="")
$sql ."phone = '$phone', "
if($aboutme!="")
$sql ."aboutme = '$aboutme' "
$sql ."WHERE email = '$email'";
$query = mysqli_query($database,$sql);
if($query)
{
$message = "<div class=\"btn btn-lg btn-default\"><i class=\"text-success text-center\">Update Successful!</i></div>";
//echo "update successful";
}
You should be using parameters rather than placing user input directly into strings. However, that is good practice and protects against SQL injection and poorly formed parameters.
Doesn't help your problem, though. You need to see if there is a new value, otherwise, use the old one. Assuming the new value is NULL when not present, then use COALESCE(). For example:
SET username = COALESCE($username, username),
. . .
Note: There is no reason to set email in the SET statement because you are using it in the WHERE.

Update table for only one record

I have a question, I want to edit customer information, but I only want to update record of one customer at a time. I tried to add where _SESSION['customerCode'] but it doesn't seem to work.
<?php
$connection =
mysql_connect("com-db-02.student-cit.local", "team16", "DbSLzU")
or die (mysql_error());
$db = mysql_select_db("team16") or die(mysql_error());
$FName = $_POST['fname'];
$LName = $_POST['lname'];
$Email = $_POST['custemail'];
$Address = $_POST['address'];
$Town = $_POST['town'];
$County = $_POST['county'];
$Eircode = $_POST['eircode'];
$Phone = $_POST['phone'];
$query = mysql_query("UPDATE CUSTOMER set custFName = '$FName', custLName = '$LName', custemail = '$Email' where customerCode = "$_SESSION['customerCode']"") or die(mysql_error());
?>
I get an error unexpected '$_SESSION' (T_VARIABLE)
Also is it possible to add not update those fields that are blank, so if customer wants to change their address only, other fields won't get wiped out
You have a mistake on your concatination. Make it like this .$_SESSION['customerCode']
Try the code below.
session_start();
$custCode = $_SESSION['customerCode'];
$query = mysql_query("UPDATE CUSTOMER set custFName = '$FName', custLName = '$LName', custemail = '$Email' where customerCode = ".$custCode) or die(mysql_error())
Also is it possible to add not update those fields that are blank, so
if customer wants to change their address only, other fields won't get
wiped out
This was already been answered here before. Search for MySQL COALESCE
You can check the following:
https://dba.stackexchange.com/a/36748
https://stackoverflow.com/a/15525287/4672534

doing an update or an insert with sql

I have a website for fantasy golf. I use php to read an xml file and update the sql database using the following
foreach($field->field->children() as $player){
$lastname = ($player['last_name']);
$firstname = ($player['first_name']);
$firstname = mysql_real_escape_string($firstname);
$lastname = mysql_real_escape_string($lastname);
$sSQL = "UPDATE `Sheet1` Set InField= 1 WHERE LastName = '$lastname' AND Firstname = '$firstname'";
$result = mysql_query($sSQL, $conn) or die(mysql_error());
This updates the database INFIELD column with the players on the xml file. My question is how would I go about adding that player to the database if he isn't in it already? So almost like doing and if not in the database--insert new record?
any help would be appreciated.
Make sure you have a unique key on (LastName, FirstName), then use:
INSERT INTO Sheet1 (LastName, FirstName, InField)
VALUES ('$lastname', '$firstname', 1)
ON DUPLICATE KEY UPDATE InField = 1
Documentation
I suggest you condition it.
player =mysql_query(select player_in_table from players_table where player_in_table = playerx)
if(mysql_num_row(player) = 1){
//update
} else {
//update
}

Comparing data in database in PHP

What I'm trying to do is saving some data in the database and when user will press "SAVE" button script will compare the data entered by the user with data already present in the database. If the data matches it will show a warning that is "The entered data is already in the database please use search bar to search it." In my case I only want it to check phone number and cnic (cnic = national identity card number). Here is what I am doing.
<?php include_once("config.php"); // mysql_connect and database selection are in this file.
$name = $_POST['name']; // data coming from save_info.php
$gender = $_POST['option']; // data coming from save_info.php
$cnic = $_POST['cnic']; // data coming from save_info.php
$number = $_POST['number']; // data coming from save_info.php
$address = $_POST['address']; // data coming from save_info.php
$info = $_POST['info']; // data coming from save_info.php
$check = "SELECT * FROM info WHERE num = $number AND cnic = $cnic"; // checking data
$cresult = mysql_query($check);
if (mysql_num_rows($cresult)==1) {
echo "The entered phone number/cnic is already in the database, Please use search bar to search it.";
header('refresh:10;url=save_info.php');
}
else
{
$sql = "INSERT INTO info(name, gender, cnic, num, address, info)VALUES('$name', '$gender', '$cnic', '$number', '$address', '$info')";
$result = mysql_query($sql);
mysql_close();
header('Location:saved_info.php');
}
?>
You probably missed the quotes in your query:
$check = "SELECT * FROM info WHERE num = \"$number\" AND cnic = \"$cnic\"";
Since the fields are probably textual (varchar or something like that) you need to tell where the limits of the values you're comparing to are.
Also if you need to skip the saving if any of the values matches you should use OR:
$check = "SELECT * FROM info WHERE num = \"$number\" OR cnic = \"$cnic\"";
Try to add single quotes around your parameters and rewrite the query like this..
$check = "SELECT * FROM `info` WHERE `num` = '$number' OR cnic='$cnic'";
Also, on your if statement.. check like this
if (mysql_num_rows($cresult)>0) {
Also, stop using mysql_* functions as they are deprecated. Switch to MySQLi or PDO instead.

php mysql update query

i have this piece of code that allow user to edit their profile from the form using php and mysql when i echo the submitted or changed value it display the right and the edit value but nothing change in the database can anyone help me to solve this problem
this is the part that i am updating the query
if you need any addition files let me know and thank you
search.php
//submit whatthe user types into the database
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$country = $_POST['country'];
$spec = $_POST['specialization'];
///errroor in updating the dataabse
$edit_query = mysql_query("UPDATE user SET first_name= '$fname', last_name= '$lname', address= '$country', specialization_name= '$spec' WHERE user_name = '$username'") or die(mysql_error());
$username is not defined. As result the query is executed for no database row.
Please use prepared statements instead of sql injectionable mysql_query().
You need to initialise the userName variable.
Try this.....
$edit_query = mysql_query("UPDATE `user` SET first_name= '".$fname."', last_name= '".$lname."', address= '".$country."', specialization_name= '".$spec."' WHERE user_name = '".$username."'") or die(mysql_error());
//Make sure that your $username hold some valid value.
$username is required and your query is vulnerable by sql injection. so use mysql_real_escape_string() function
$fname = mysql_real_escape_string($_POST['fname']);
$lname = mysql_real_escape_string($_POST['lname']);
$country = mysql_real_escape_string($_POST['country']);
$spec = mysql_real_escape_string($_POST['specialization']);
$edit_query = mysql_query("UPDATE user SET first_name= '$fname', last_name= '$lname', address= '$country', specialization_name= '$spec' WHERE user_name = '$username'") or die(mysql_error());

Categories