mysql update clause is being ignored - php

I have a table with a date, ID1, ID2 score1 and score2. I am trying to update one row through php when the user has entered the specific date and id's in an html form. I have validated all the user entries. When I run my query it updates all rows in the table instead of just one. Here is a snippet of my code:
include('connect.php');
$q = mysqli_query($dbc, "SELECT * from Game");
while ($row =mysqli_fetch_array($q, MYSQLI_ASSOC))
{
mysqli_query($dbc, "UPDATE Game SET score1 ='".$points1."', score2='".$points2."'
WHERE '".$date."' = '".$row['Date']."' AND '".$id."' = '".$row['ID1']."' ");
}
mysqli_close($dbc);

Shouldn't your where clause be:
WHERE Date = '".$row['Date']."' AND ID1 = '".$row['ID1']."' ");
instead of
WHERE '".$date."' = '".$row['Date']."' AND '".$id."' = '".$row['ID1']."' ");
In the latter you - probably by accident - use some variables as field names as well, which might cause some unwanted issues. For example in your case it's likely to cause an identity condition in your where clause, which will result that all of your rows will get updated.

The WHERE clause in your update statement references only literals. There are no column references.
For debugging, I suggest you concatenate your SQL into a string, and echo it out.
$sql = "UPDATE Game SET score1 ='".$points1."', score2='".$points2."'
WHERE '".$date."' = '".$row['Date']."' AND '".$id."' = '".$row['ID1']."' ";
echo $sql;
mysqli_query($dbc, $sql);
With the values of these variables set as shown here:
$date = 'fee'
$row['Date'] = 'fi'
$id = 'fo'
$row['ID1'] = 'fum'
The WHERE clause in the generated UPDATE update statement would look like this:
WHERE 'fee' = 'fi' AND 'fo' = 'fum'
MySQL sees the values enclosed in single quotes as string literals. There's nothing wrong with that in terms of SQL (it's valid syntax) but it's much more likely you want the WHERE clause to be more like this:
WHERE fee = 'fi' AND fo = 'fum'
with fee and fo as references to columns.

Related

How to store a PHP variable from a SQL table INT camp

This is my table:
All I want to do is to obtain the '75' int value from the 'expquim' column to later addition that number into another (75+25) and do an UPDATE to that camp (now it is 100).
Foremost, there are dozens of ways to accomplish what you want to do. If you're querying the table, iterating over results and doing some conditional checks, the following will work for you. This is pseudo code... Check out the function names and what parameters they require. $db is your mysqli connection string. Obviously replace tablename with the name of your table. The query is designed to only select values that are equal to 75. Modify the query to obtain whatever results you want to update.
This should get you close to where you want to be.
$query = "SELECT * FROM tablename WHERE idus='1'";
$result = mysqli_query($db, $query);
while($row = mysqli_fetch_assoc($result)) {
if($row['expquim'] == 75){
$query2 = "UPDATE tablename SET expquim='".$row['expquim']+25."' WHERE idus='".$row['idus']."' LIMIT 1 ";
$result2 = mysqli_query($db,$query2);
}
}

PHP loop through array to update SQL database

I am trying to loop through an array ($lineup_selected) that corresponds to a player row in a database. For each player I would like to execute an UPDATE query to the database that adds the value of $submissions_selected to the total_picks column. I am struggling with the code as it fails to execute the query. Any help please?!
// Select team & formation
$team_selected = "team1";
$lineup_selected = array("player1", "player2", "player3");
$submissions_selected = 4000;
// Loop through and update total_picks for each player in database present in lineup_selected array
$player_picks_query = "SELECT full_name, total_picks FROM table WHERE team=$team_selected";
$result = mysqli_query($conn, $player_picks_query);
while($row = mysqli_fetch_assoc($result)) {
$player = mysql_real_escape_string($row["full_name"]);
$add_player_picks = "UPDATE table
SET total_picks = total_picks + $submissions_selected
WHERE full_name = '$player'";
}
why not:
UPDATE table
SET total_picks = total_picks + $submissions_selected
WHERE team = '$team_selected'
this way you have only one query to execute and let your database do the looping. Else you would first select some records and then have your database update each one of them to update the record.
I assume the fullname is unique. If not, it would mean your version can have the update-query modify multiple records each time and so my approach is invalid
-- and I seem to repeat a lot of the comments when stating to sanitize and escape your input to be save(r).
edit:
combined it should come to:
// set team & formation
$team_selected = "team1";
$lineup_selected = array("player1", "player2", "player3");
$submissions_selected = 4000;
$updatequery = "UPDATE table
SET total_picks = total_picks + ?
WHERE team= ?";
$stmt = mysqli_prepare($updatequery);
mysqli_stmt_bind_param($stmt, "is", $submissions_selected, $team_selected);
/* execute prepared statement */
mysqli_stmt_execute($stmt);
Myself I am more into the pdo approach, but syntax should be like this.
In your select request you have a team that is obviously a String. So, maybe you can try your request like : "SELECT full_name, total_picks FROM table WHERE team='$team_selected'"
I don't know if PHP is smart enough to put the quotes.
I think it will be better if you use only an update statement.
First of all you implode your array
$lineup_selected = array("player1", "player2", "player3");
$players='".implode("','",$lineup_selected )."';
Now you can update the table
$updateStmt="UPDATE table
SET total_picks = total_picks + $submissions_selected
WHERE full_name in (".$players.") and team=".$team_selected.";

Insert into if not exist MySQL

I'm using PostgreSQL to get data and i want to insert it into MySQL. I have a php script which allows me to get the data, check for repeated and then insert it into MySQL DB. Problem is that instead of inserting only the non existing data it inserts one random row and doesn't insert nothing else.
$check_for_episode = mysqli_query($conn, "SELECT DISTINCT house_number,number FROM episode WHERE house_number LIKE '".$house_number."' AND number = ".$episode_id_pg." LIMIT 1");
if (mysqli_fetch_array($check_for_episode)){
}else{
$insert_episode = mysqli_query($conn, "INSERT INTO episode(".$episode_col.")VALUES('".$episode_values."')");
}
the variables $episode_col and $episode_values get data from an array called $episode through implode:
$episode_col = implode(", ", array_keys($episode));
$episode_values = implode("', '", array_values($episode));
This is you code.
IF statements are used for comparisons, yours is just fetching the array and there's no condition inside your IF statement. You need to fix the statements to get the columns and their respective values.
$check_for_episode = mysqli_query($conn, "SELECT DISTINCT house_number,number FROM episode WHERE house_number LIKE '".$house_number."' AND number = ".$episode_id_pg." LIMIT 1");
if (mysqli_fetch_array($check_for_episode)){
}else{
$insert_episode = mysqli_query($conn, "INSERT INTO episode(".$episode_col.")VALUES('".$episode_values."')");
}
You can try to use WHERE EXISTS or WHERE NOT EXISTS too.
SELECT DISTINCT column1 FROM table1
WHERE EXISTS (SELECT * FROM table2
WHERE table2.column1 = table1.column1);
SELECT DISTINCT column1 FROM table1
WHERE NOT EXISTS (SELECT * FROM table2
WHERE table2.column1 = table1.column1);
For more info: https://dev.mysql.com/doc/refman/5.7/en/exists-and-not-exists-subqueries.html

echo updated values instead of old values

How do I echo the latest values in column1? The below code echos the values before the update.
while($line = mysql_fetch_array($result)) {
$Student = $line["calss8"];
$querySf = "SELECT SUM(ABC) AS val1 FROM tbl1 WHERE student = '$Student'";
$resultSf = mysql_query($querySf);
$rSf = mysql_fetch_array($resultSf);
$totalSf = $rSf['val1'];
$totTMonth = $totalSf;
mysql_query("UPDATE tbl4 SET column1 = $totTMonth WHERE student = '$Student' LIMIT 1");
}
echo $line["column1"].",,";
As far as I know, you'll have to make a separate query to see what was just updated. I mean, run your select, perform your update, then do another select. You can get general information like how many rows were updated, but I don't think you can get specific information like the changed values in a column. Phil was right in suggesting that you should just print out the '$totTMonth' value since that is what you are updating your column with. That would be less overhead than doing another query to the database.
I think that problem starts before the code above. This code line will display the select results :echo $line["column1"].",,";. The variable $line is set before the code above. My solution is to do the following:
$result1 = mysql_query("SELECT column1 FROM student ..."); /* I insert the select query here */
While($row= mysql_fetch_array($result)) {
echo $row['column1'].",,";
}

mysql nested subqueries with php

I have two tables. I want to be able to get the orders of each id in the credit table from the orders table code below:
$downlinequery = "SELECT recid, Level, sp1 FROM credit
WHERE sp1 = '$id' or sp2 = '$id' or sp3 = '$id' or sp4 = '$id'
or sp5 = '$id' or sp6 = '$id' or sp7 = '$id' or sp8 = '$id'" ;
$downlineresult = mysql_query($downlinequery) ;
while ($downlinerow = mysql_fetch_array($downlineresult)) {
extract($downlinerow) ;
$orderquery = "SELECT date,cc,cop FROM order WHERE userid='1127'" ;
$orderresult = mysql_query($orderquery) or die("unable to get orders");
while($orderrow = mysql_fetch_array($orderresult)){
extract($orderrow);
echo "$date,$cc,$cop" ;
}
}
but i keep getting the error: unable to get orders
Is it possible to make queries while another is running ?
The error might happend because "ORDER" is a reserved word in MySQL. You should escape it with backticks:
$orderquery = "SELECT date,cc,cop FROM `order` WHERE userid=1127" ;
Same should be for "date", although that's being tolerated (see further down in the same page I linked)
As for your question, of course you can do queries in a loop (although that's not really the best in terms of performance). But if your tables have a foreing key (I'm guessing 'recid' and 'userid') you can build a JOINed query instead
To your actual question:
I don't think the question is right. The first query is not running. It ran and it filled result in $downlineresult (mysql_query) and then, you are just iterating thru the parts of the result (mysql_fetch_array).
It seems you have error in your MySQL query, so you should use:
echo mysql_error();
See the description of the methods you use:
mysql_query
mysql_fetch_array

Categories