MySQL Update only certain fields in a table - php

I have some insurance information in a website, and I'd like to only edit certain fields the user wants to change like for example:
user, id, phone, address, city
and the user wants to change his city and phone...do i have to make a query for each specific case or is there a code that can help me retrieve the key(phone) and value (9397171602)??
to then send it in a query

Basic update would take the form of:
UPDATE table_name SET column_1 = value_1, column_2 = value_2 WHERE column_3 = value_3
Where col1, col2 would be your city and phone, and col3 would be the user id. Check out the MySQL website http://dev.mysql.com/doc/refman/5.0/en/update.html for more info

There are number of ways to update a record safely. Conside the following pseudo code + php program.
class Example
{
function UpdateRecord($editedRecord)
{
//Fetch existing record from the database
$originalRecord=DB::fetchExample($editedRecord->getId())
//validate each edited field and it is valid then assign its value
//to the originalRecord's field
if(IsValid($editedRecord->getName())
{
$originalRecord->setName($editedRecord->getName());
}
.....
//update the record.
$originalRecord->Update();
}
}

Just add some sql to it:
$sql = "UPDATE example SET col_1 = val_1, col_9 = val_9 WHERE col_7 = val_7";
mysql_query($sql);
Then replace the columns and values with you stuff. For further info: PHP MySql Update

Related

How to display both old and new values of particular column in sql on html using php?

Let us assume there is a form which has a text field and a submit button.
Every time I type a text and submit it should be stored in the database and displayed in a table.
Additionally, when I again submit the form the old text in SQL column value should be overwritten with this new value and both values should be displayed in table rows.
So every time I do this I want old data and new data to be appended to table rows.
How to achieve this??
Instead of overwriting the data, why not create a new entry and mark it as active, such that to get the latest data using sql, you order by primary key desc limit 1. If you need the old data you ust get the previous entry.
We have very few information, but here is some idea to achieve it :
1/ Add an last field in your table and update it each time you add a new data, then when you display it just get all data and check the last field to see which one is the last :
So imagine this table :
Table data
===============================
id_data | id_user | data | last
When you display it for your user :
select * from data where id_user = :id_user order by last desc;
This way you will get the last one with last = 1 (true) first then the other.
And when you submit a new data :
// you update all old data as "old"
update data set last = 0 where id_user = :id_user;
// you create a new data
insert into data (id_user, data, last) values (:id_user, :data, 1);
2/ Add a field date so you know wich one are older than other
Table data
==================================
id_data | id_user | data | created
When you display it for your user :
select * from data where id_user = :id_user order by created desc;
This way you will get the data order by the created date with the last one first.
And when you submit a new data :
// you create a new data with the current date
insert into data (id_user, data, created) values (:id_user, :data, NOW());
This solution is better I think so you can have some "historic" of each data.
Is it what you are looking for?
why not just append it with a pipe character like so... "|entry_data" then just explode it when you need it.
var data_array = explode("|",data);
print_r(data_array);
If you want to show all changes only for some users then better to save you last value in main table and create new history table for changes.
table_history
id | id_row | field | before | after
In this case you can without additional query show last value for some users and all data for others.
In this structure you also can save multiple fields data if you need.
And believe me, saving previous value in your table will make you life is easy in future.
In given below code i update field with new one insert data and also append your new data with old I hope this help you
Form from which you insert and update data
if(isset($_POST['submit']) && $_POST['submit']){
$text_field = $_POST['text_field'];
$query ="SELECT * FROM `table_name`"; //replace with your table name
$run=mysqli_query($conn,$query);
$result = mysqli_fetch_row($run);
$data = $result[1];
if(count($result)){
$last_string = $data.','.$text_field;
$update= "UPDATE `table_name` SET `text`='".$last_string."'";
mysqli_query($conn,$update);
}else{
$query = "INSERT INTO `table_name`(`text`) VALUES ('".$text_field."')";
mysqli_query($conn,$query);
}
}
?>
<form action="" method="POST">
<input type="text" name="text_field">
<input type="submit" name="submit">
</form>
view of data which is inserted
<?php
$query ="SELECT * FROM `table_name`";
$run=mysqli_query($conn,$query);
$result = mysqli_fetch_row($run);
if(isset($result) && count($result)){
echo "<p>$result[1]</p>";
}

Inserting data into multiple tables not functioning correctly

I have the following two tables
Table player:
player_id (int)(primary)
player_name (varchar)
player_report_count (int)
Table report:
report_id (int)(primary)
player_id
report_description
report_location
Firstly I ask the user for the player_name and insert it into the player database. From here the player is given an id.
Then I tried to grab the value of the players report count and increment the current value by one (which isn't working).
This is followed by grabbing the playerId from the player table and then inserting into the corresponding column from the report table (also does not work).
When I insert some values into the database, the names, description and report are added to the database however the playerID remains at 0 for all entries and the player_report_count remains at a consistent 0.
What is the correct way to make these two features function? And also is there a more efficient way of doing this?
<?php
$records = array();
if(!empty($_POST)){
if(isset($_POST['player_name'],
$_POST['report_description'],
$_POST['report_location'])){
$player_name = trim($_POST['player_name']);
$report_description = trim($_POST['report_description']);
$report_location = trim($_POST['report_location']);
if(!empty($player_name) && !empty($report_description) && !empty($report_location)){
$insertPlayer = $db->prepare("
INSERT INTO player (player_name)
VALUES (?)
");
$insertPlayer->bind_param('s', $player_name);
$reportCount = $db->query("
UPDATE player
SET player_report_count = player_report_count + 1
WHERE
player_name = $player_name
");
$getPlayerId = $db->query("
SELECT player_id
FROM player
WHERE player_name = $player_name
");
$insertReport = $db->prepare("
INSERT INTO report (player_id, report_description, report_location)
VALUES (?, ?, ?)
");
$insertReport->bind_param('iss', $getPlayerId, $report_description, $report_location);
if($insertPlayer->execute()
&& $insertReport->execute()
){
header('Location: insert.php');
die();
}
}
}
Main issue here is you are getting player details before inserting it. $getPlayerId will return empty result always.
Please follow the order as follows.
Insert player details in to player table and get payerid with mysql_insert_id. After binding you need to execute to insert details to the table.
Then bind and execute insert report .
Then update the player table by incrementing report count with playerid which you got in step 1.
Note : use transactions when inserting multiple table. This will help you to rollback if any insert fails.
MySQL Query will return result object. Refer it from here https://stackoverflow.com/a/13791544/3045153
I hope it will help you
If you need to catch the ID of the last insterted player, This is the function you need if you're using PDO or if it's a custom Mysql Class, you need the return value of mysql_insert_id() (or mysqli_insert_id()) and then directly use it in the next INSERT INTO statement

Selecting multiple data from a table and inserting into another table using PHP form

I've created a form that submits data into multiple tables. My fields are First Name, Last Name, Email, City/Region/Country and they're all inserted into 3 different tables (User, Email, Location).
The data goes into User and Email just fine, but I'm confused about what to do with Location.
I have 3 separate tables for Location (City, Region, Country). What I want to do is insert CityID, RegionID, and CountryID into the Location table. I have the City/Region/Country field set up so it autocompletes based on the city like this:
My Cities table has all the necessary info (CityID, RegionID, CountryID). How can I pull that data from the Cities table and insert it into my Location table?
Here's part of my code. I'm very very new to PHP and MySQL, so I apologize for the sloppiness of this. The first part of the code works, but the 2nd part doesn't (inserting data into the Location table).
//Insert static values into people table
$sql_user = sprintf("INSERT INTO User (FirstName, LastName,) VALUES ('%s','%s')",
mysql_real_escape_string($_POST['FirstName']),
mysql_real_escape_string($_POST['LastName']),
$result_user = $db->query($sql_user);
//get last inserted userid
$inserted_user_id = $db->last_insert_id();
//Insert values into location table
$sql_city = sprintf("INSERT INTO Location (UserID, CityID, RegionID, CountryID)
VALUES ('$inserted_user_id',(SELECT CityID, RegionID, CountryID, FROM Cities))");
$result_city = $db->query($sql_city);
I figure maybe I need to have "WHERE..." after FROM Cities, but I don't know what my condition would be.
That condition is up to you. If you're taking the value from the input box, it looks like you need to figure out the best way to read the location from the input field. Taking it as is you might want to first break the input into an array:
$location = explode(',',$_POST['location'])
$city = $location[0];
$region = $location[1];
$country = $location[2];
Now in your query -
"...WHERE city_name = '{$city}' AND region_name = '{$region_name}' AND country_name = '{$country}'";
*EDIT
To be more detailed, you need to setup a separate query to get the location by using SQL Joins. Your join combined with the WHERE constraints should return the city you are looking for. So here:
"SELECT Cities.CityID,Cities.RegionID,Cities.CountryID FROM Cities JOIN (Regions,Countries) ON Cities.RegionID = Regions.RegionID AND Cities.CountryID = Countries.CountryID WHERE Cities.CityName = '{city}' AND Regions.RegionName = '{$region}' AND Countries.CountryName = '{$country}' LIMIT 1"
**UPDATE
This is pretty basic stuff that you can get by looking at the PHP manual on MySQL.
http://php.net/manual/en/function.mysql-query.php
Since you're new, I will grant you a pass.
After you run your this query:
$location_result = mysql_query("SELECT Cities.CityID,Cities.RegionID,Cities.CountryID FROM Cities JOIN (Regions,Countries) ON Cities.RegionID = Regions.RegionID AND Cities.CountryID = Countries.CountryID WHERE Cities.CityName = '{$city}' AND Regions.RegionName = '{$region}' AND Countries.CountryName = '{$country}' LIMIT 1");
You need to access the result. So:
while ($row = mysql_fetch_assoc($location_result)) {
$cityID = $location_result['CityID'];
//etc... for each associative column
}
And then in your insert query, insert the $cityID variable for CityID column, etc...

Multiple queries MySQL PHP

Is there is proper way to do this. I want to calculate the average rating for a table and update the result in another table simultaneously. Im new to PHP and MYSQL and I would appreciate any help
$query=mysql_query("INSERT INTO review (username, restaurant, rating, review) VALUES ('$username','$restaurant','$rating','$review')");
if($query)
{
$avg_query="SELECT ROUND(AVG(rating),0) FROM review WHERE name =\"$restaurant\"";
$avg_result=mysql_query($avg_query);
$avg_row=mysql_fetch_array($avg_result);
$rating=$row['ROUND(AVG(rating),0)'];
if($avg_result)
{
$update_query= "UPDATE restaurant SET rating=\"$rating\" WHERE name =\"$restaurant\"";
$update_result=mysql_query($update_query);
}
}
else
{
}
Thanks!
UPDATE restaurant
SET rating= (SELECT ROUND(AVG(rating),0) FROM review WHERE name ='$restaurant')
WHERE name ='$restaurant'
I would combine the two into one like this:
$query=mysql_query("INSERT INTO review (username, restaurant, rating, review) VALUES ('$username','$restaurant','$rating','$review')");
if($query)
{
$avg_query="UPDATE restaurant a SET rating=(SELECT ROUND(AVG(rating),0) FROM review WHERE name =a.name) WHERE name ='".$restaurant."'";
$avg_result=mysql_query($avg_query);
}
else
{
}
Having said that, you should move over to either PDO or mysqli as the mysql_* functions are depreciated.
Another option is to use a mysql trigger. For example (don't hold me to the syntax):
CREATE TRIGGER after_insert_review
AFTER INSERT ON review
FOR EACH ROW
BEGIN
UPDATE restaurant
SET rating = (SELECT ROUND(AVG(rating),0) FROM review WHERE name = NEW.restaurant)
WHERE name = NEW.restaurant;
END
Again as mentioned by others use PDO or MySQLi.

How to ensure that MySQL rows are unique?

I am trying to insert a row into a MySQL table, with the condition that the row itself has to be unique.
So for example, the row would have id, name and address, but we can't have an insert with duplicate name and address.
I tried doing a select before inserting, to make sure I don't find the result, but it doesn't seem to be working.
I am currently trying to do this before inserting:
SELECT * FROM locations WHERE cityId = $cityId AND countyId = $countyId AND stateId = $stateId AND countryId = $countyId AND district = $district;
EDIT:
All those fields are allowed to duplicate, they just can't duplicate all at the same time.
The cleanest solution would be to put a UNIQUE constraint on cityId, countyId, stateId, countryId, districtId and then check whether the insert statement was successful.
To quickly test this:
ALTER TABLE your_table_here ADD UNIQUE INDEX(cityId, stateId, countryId, countyId, districtId);
And rerun the insert query. If it encounters a duplicate it will fail, which you will be able to handle in your application.
Assuming you already have a unique index set on the table you can use:
INSERT IGNORE INTO locations SET cityId = $cityId, countyId = $countyId, stateId = $stateId, countryId = $countyId, district = $district;
with such constraints, you should have made the name and address columns as composite primary key..
I think I have a better solution. First check the database and check if the IP and name exists by using:
$check = mysqli_num_rows(mysqli_query($conn, 'SELECT FROM tablename WHERE name="'.$_POST['name'].'"'));
if($check = 0) //Checks if the name does not exist
{
// Your code...
}
else
{
// Error to tell the user the name already exists....
}

Categories