Multiple queries MySQL PHP - 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.

Related

INSERT INTO SELECT with VALUES in one query

Bit new to MYSQL and PHP - I have the following code that will create a new record in multiple tables that I have setup however I need to merge the following code together somehow as it creates separate rows instead of one record
$sql .=("INSERT INTO orders (customer_id) SELECT customer_id FROM
customer_details;");
foreach($result as $item){
$mysql_desc = $item['product_description'];
$mysql_mode = $item['delivery_mode'];
$mysql_cost = $item['course_cost'];
$sql .=("INSERT INTO orders(product_description, delivery_mode, course_cost) VALUES('$mysql_desc', '$mysql_mode', '$mysql_cost');");
}
The result I'm getting:
Based on your data I assume that you want to insert the customer id and the values from php into the same record. In this case you need to combine them into the same insert ... select ... statement:
$sql .=("INSERT INTO orders(customer_id, product_description, delivery_mode, course_cost) select customer_id, '$mysql_desc', '$mysql_mode', '$mysql_cost' from customer_details;");
Couple of things to note:
This insert ... select ... statement will insert the same records for all customers in the customer details table. I'm not sure if this is your ultimate goal.
Pls consider the advices made in the comments regarding the old mysql API and the use of prepared statements.
To put this more into what I would expect to happen, something along the lines of - prepare statement, then loop through each item and add in new row...
$insert = $connection->prepare("INSERT INTO orders (customer_id,product_description, delivery_mode, course_cost)
VALUES (?,?,?,?)");
foreach($result as $item){
$customerID = 1; // Have to ensure this is what your after
$mysql_desc = $item['product_description'];
$mysql_mode = $item['delivery_mode'];
$mysql_cost = $item['course_cost'];
$insert->execute([customerID,mysql_desc,mysql_mode,mysql_cost]);
}

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

PHP Creating entries in different tables

I'm currently working on a project and stuck with something.
I am looking for a way to join two different tables. When you create an entry in one table, it will automatically create an entry in another table.
For example lets say I am creating new patients for a system. When I input all data in to the form and click submit, all of the data is then stored in the patients table under the unique patient id.
Now where I have created a row for Bob in the patients table, I would like for it to also create a row for Bob in the accounting table. So that the accounting data would be tied with the patient data.
So when I submit for a new patient, I would it to also create a new row in the accounting table that can refer to the patient it's created for.
I am not sure if I made my question clear..
EDIT:
Thanks for all the help! I managed to get it up and working with the following..
<?
session_start();
include "database_connect.inc";
$sql="INSERT into patients SET patient_fname='".addslashes($_POST['fname'])."',
patient_initial='".$_POST['initial']."',
patient_lname='".addslashes($_POST['lname'])."',
address='".addslashes($_POST['address'])."',
city='".addslashes($_POST['city'])."',
state='".$_POST['state']."',
zipcode='".$_POST['zip']."',
phone1label='".$_POST['phone1label']."',
phone1='".$_POST['phone1']."',
phone2label='".$_POST['phone2label']."',
phone2='".$_POST['phone2']."',
phone3label='".$_POST['phone3label']."',
phone3='".$_POST['phone3']."',
phone4label='".$_POST['phone4label']."',
phone4='".$_POST['phone4']."',
dateofinjury='".$_POST['dateofinjury']."',
office_location='".$_POST['officelocation']."',
law_office1='".$_POST['lawoffice1']."',
law_office2='".$_POST['lawoffice2']."',
insurance1='".$_POST['insurance1']."',
pip='".$_POST['pip']."',
claim1='".$_POST['claim1']."',
insurance3='".$_POST['insurance3']."',
claim3='".$_POST['claim3']."'";
$result = mysql_query($sql,$cn);
if (!$result) die("ERROR - Query failed while trying to add a new patient record!<br>".$sql);
$sql="INSERT INTO accounts (patient_id,patient_name,patient_lname) VALUES(LAST_INSERT_ID(),'".$_POST['fname']."','".$_POST['lname']."')";
if (!mysql_query($sql,$cn))
{
die('Error' . mysql_error());
}
header("location:createpatient.php");
?>
Based on your question, I prefer suggest you this concept:
example:
table1 name: patients
table2 name: accounting
indicator:
patient_id in patients table1
accounting_id in accounting table2
then, let's do it!:
<?php
$sql="INSERT INTO patients (patient_fname, ...)
VALUES ('$_POST[patient_fname]','....')";
mysql_query($sql);
if (!mysql_query($sql,$cn))
{
die('Error' . mysql_error());
}
$getIdInTable1 = mysql_query("SELECT LAST_INSERT_ID() AS patient_id
FROM patients");
$setID = mysql_fetch_assoc($getIdInTable1);
$sql="INSERT INTO accounting (patient_id, ....)
VALUES ({$setID['accounting_id']}, '$_POST['patient_id']','....')";
if (!mysql_query($sql,$cn))
{
die('Error' . mysql_error());
}
mysql_close($db_server);
header("location:createpatient.php");
exit();
?>
'Hope this really help you.
At first give it a try, then ask where you get actually stuck.
If i were you, i would try something like this.
BEGIN;
INSERT INTO patients(name,details)
VALUES('test', 'test');
INSERT INTO patient_profiles (patient_id, information)
VALUES(LAST_INSERT_ID(),'something useful');
COMMIT;
Please refer some manual.
it s better than You use a manual progressive max code to join tables instead of id

PHP MySQL INSERT data from another table using the where clause and insert unique values to the same rows

I want to insert data from one table into another where one field equals another in both tables. So far this works. The problem is, I also need to insert additional data into those same rows that is not included on the first table.
//enter rows into database
foreach($_POST['sku'] as $row=>$sku)
{
//this is the data that needs to be added to the table
$item_sku=$sku;
$image="/$item_sku.jpg";
$small_image="/$item_sku.jpg";
$thumbnail="/$item_sku.jpg";
//currently this is what is working to import data from one table to the other
$sql= "INSERT INTO magento_import (sku, description, price)
SELECT PR_SKU, PR_Description, PR_UnitPrice
FROM products
WHERE PR_SKU = '$sku'";
//I need something here to add the above variables to the same row where PR_SKU = '$sku'
if (!mysql_query($sql))
{
die('Error: '.mysql_error());
}
echo "$row record added";
}
The columns for the missing data on magento_table are called 'image', 'small_image', and 'thumbnail'. This is simple a hack to put data from an old product table into a new product table, export as a CSV, and run a profile in Magento. I don't need to worry about SQL injections. It's something I'm running off of a local machine. I'm trying to avoid as much manual data entry as possible while switching products over to a new ecommerce system. Thanks for any help you can give.
Selecting literal values should do what you intend:
$sql= "INSERT INTO magento_import (sku, description, price, image, small_image, thumbnail)
SELECT PR_SKU, PR_Description, PR_UnitPrice, \"$image\", \"$small_image\", \"$thumbnail\"
FROM products
WHERE PR_SKU = '$sku'";
You can use another update statement to do this. I doubt if you can do this with one single query
foreach($_POST['sku'] as $row=>$sku)
{
//this is the data that needs to be added to the table
$item_sku=$sku;
$image="/$item_sku.jpg";
$small_image="/$item_sku.jpg";
$thumbnail="/$item_sku.jpg";
//currently this is what is working to import data from one table to the other
$sql= "INSERT INTO magento_import (sku, description, price)
SELECT PR_SKU, PR_Description, PR_UnitPrice
FROM products
WHERE PR_SKU = '$sku'";
//I need something here to add the above variables to the same row where PR_SKU = '$sku'
if (!mysql_query($sql))
{
die('Error: '.mysql_error());
}else {
$sql = "UPDATE magento_import SET item='$item',image='$image',small_image='$small_image',thumbnail='$thumbnail' WHERE PR_SKU = '$sku'";
echo "$row record added";
}
}
You can just add the variables directly to the query. As long as they are quoted they will work as simple values.
$sql= "INSERT INTO magento_import (sku, description, price, x, y, z)
SELECT PR_SKU, PR_Description, PR_UnitPrice, '$x' AS x, '$y' AS y, '$z' AS z
FROM products
WHERE PR_SKU = '$sku'";

MySQL Update only certain fields in a table

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

Categories