I'm using foreach to loop an array and update a MySQL database.
This is my code
foreach($result['getHiscore'] as $highScoreType => $highScoreValues){
$rank = $highScoreValues['rank'];
$lvl = $highScoreValues['lvl'];
$totalXp = $highScoreValues['totalxp'];
mysqli_query($con,"UPDATE Users SET Level("$highScoreType") = $lvl, Xp("$highScoreType") = $totalXp,
WHERE UserID= '1'");
}
i'm trying to conflate the word "level" with the contents of $highScoreType, the column titles in my DB are Leveloverall, Xpoverall, Levelattack, Xpattack and so on so i was planning on keeping the Level/Xp title constant and just changing the key.
This looks fine to me and when i tested the sql with pre-set values it updated fine, however using the variables doesn't update at all. I know that the variables are coming out of the array correctly as when i echo them inline with the foreach they print out in the correct format and order.
Is it my formatting thats the issue or am i doing missing something else?
If you echo the generated SQL query that should help you see any problems in the query.
It looks odd to me: UPDATE Users SET Level("$highScoreType") = $lvl
Shouldn't that just be UPDATE Users SET $highScoreType = $lvl ?
Be aware also that this sort of code is vulnerably to SQL injection attacks so always be wary of what could be in those variables.
To print the query do:
$query = "UPDATE Users SET Level("$highScoreType") = $lvl, Xp("$highScoreType") = $totalXp, WHERE UserID= '1'"
echo $query
mysqli_query($con, $query)
Related
My query is not working when I use the variable in the WHERE clause. I have tried everything. I echo the variable $res, it shows me the perfect value, when I use the variable in the query the query is not fetching anything thus mysqli_num_rows is giving me the zero value, but when I give the value that the variable contains statically the query executes perfectly. I have used the same kind of code many times and it worked perfectly, but now in this part of module it is not working.
Code:
$res = $_GET['res']; // I have tried both post and get
echo $res; //here it echos the value = mahanta
$query = "SELECT * FROM `seller` WHERE `restaurant` = '$res'"; // Here it contains the problem I have tried everything. Note: restaurant name is same as it is in the database $res contains a value and also when I give the value of $res i.e. mahanta in the query it is then working.
$z = mysqli_query($conn, $query);
$row2 = mysqli_fetch_array($z);
echo var_dump($row2); // It is giving me null
$num = mysqli_num_rows($z); // Gives zero
if ($num > 0) {
while ($row2 = mysqli_fetch_array($z)) {
$no = $row2['orders'];
$id = $res . $no;
}
}
else {
echo "none selected";
}
As discussed in the comment. By printing the query var_dump($query), you will get the exact syntax that you are sending to your database to query.
Debugging Tip: You can also test by pasting the var_dump($query) value in your database and you will see the results if your query is okay.
So update your query syntax and print the query will help you.
$query = "SELECT * FROM `seller` WHERE `restaurant` = '$res'";
var_dump($query);
Hope this will help you and for newbies in future, how to test your queries.
Suggestion: Also see how to write a mysql query syntax for better understanding php variables inside mysql query
The problem is the way you're using $res in your query. Use .$res instead. In PHP (native or framework), injecting variables into queries need a proper syntax.
<?php
$userData = array();
while (anything to create a loop) {
$value1 = $result1_from_loop;
$value2 = $result2_from_loop;
$value3 = $result3_from_loop;
$userData[] = '("'.$value1.'", "'.$value2.'", "'.$value3.'")';
} // THIS ENDS THE WHLE OR FOR LOOP
$query = 'INSERT INTO users (data1,data2,data3) VALUES' . implode(',', $userData);
mysql_query($query);
?>
The above code works perfectly for inserting multiple records into table users as seen above and it's very fast as well.
However, I am trying to use the same method to update after going through a loop as before. I have no idea how to achieve this.
I want something like this:
<?php
$userData = array();
while (Loop statement) {
$value1 = $result1_from_loop;
$value2 = $result2_from_loop;
$value3 = $result3_from_loop;
$userData[] = '("'.$value1.'", "'.$value2.'", "'.$value3.'")';
} // This ends the WHLE or FOR loop
$query = 'UPDATE users SET(data1,data2,data3) VALUES' . implode(',',$userData) WHERE data2=$value2
mysql_query($query);
I know the above code is not close to correct, syntax is even wrong. I just pasted it to show the idea of what I want achieved. In the WHERE statement how will data2 get to know the value of each $value2?
UPDATE uses a different format to INSERT. For UPDATE, your code should look something like this:
$query = 'UPDATE users SET data1 = $userData[0], data2 = $userData[1], data3 = $userData[2] WHERE data2=$value2';
Although just as a note, using mysql_query is not advised as it is deprecated (and will be removed altogether in later PHP versions) and your code is vulnerable to SQL injection. At a minimum I'd recommend using mysqli_query instead and looking into using prepared statements.
I have a page that brings up a users information and the fields can be modified and updated through a form. Except I'm having some issues with having my form update the database. When I change the update query by hardcoding it works perfectly fine. Except when I pass the value through POST it doesn't work at all.
if (isset($_POST['new']))
{
$result1 = pg_query($db,
"UPDATE supplies.user SET
id = '$_POST[id_updated]',
name = '$_POST[name_updated]',
department = '$_POST[department_updated]',
email = '$_POST[email_updated]',
access = '$_POST[access_updated]'
where id = '$_POST[id_updated]'");
if (!$result1)
{
echo "Update failed!!";
} else
{
echo "Update successful;";
}
I did a vardump as an example early to see the values coming through and got the appropriate values but I'm surprised that I get an error that the update fails since technically the values are the same just not being hardcoded..
UPDATE supplies.user SET name = 'Drake Bell', department = 'bobdole',
email = 'blah#blah.com', access = 'N' where id = 1
I also based the form on this link here for guidance since I couldn't find much about PostGres Online
Guide
Try dumping the query after the interpolation should have happened and see what query you're sending to postgres.
Better yet, use a prepared statement and you don't have to do variable interpolation at all!
Do not EVER use data coming from external sources to build an SQL query without proper escaping and/or checking. You're opening the door to SQL injections.
You should use PDO, or at the very least pg_query_params instead of pg_query (did you not see the big red box in the manual page of pg_query?):
$result1 = pg_query($db,
"UPDATE supplies.user SET
id = $1,
name = $2,
department = $3,
email = $4,
access = $5
WHERE id = $6",
array(
$_POST[id_updated],
$_POST[name_updated],
$_POST[department_updated],
$_POST[email_updated],
$_POST[access_updated],
$_POST[id_updated]));
Also, when something goes wrong, log the error (pg_last_error()).
By the way, UPDATE whatever SET id = some_id WHERE id = some_id is either not really useful or not what you want to do.
I'm trying to create an update function in PHP but the records don't seem to be changing as per the update. I've created a JSON object to hold the values being passed over to this file and according to the Firebug Lite console I've running these values are outputted just fine so it's prob something wrong with the sql side. Can anyone spot a problem? I'd appreciate the help!
<?php
$var1 = $_REQUEST['action']; // We dont need action for this tutorial, but in a complex code you need a way to determine ajax action nature
$jsonObject = json_decode($_REQUEST['outputJSON']); // Decode JSON object into readable PHP object
$name = $jsonObject->{'name'}; // Get name from object
$desc = $jsonObject->{'desc'}; // Get desc from object
$did = $jsonObject->{'did'};// Get id object
mysql_connect("localhost","root",""); // Conect to mysql, first parameter is location, second is mysql username and a third one is a mysql password
#mysql_select_db("findadeal") or die( "Unable to select database"); // Connect to database called test
$query = "UPDATE deal SET dname = {'$name'}, desc={'$desc'} WHERE dealid = {'$did'}";
$add = mysql_query($query);
$num = mysql_num_rows($add);
if($num != 0) {
echo "true";
} else {
echo "false";
}
?>
I believe you are misusing the curly braces. The single quote should go on the outside of them.:
"UPDATE deal SET dname = {'$name'}, desc={'$desc'} WHERE dealid = {'$did'}"
Becomes
"UPDATE deal SET dname = '{$name}', desc='{$desc}' WHERE dealid = '{$did}'"
On a side note, using any mysql_* functions isn't really good security-wise. I would recommend looking into php's mysqli or pdo extensions.
You need to escape reserved words in MySQL like desc with backticks
UPDATE deal
SET dname = {'$name'}, `desc`= {'$desc'} ....
^----^--------------------------here
you need to use mysql_affected_rows() after update not mysql_num_rows
I'm in a bit of a pickle here, its just that I'm trying to enter some data that I get from users into a table, but for some reason it won't let me insert the data, however I have exactly the same query for another part of the table and that seems to work perfectly fine.
for example when I execute this query, it doesn't work:
$updateibtask2 = "UPDATE ibtask_task2_75beep SET
Trial1_tone_actual= '$taskerror[0]', Trial2_tone_actual= '$taskerror[1]', Trial3_tone_actual= '$taskerror[3]',
Trial4_tone_actual= '$taskerror[4]', Trial5_tone_actual= '$taskerror[5]', Trial6_tone_actual= '$taskerror[6]',
Trial7_tone_actual= '$taskerror[7]', ... WHERE user_id = '$memberid'";
However, when I try this query it works perfectly fine:
$updateibtask2_estimate = "UPDATE ibtask_task2_75beep SET
Trial1_tone_estimate= '$taskerror[0]', Trial2_tone_estimate= '$taskerror[1]', Trial3_tone_estimate= '$taskerror[3]',
Trial4_tone_estimate= '$taskerror[4]', Trial5_tone_estimate= '$taskerror[5]', Trial6_tone_estimate= '$taskerror[6]',
Trial7_tone_estimate= '$taskerror[7]', ... WHERE user_id = '$memberid'";
I'm just wondering where I'm going wrong?
Also if it helps the PHP code that I'm using to run these queries are:
$task2 = array();
$task2 = $_SESSION['task2'];
$task2estimate = array();
$task2estimate = $_SESSION['estimatedpress2'];
$task2actual = array();
$task2actual = $_SESSION['actualpress2'];
addacutalerror_75($memberid, $task2actual);
addestimatederror_75($memberid, $task2estimate);
Also to check whether there was data present for $task2actual I had done an echo ..[0], .. [1].. etc and there was data present in the array.
Updated
For those who are searching for solutions and have the same problem, here's what I did:
function addacutalerror_75($memberid, $task2actual) {
$insertmember = "INSERT INTO ibtask_task2_75beep (user_id, Trial1_tone_actual,
Trial2_tone_actual, Trial3_tone_actual, Trial13_tone_actual,
Trial14_tone_actual, ..., Trial40_notone_actual) VALUES ('$memberid', '$task2actual[0]', '$task2actual[1]', '$task2actual[3]', '$task2actual[18]', '$task2actual[21]', '$task2actual[22]', '..., '$task2actual[24]', '$task2actual[29]', '$task2actual[33]','$task2actual[38]' )";
mysql_query($insertmember) or die(mysql_error());
}
by the way, UPDATE is very different from INSERT.
UPDATE - modify the existing record(s) on the table.
INSERT - adds new record(s) on the table.
Your query is fine but you are doing update. But you want to insert record not to update record right? The query when you insert record looks like this,
$updateibtask2 = "INSERT INTO ibtask_task2_75beep
(Trial1_tone_actual, Trial2_tone_actual,
Trial3_tone_actual,...)
VALUES ('$taskerror[0]', '$taskerror[1]',...)";
and your query is vulnerable with SQL Injection. Please take time to read the article below to protect against SQL injection,
Best way to prevent SQL injection in PHP?