Why Output of PHP script and MySQL database data are not same? - php

Please refer to the following image. In this image number (1) is what the field position in my database userdb looks like before I run my code. Number (2) is what change I am expecting in the position field of some rows after I run the code. The value of the position field of second row is primarily 2 what I want to be changed to 3. Similarly, The values of the position field of third, fourth and fifth rows are primarily 3, 4 and 5 respectively what I want to be changed to 4, 5 and 6 respectively. So, I run the following code and in my browser I see what I expect. However, In the database I see wrong data is inserted, like number (3) on the image. Notice that my last expected value of the position field is 6 (for fifth row), but I am getting 6 in all rows!!!
Here is the code I run:
$requestedPosition = 2; $oldPosition = 6;
for($i=$requestedPosition+1; $i <= $oldPosition; $i++){
$query = mysql_query("UPDATE userdb SET position = '$i' WHERE position='{$requestedPosition}' ");
echo 'Old Position: '.$requestedPosition.' is now: '.$i.'<br>';
$requestedPosition++;
}
I think something must be wrong in the mysql query. If I comment out the query I get expected result in browser. However, to insert those data into database I need to run the query but when I do it, I get wrong data inserted in database. I am on windows, running PHP 5.3.13, MySQL 5.5.24.
Most Confusingly, in the for loop, if I change $i=$requestedPosition+1; to $i=$requestedPosition; I get 2,3,4,5 inserted (in 2nd,3rd,4th,5th row respectively) rather than 6,6,6,6. However, I want 3,4,5,6 inserted (in 2nd,3rd,4th,5th row respectively), so I had to use $i=$requestedPosition+1; in for loop, and when I do, Code gets Mad!!! So, do I :( Stuck with this (with bad headache) for last two days!

There's a slight flaw in your logic.
The first time that your loop runs, you're updating one row - you're updating the row with position 2 to be position 3. This is fine.
But the second time the loop runs, you're updating all rows where position is 3 to be position 4 - and there's two of them now, the one from the table, and the one you've just updated. The same happens on the third and fourth iteration.
You can probably do this more elegantly, with one call:
$query = mysql_query("UPDATE userdb SET position = position + 1 WHERE position >={$requestedPosition} AND position <= ${oldPosition}' ");
I've not tested that, but it should at the least give you an idea.

Related

PHP/MySQL Update Query

I have a form with several select and text boxes that gets dynamically generated from a database query.
The number of rows (The form lives in a html table) depends on how many records gets returned from the database.
For instance:
Row 1 - MUStatus(dropdown), IPlan(dropdown), ATT(text box)
Row 2 - MUStatus(dropdown), IPlan(dropdown), ATT(text box)
Row 3 - MUStatus(dropdown), IPlan(dropdown), ATT(text box)
...
...
...
Row 10 - MUStatus(dropdown), IPlan(dropdown), ATT(text box)
Not all rows are going to be updated all the time. Maybe a user gets a 10-row form and updates only one.
My processing script needs to loop through all rows to figure out which one has changed in order to update. This causes
the update query to run 10 times even if the user only updates one row.
How can I get it to update only the number of rows that has been changed on the form?
Currently this is my processing script (not sanatized yet. Just in test mode)
for($i = 0; $i < $_POST['totalRecords']; $i++){
if($_POST['muStatus'] != $providerMUStatusArray[$i] ||
$_POST['att1IncentivePlanDropDown'!= $providerATT1IncentivePlanArray[$i] ||
$_POST['att1AttestationNumber'!= $providerATT1NumberArray[$i]){
UPDATE QUERY GOES HERE
}//END IF
}//END FOR
Any help is appreciated
This is how I would do it: I would add a hidden field in each row called "Updated" with a start value of 0 then use JQuery or just JavaScript to set it to 1 every time a value in that row is changed.
Even better, I would use AJAX to update each row as soon as the user is done editing it.
I would create a session and store the values you expect. Then when the form is submitted you just check to see if the submitted value equals the session saved value. If it does not equal it then process.

using mysqli::fetch_array but only getting 2 of the items?

Ive got a database that Im trying to pull data from (the name of each unique identifier and also how many times it appears in the database) by using this query:
$query = "SELECT Dcol, COUNT(*) FROM dtest GROUP BY Dcol";
and then using this to actually print the data out:
while($result->fetch_row()){
$row = $result->fetch_array(MYSQLI_NUM);
printf("<strong>%s</strong> : <i>%s</i><br />",$row[0],$row[1]);
}
and it works great except for the fact that it only gets 2 of the 4 unique items from the Dcol column. I've tested it by just putting everything that the fetch_row() returns into an array and then using print_r and when I do that it actually shows all 4 with the correct number of times it was used, but when I try to print it using the above statement I get 2 of the 4 (the second and fourth one, if that helps at all)
Can anyone tell me why this would only be giving two of the four unique items?
The 'fetch_row' command is getting the first row - then you ask for the 2nd row with the 'fetch_array' command. So you're only seeing 2 and 4 as a result.

Can you help me understand this php script

I'm a fairly newbie php coder, got this php code in a tutorial to create a randomly generated quote, but I don't fully understand the code
IN particular, I don't understand
a) line 4 -- where does the "rows" come from. Is that a name made up on the spot. Could it just as easily have been called "ferrari"
b) line 9 -- where does "storedtext" come from? is it just made up on the spot?
c) based on the code, do you have an idea what the database is supposed to look like. Would it just be a database called "text" with a table called "quotables" in it?
<?
//
// count() gets the number of rows from database text--
//it assigns a number to rowcount
1 $rowcount = mysql_query("select count() as rows from text");
// don't understand what exactly is happening here, where did "rows" come from
2 while ($row = mysql_fetch_assoc($rowcount))
3 {
4 $max = $row["rows"];
5 }
// Selects an item's index at random
6 $rand = rand(1,$max)-1;
//there is a database table called "quotables?" taking one random row
7 $result = mysql_query("select from quotables limit $rand, 1");
8 $row = mysql_fetch_array($result);
//where does "storedText" come from?????
9 $randomOutput = $row['storedText'];
10 echo '<p>' . $randomOutput . '</p>';
11 ?>
where does the "rows" come from?
It is a name assigned to a value in the SQL query select count() as rows from text.
where does "storedtext" come from?
It seems to be the name of a field in the quotables table.
based on the code, do you have an idea what the database is supposed to look like. Would it just be a database called "text" with a table called "quotables" in it?
No. We cannot say anything about the database name. But this database contains the tables text and quotables where the latter has at least the field storedText.
a) Yes.
b) It must be a column in the database. In line 7, it's pulling all columns in the database, but isn't specific about it's names
c) No, you could print_r($row) to see the table structure though (will print out the array, showing all columns). You should also have access to the db (to make this work, you'll need the db and tables set up), so however you mysql_connect() and mysql_select_db() will tell you the name of the host/db.
A) rows is the alias given to the count() function in the mysql query in line 1. If you changed rows in line one to ferrari then changed rows in line 4 to ferrari then it would still work.
B) stored text comes from the second mysql query on line 7. This will be the name of a column from within that table.
C) Based on the code you have given I can tell you that you have a database which I do not know the name of and that database has two tables one called text and the other quotables I can tell you that quotables has one column called storedText.
a) rows came from sql query "select count() as rows from text"
b) I think there "*" in line 7 because there is no column specified, so if * is there then its selecting all the columns in that table and "storedText" is one column in it
c) text,quotables both are tables
a) rows comes from the SQL query:
$rowcount = mysql_query("select count() as rows from text");
It is the name given to the count() column.
b) storedText is a column in the quotables table, probably with the quote in it.
What the script does is, get a row count from the text table.
Get a random number in the range of 1 to $max.
Get the corresponding quote from the quotables table.
The SQL doesn't tell us anything except that quotables is a table and storedText is a column in it. The names in strings show up in the SELECT statement and come into existance when it completes.
"rows" come from mysql table. This is the name of column. For instance, if you have table with 2 columns, and one of them named like "price" you should use $var['price'] after using mysql_fetch_assoc to use it.
'storedText' the same.
ANS - 1
in while loop, we have assigned value to $row...
ANS - 2
If you have looked code carefully, on line no 8, you have again assigned value to $row.
in line no 8 mysql_fetch_array($result) will fetch all the values for 1st row in array format.
there must be one column in "quotables" table named "storedText" so that it is coming in the $row['storedText'].
you should refer php manual toi understand mysql_fetch_array and mysql_fetch_assoc functions..
refer this url : http://be.php.net/manual/en/book.pdo.php
Line 2 is relevant to a)
while ($row = mysql_fetch_assoc($rowcount))
the while-construct will repeat as long as the expression inside the parentheses evaluates to a true-ish value. In PHP; an assignment is also an expression, which evaluates to the value being assigned, i.e. $row. Before each iteration, the function is executed and tries to retrieve the next row from the database. When it fails, it will return false instead of a row, which then in turn make the loop end, because the assignment-expression will evaluate to false, which is the terminating condition for the while-statement.
b) line 9 -- where does "storedtext" come from? is it just made up on the spot?
It comes from a randomly fetched result from the database. It's the value of one column.
c) based on the code, do you have an idea what the database is supposed to look like. Would it just be a database called "text" with a table called "quotables" in it?
We only know that the database has at least two tables text and quotables, the latter of which has at least one column storedText.
What it does
It tries fetching a random quote. However, the logic is not sound and will most likely not work in all instances.
Why is it wrong?
Basically, it assumed that for each row in text, there is exactly one entry in quoteables. If that was so, you would not need two tables in the first place. Because of this, I assume that quoteables can contain any number of rows, possibly even less, in which case you would sometimes not get a single result from the query. This would have your query fail and your script, because you try to access "false["storedText"] so to speak.
A
$rowcount = mysql_query("select count() as rows from text");
// the $rowcount is an array, the lines below get the values (that actually is just one)
// and put into $max variable
while ($row = mysql_fetch_assoc($rowcount))
{
$max = $row["rows"];
}
B
//get the text from database based on randon limit offet
$result = mysql_query("select from quotables limit $rand, 1");
//put the value returned into $row variable
$row = mysql_fetch_array($result);
//get the storedText (that is a table column name), and put the value into $randomOutput
$randomOutput = $row['storedText'];
C:
Based on code I can't afirm what is the database model.

MySQL query in PHP gives obvious wrong result

I'm using PHP and PHPMyAdmin to create a small profile site.
I'm giving members an ID number, based on which is the biggest number currently in the database, +1
I did 25 tests before I got the PHP script where I wanted it to be.
I then deleted those 25 entries using PHPMyAdmin.
But now, when my PHP code does this:
function getLatestID() {
$query = "SELECT max(member_id) FROM members";
$result = #mysql_query($query) or showError("unable to query database for user information");
if (!($record = mysql_fetch_array($result))) return null;
return $record[0];
}
I get the wrong number.
Test scenario: the database table holds 3 entries, with ID's 1, 2 and 3.
I start a debugging session and put a breakpoint on the return $record[0].
I check its contents and instead of 3, which is the biggest number, it's 28.
As in 25+3=28, the 25 entries that I allready deleted...
Does anybody know what's causing this and how I can fix it?
It's probably because you have auto_increment set and the query is returning the highest id. When you deleted the other records, you probably didn't reset the auto increment count.
If you're using auto_increment in MySQL then deleting records won't decrease the next value.
You can empty a table with TRUNCATE TABLE mytable - this will reset the value.
You can also change value that auto-increment thinks is the next value to allocate:
ALTER TABLE members AUTO_INCREMENT = 3;
Note that if you put in a value that is less than the current max value in the auto-increment column, it'll change the value to that MAX+1. To see what the current next value is set to, do this:
SHOW CREATE TABLE members;
At the end of the table definition, it'll show "AUTO_INCREMENT = 26" or whatever it's current value is.

How can I get every n rows in MySQL?

I have a table which contains data recorded every minute, so I have a row for each minute. When returning the data for processing, this accuracy is required for the last 6 hours but after that, a lower level of accuracy is sufficient, e.g. every 5 minutes.
I can return all the data into an array and then remove all but every 5th element but that requires all data to returned by MySQL and then read into the array first - quite a lot of data.
How can I return every nth row in MySQL? I have read this blog post which suggests using primaryKey % 5 = 0 where primaryKey is auto_increment but this
a) doesn't use indexes
b) will only return primaryKey values which are divisible by 5 and in the case of deletions, may not actually be every 5th row
Can this be done just within the SQL query or will it require looping row by row through the result set using cursors?
I am using MySQLi in PHP to connect to the DB.
The list of timestamps every 5 minutes:
SELECT
MIN(logtimestamp) AS first_of_five_minutes
FROM tLog
GROUP BY
DATE(logtimestamp),
HOUR(logtimestamp),
MINUTE(logtimestamp) - (MINUTE(logtimestamp) % 5)
Now, you can use this as a sub-select to get the requested log entries by joining logtimestamps to first_of_five_minutes on the . Of course, additional WHERE-clauses have to be replicated inside and outside so you get the "right" timestamps.
Also, note that this returns the first timestamp in every five-minute interval, wheras solutions directly using minutes%5 = 0 only return logentries which are actually on multiples of :05, which may fail if you have delays in recording logs or similar.
completely untested but this might work
SELECT Row, col_a
FROM (SELECT #row := #row + 1 AS Row, col1 AS col_a FROM table1) As derived1
WHERE Row%5 = 0;

Categories