i am trying to update my records using UPDATE in php and mysql , the query working but there is not updates at all happened on the database , i have many records for tickets which i need to update there status when the user purchase them , let say the user books 10 tickets i used this syntax
for ($counter = 1; $counter <= $tickets; $counter++) {
echo $eventId;
echo $chooseClass;
echo $chooseUser;
$bookTicket = mysql_query("UPDATE units
SET ticketSold = 'Yes',
userIdFK = '$chooseUser'
WHERE BusinessreservationIdFk = '$eventId'
AND classIDfk ='$choosedClass'"
) or die(mysql_error());
if ($bookTicket)
{
echo "<br/>ticket " . $counter . " done !";
}
else
{
i tried to echo all variables here inside the for loop to make sure this for gets all the variables values , which is working , i have like 1000 tickets already stored on mysql table units which i need to update their status from sold = No to Yes. where is the problem here ?
try building the query separately (e.g. $sql = 'UPDATE ...', so you can do an echo $sql and copy/paste the query and run it manually. Nothing in your code looks wrong, so the values you're passing around must not be correct or the WHERE ... logic isn't proper. So run a sample query manually and see if anything happens then.
However, note that you're doing this inside a for() loop, but aren't using that $counter value anywhere. In effect you're just running the SAME query over and over. Setting ticketSold to Yes $counter times isn't going to make it "more" Yes than if you'd done this update only once.
Related
I am trying to code a user system. I am having an issue with the activation part. I can select and insert data to my table but now I am trying to create an update statement and got stuck.
<?PHP
include "db_settings.php";
$stmt = $dbcon->prepare("UPDATE 'Kullanicilar' SET 'Aktivasyon' = ? WHERE 'KullaniciID'=?");
// execute the query
$stmt->execute(array('1','5'));
// echo a message to say the UPDATE succeeded
echo $stmt->rowCount() . " records UPDATED successfully";
?>
And I am getting error as:
"0 records UPDATED successfully".
This is my table; http://i.imgur.com/PL2eD80.png
I have tried by changing my 'Aktivasyon' type int to char but it also does not work.
EDIT:
I am trying to make this a function;
function dataUpdate($tableName, $updateRow, $updateValue, $conditonRow, $conditionValue)
{
include "db_settings.php";
$q = $dbcon->prepare("UPDATE $tableName SET $updateRow= ? WHERE $conditonRow= ?");
$q->execute(array($updateValue,$conditionValue));
}
I also try this :
...
$q = $dbcon->prepare("UPDATE `$tableName` SET `$updateRow`= ? WHERE `$conditonRow`= ?");
...
How can I make this statement work?
You are using wrong quotes. You are basically saying "update this table, set this string to something when the string KullaniciID equals the string 5" which of course never is true.
You should use backticks ` if you want to specify column names. Then your query would work. Usually you don't even need those, but for some reason MySQL world is always adding them.
So to clarify, this is a string: 'KullaniciID' and this is a column name: `KullaniciID`.
Also you should not send integers as strings. It causes extra conversions or even errors with more strict databases.
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)
I populate a web form with rows of data. Some of the fields I need to be updatable so I put the value into a text field. MySQL query is:
SELECT * FROM results WHERE EventID = %s AND CompNo = %s", GetSQLValueString($colname_rsResults, "int"),GetSQLValueString($colname2_rsResults, "int"));
EventID and CompNo are passed in the URL.
Let's say the result is 50 rows. I want to be able to update the Name field (eg, make correction to the spelling), click a button and have the code update the database with any new values. It doesn't matter that most of the values will not change as this is a very infrequent operation.
I used to be able to do this in ASP but I can't seem to do in PHP.
This is the code I am using and I think it is completely wrong!!
if ((isset($_POST["JM_update"])) && ($_POST["JM_update"] == "form1")) {
$i = 0;
$j = $totalRows_rsResults;
while($i < $j)
$resultID=$_GET['ResultID'];
$vDelete=$_GET['Del'];
if ($vDelete == 1) {
$delSQL = sprintf("DELETE FROM Results WHERE ResultID=$resultID");
mysql_query($delSQL,$connFeisResults);
} else {
$name=$_GET['Name'];
$qual=$_GET['Qual'];
$updateSQL = sprintf("UPDATE results SET Name = ".$name{$i}.", Qual = ".$qual[$i]." WHERE ResultID=$resultID");
mysql_query($updateSQL, $connFeisResults);
$i++;
}
}
There is also a checkbox at the end of each row to check if I need that record deleted. That doesn't work either!!
I am using Dreamweaver CS6 and trying to adapt the update behaviours etc.
Any thoughts? Many thanks in advance.
It looks like you're missing an opening brace after your while statement.
--UPDATED
Also, check your sprintf statements -- they look wrong, and they look like they're writing the raw '$resultID' to the SQL String, instead of the value within it.
See how to do it here: http://www.talkphp.com/general/1062-securing-your-mysql-queries-sprintf.html
i've got a script which is supposed to run through a mysql database and preform a certain 'test'on the cases. Simplified the database contains records which represent trips that have been made by persons. Each record is a singel trip. But I want to use only roundway trips. So I need to search the database and match two trips to each other; the trip to and the trip from a certain location.
The script is working fine. The problem is that the database contains more then 600.000 cases. I know this should be avoided if possible. But for the purpose of this script and the use of the database records later on, everything has to stick together.
Executing the script takes hours right now, when executing on my iMac using MAMP. Off course I made sure that it can use a lot of memory etcetare.
My question is how could I speed things up, what's the best approach to do this?
Here's the script I have right now:
$table = $_GET['table'];
$output = '';
//Select all cases that has not been marked as invalid in previous test
$query = "SELECT persid, ritid, vertpc, aankpc, jaar, maand, dag FROM MON.$table WHERE reasonInvalid != '1' OR reasonInvalid IS NULL";
$result = mysql_query($query)or die($output .= mysql_error());
$totalCountValid = '';
$totalCountInvalid = '';
$totalCount = '';
//For each record:
while($row = mysql_fetch_array($result)){
$totalCount += 1;
//Do another query, get all the rows for this persons ID and that share postal codes. Postal codes revert between the two trips
$persid = $row['persid'];
$ritid = $row['ritid'];
$pcD = $row['vertpc'];
$pcA = $row['aankpc'];
$jaar = $row['jaar'];
$maand = $row['maand'];
$dag = $row['dag'];
$thecountquery = "SELECT * FROM MON.$table WHERE persid=$persid AND vertpc=$pcA AND aankpc=$pcD AND jaar = $jaar AND maand = $maand AND dag = $dag";
$thecount = mysql_num_rows(mysql_query($thecountquery));
if($thecount >= 1){
//No worries, this person ID has multiple trips attached
$totalCountValid += 1;
}else{
//Ow my, the case is invalid!
$totalCountInvalid += 1;
//Call the markInvalid from functions.php
$totalCountValid += 1;
markInvalid($table, '2', 'ritid', $ritid);
}
}
//Echo the result
$output .= 'Total cases: '.$totalCount.'<br>Valid: '.$totalCountValid.'<br>Invalid: '.$totalCountInvalid; echo $output;
Your basic problem is that you are doing the following.
1) Getting all cases that haven't been marked as invalid.
2) Looping through the cases obtained in step 1).
What you can easily do is to combine the queries written for 1) and 2) in a single query and loop over the data. This will speed up the things a bit.
Also bear in mind the following tips.
1) Selecting all columns is not at all a good thing to do. It takes ample amount of time for the data to traverse over the network. I would recommend replacing the wild-card with all columns that you really need.
SELECT * <ALL_COlumns>
2) Use indexes - sparingly, efficiently and appropriately. Understand when to use them and when not to.
3) Use views if you can.
4) Enable MySQL slow query log to understand which queries you need to work on and optimize.
log_slow_queries = /var/log/mysql/mysql-slow.log
long_query_time = 1
log-queries-not-using-indexes
5) Use correct MySQL field types and the storage engine (Very very important)
6) Use EXPLAIN to analyze your query - EXPLAIN is a useful command in MySQL which can provide you some great details about how a query is ran, what index is used, how many rows it needs to check through and if it needs to do file sorts, temporary tables and other nasty things you want to avoid.
Good luck.
I'm having an issue that I can't quite figure out. I have a bit of code that allows a user to pick, let's say, which type of fruit is their favourite. If they've previously selected 'apples' as their favourite and want to change it to 'oranges' - the script performs well.
But if they select 'apples' when they've already selected 'apples' the MYSQL Update call breaks down and returns an error. It's like it won't write over itself with the same data, that the new value has to be unique. I'm at a loss.... Here's the update bit:
// UPDATE THEIR FRUIT SELECTION...
$q = "UPDATE account SET fav_fruit='" . $row['fruit'] . "' WHERE act_id=$act_id LIMIT 1";
$r = #mysqli_query ($dbc, $q);
if (mysqli_affected_rows($dbc) == 1) { // If it ran OK.
echo 'success!';
} else {
echo 'oops!';
}
Again, this works so long as the new selection and what's in the database aren't the same. If they are: I get the oops! error.
Why would you need to update a field to contain a value it already contains?
Regardless, this can be fixed by altering the table structure. You need to remove the unique flag from the fav_fruit column.