Using Update Query to Copy Column Data - php

I need to copy the value in a column named TEAM from one row into another row. Both rows need to have the same team name. This is my query that doesn't work:
$query = "UPDATE profiles SET team = (SELECT team FROM profiles WHERE id = '$coach_id') WHERE id = '$player_id'";
I have tried removing single quotes, removing "FROM profiles", changing value to table.value, tried to give a newdata.clan alias, and I have even tried changing the values to integers instead of parameters. Nothing works, and this is what I get:
Error: You have an error in your SQL
syntax; check the manual that
corresponds to your MySQL server
version for the right syntax to use
near 'WHERE id = '') WHERE id = ''' at
line 3

$query1 = "SELECT team FROM profiles WHERE id = '$coach_id'";
/* get the value of the first query and assign it to a variable like $team_name */
$query2 = "UPDATE profiles SET team = '$team_name' WHERE id = '$player_id'";

Also, you should surround your PHP variables in curly braces:
$query = "UPDATE profiles SET team = \"(SELECT team FROM profiles WHERE id = '{$coach_id}')\" WHERE id = '{$player_id}'";

From the MySQL manual:
"Currently, you cannot update a table
and select from the same table in a
subquery."
Source: http://dev.mysql.com/doc/refman/5.0/en/update.html
Use the method that FinalForm wrote:
<?
$coach_id = 2;
$player_id = 1;
$query1 = "SELECT team FROM profiles WHERE id = '$coach_id'";
$rs = mysql_query($query1);
if ($row = mysql_fetch_array($rs)) {
$team_name = $row['team'];
$query2 = "UPDATE profiles SET team = '$team_name' WHERE id = '$player_id'";
mysql_query($query2);
// Done, updated if there is an id = 1
} else {
// No id with id = 2
}
?>

Related

SQL Syntax with Updating 2nd table on 1st table insert

I am trying to issue a mysqli_multi_query, in which my querys are named $query & $query2. Query 1 is a seperate table from query 2. This is a sample of how the code syntax looks like:
$query1 = "INSERT INTO invoices (`id`,`c`) VALUES (NULL, '$client_id')";
$query2 = "UPDATE `customers` SET `a` = `$a`,`b` = `$b` WHERE `customers.id` = $client_id";
the invoices.client_id is the same as the customers.id, and I only want to update customers.id that matches the invoice client_id.
For some odd reason, everything is updated fine into my invoices, but not into my customers. Is my syntax correct?
after our discussion in the chat we figured out the following misstakes:
Your code:
$query2 = "UPDATE customers SET alarmcode = $alarmcode, garagecode = $garagecode, gatecode = $gatecode, liason = $liason, lphone = $lphone WHERE customers.id = '$client_id'";
table-def:
So the problem was not correct encapsulating of strings in the sql statement.
corrected statement was:
$query2 = "UPDATE customers SET alarmcode = '$alarmcode', garagecode = '$garagecode', gatecode = '$gatecode', liason = '$liason', lphone = '$lphone' WHERE id = $client_id";

Using MAX() in mySQL query is giving problematic results

I'm trying to make multiple queries in order to find the most recent entry in a database by username.
Here's my code:
<?php
require_once("../includes/db_connection.php");
$userID = $_POST["userID"];
$returnString = array();
// Query the max id value of a given key_id (find the most recent upload)
$query = "SELECT MAX(id) FROM photos WHERE key_id = {$userID}";
$result = mysqli_query($connection, $query);
//additional while loop could go here
//now get the url where from the max id value that we just queried
$query = "SELECT url FROM photos WHERE id = {$urlID}";
$result = mysqli_query($connection, $query);
$returnString['url'] = $urlID;
mysqli_free_result($result);
echo json_encode($returnString);
?>
I think the problem lies in the first query. When I return the result from that, I get:
{"maxID": "current_field":null,"field_count":null,"lengths":null,"num_rows":null,"type":null}
When I create a while loop to capture the array (why I need to do this is beyond me because it will only ever return 1 value):
while($row = mysqli_fetch_assoc($result)) {$returnString[] = $row;}
Then I get this funky result:
[{"MAX(id)":"30"}]
30 is the correct value, but then I don't know how to use that result in my next mySQL query.
**********UPDATE*************
The query :
SELECT url FROM photos WHERE id = (SELECT MAX(id) FROM photos WHERE key_id = {$userID});
Works perfectly when making the query from within mySQL, but doesn't work from my php script. It returns this weird string:
{"url":{"current_field":null,"field_count":null,"lengths":null,"num_rows":null,"type":null}}
Here's the updated script:
require_once("../includes/db_connection.php");
$userID = $_POST["userID"];
$returnString = array();
$query = "SELECT url FROM photos WHERE id = (SELECT MAX(id) FROM photos WHERE key_id = {$userID})";
$result = mysqli_query($connection, $query);
mysqli_free_result($result);
$returnString['url'] = $result;
echo json_encode($returnString);
Unless I'm missing something in the schema that's not apparent from code and comments, you can save yourself a roundtrip by combining your SQL commands.
$query = "SELECT id AS urlID, url FROM photos WHERE id = (SELECT MAX(id) FROM photos WHERE key_id = {$userID})";
Then interface with your results like you normally would.
Updated answer:
$query = "SELECT url FROM photos WHERE id = (SELECT MAX(id) FROM photos WHERE key_id = {$userID})";
$result = mysqli_query($connection, $query);
$row = mysqli_fetch_array($result):
$url = $row['url'];
echo json_encode($url);
mysqli_free_result($result);
I think the real problem is in the loop and use of an array for the results.
You should change to a single query like:
SELECT url, MAX(id) as id FROM photos WHERE key_id = {$userID}
MAX(id) as id returns the aggregate column name as id
You don't need to loop with a while if you are only expecting one row. Just change the while to if to test if any row is returned, and assign the values to single variables:
$id = {$row['id']};
$url = {$row['url']};
The "funky" result is from trying to print the array which is not needed and has stored the column name and value.

MySql Fetch Array manipulation

Ok..I know how to get a data record from a MySql table...and I want to change data in that record and update the table.
My question is...can you actually manipulate that data from the result row, and subsequently use those in the update statement?
For example.
Let's say the table rows have 2 fields: Name, YearlyEarn.
And once a month I want to add that month's income to the YearlyEarn field for each person.
Assume we already did the Select statement for someone who's name is in $CurrentName.
And we then get their record.
$DataRow = mysql_fetch_array($result):
Can you do this:
$DataRow["YearlyEarn"] = $DataRow["YearlyEarn"] + $MonthEarn;
$query = "UPDATE EarnTable SET YearlyEarn = '$DataRow["YearlyEarn"]'
`WHERE Name = '$CurrentName'" ;
$UpdResult = mysql_query($query) or die(mysql_error());
OR.....should I put the data into intermediate fields, manipulate it..and then use those fields in the update statement?
You should use prepared statements, like PDO. The mysql_* is outdated. But if not doing so, you should consider changing your query from:
$query = "UPDATE EarnTable SET YearlyEarn = '$DataRow["YearlyEarn"]'`WHERE Name = '$CurrentName'" ;
to:
$query = "UPDATE EarnTable SET YearlyEarn = `" . $DataRow['YearlyEarn'] . "` WHERE Name = `$CurrentName`" ;
Yes, you can:
UPDATE EarnTable
SET YearlyEarn = YearlyEarn + 123
WHERE Name = 'abc'
You can use:
$query = "UPDATE EarnTable SET YearlyEarn = '$DataRow[YearlyEarn]' WHERE Name = '$CurrentName'" ;
When you're interpolating an array reference, the key is automatically quoted.
or:
$query = "UPDATE EarnTable SET YearlyEarn = '{$DataRow["YearlyEarn"]}' WHERE Name = '$CurrentName'" ;
Inside {...}, you can put any variable expression and it will be evaluated and interpolated.

Update table based on condition (While Loop)

So I am trying to update my table based on a singe parameter:
The dateEntered field must be blank.
And I want to randomly select 50 rows, and update the blank ownerID fields to "Tester"
Here is what I have:
<?php
include("includes/constants.php");
include("includes/opendb.php");
$query = "SELECT * FROM contacts WHERE dateEntered='' ORDER BY RAND() LIMIT 50";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_assoc($result)){
$firstid = $row['id'];
$query2 = mysql_query("UPDATE contacts
SET ownerID = 'Tester'
WHERE id = '$firstid'");
$result2 = mysql_query($query2) or die(mysql_error());
}
?>
It will update a single record, then quit and give me:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '1' at line 1
The first part that selects the records works fine, its query2 that won't update all 50 records, just one. Maybe I am writing this wrong.
mysql_query needs only one time
$query2 = mysql_query("UPDATE contacts
SET ownerID = 'Tester'
WHERE id = '$firstid'");
$result2 = mysql_query($query2) or die(mysql_error());
to
$result2 = mysql_query("UPDATE contacts
SET ownerID = 'Tester'
WHERE id = '$firstid'");
These answers are spot on, so I will only add some additional information, and a suggestion. When you are querying mysql the first time, $query1 is being set to the result resource, which for
$query1 = mysql_query("UPDATE contacts SET ownerID = 'Tester' WHERE id = '$firstid'");
returns a result of 1 (Boolean TRUE), which is why your second query failed, cause "1" isn't a valid mysql query string. As Greg P stated, you can fix your current script by eliminating the secondary mysql query.
However, you could improve the script entirely, and make fewer sql calls, by using this.
<?php
include("includes/constants.php");
include("includes/opendb.php");
$query = "UPDATE contacts SET owenerID='Tester' WHERE dateEntered='' ORDER BY RAND() LIMIT 50";
$result = mysql_query($query) or die(mysql_error());

Can't get SQL Update to work using PHP

I'm trying to get php to update a MySQL table using UPDATE statement but it simply won't work. Here's the code I wrote:
$add = "1";
$counter=mysql_query("SELECT * FROM frases WHERE id = '".$id."'");
while ($ntcounter=mysql_fetch_array($counter)) {
mysql_query("UPDATE frases SET count = '".$ntcounter[count]+$add."' WHERE id = '".$id);
}
As you can see, I am basically trying to update the SQL record to keep track of how many times a specific content ID was visited.
Thanks!
Use an alias in your SQL query (It is not mandatory, but it makes the query much more readable.)
SELECT * as count FROM frases WHERE id = '".$id."'"
And you can now access to your variable
$ntcounter['count']
So the result :
$add = "1";
$id = (int)$id
$counter = mysql_query("SELECT * as count FROM frases WHERE id = '".$id."'");
while ($ntcounter = mysql_fetch_assoc($counter)) {
mysql_query("UPDATE frases SET count = '".($ntcounter['count']+$add)."' WHERE id = '".$id);
}
You don't really need two queries. You should just be able to update like this
mysql_query("UPDATE frases SET `count` = `count` + 1 WHERE id = ".$id);
You didn't close the single quote at the end of the update statement:
mysql_query("UPDATE frases SET count = '".$ntcounter[count]+$add."' WHERE id = '".$id."'")

Categories