Starting mysqli_fetch_array from a specific row - php

I have some records, which I use while($row = $result->fetch_assoc() to iterate on each one of them, then I get some other data from a different table using while($row2 = $result2->fetch_assoc(), that is, iterating also on each one of them, then displaying in a HTML table: part of first table data and part of second table data.
However, when I truncate the first table, and then insert new records, the second query $result2->fetch_assoc(), starts from the beginning of table and iterates X times, which is basically numbers of rows from first table. This is not what I want, I want to remember the last place of iteration from its table (table 2), then, when called again, only iterate the remain rows in the second table, always which is dependent on nth times from first table.
I found an answer in stackoverflow, which you can find it here, however, I didn't understand it correctly: how can you save last LIMIT value, so to start from X id if the $result2->fetch_assoc()is called again?
I thought about storing a counter in a text document (which is incremented by first while loop), then use LIMIT from that certain number, but I don't really get how to get it work.
Edit: here are some additional info:
Table "aplikimet" schema:
Table "aplikimet_2" schema:
$sql = "SELECT id, emri, mbiemri, email, telefoni, vendbanimi, datelindja, mesazhi FROM aplikimet";
$sql2 = "SELECT statusi, uid FROM aplikimet_2";
$result = $conn->query($sql);
$result2 = $conn->query($sql2);
if (($result->num_rows > 0) AND ($result2->num_rows>0)){
(html table and th are here)
while((($row = $result->fetch_assoc()) AND $row2 = $result2->fetch_assoc()){
(html td are here)
Thanks for your help!

every time you call fetch_assoc() an internal pointer is incremented.
after last element the call returns false so your while(...) loop will end.
to reset it you can call
mysqli_data_seek($result, 0);
or
$result->data_seek(0);
see here
IMHO is not a great way to do it.
If you want to loop multiple times the same rowset you can save it in an array after the first complete loop. Then loop with foreach() your array all the times you need (your connection can be already closed at that time)
To limit the number of the rows returned by your query use the SQL LIMIT clause which can have different syntax depending on RDBMS you are using.

Related

Updating a field which the Select query loop is based on

This is a rough example of my mysql query (note: this is inside an other loop that goes through all users):
$query = db.query('SELECT * FROM table WHERE userid = $uid AND reminded = 0');
while ($row = $query->fetch()) {
// send personalized reminder email to the user
db.query('UPDATE table SET reminded = 1 WHERE userid = $uid');
}
The field reminded is set to 1 for all instances for that user.
My question is:
Is the query/while (fetch) already loaded into memory based on the original terms (reminded = 0), or will the remaining while loop behave according to those updates (reminded = 1)?
Let's say the user had 50 rows where reminded is 0, and the query selects those: Are they still existing with the value 0 in the rest of the while loop even though they were all changed to 1 during the loop?
Assuming that the code and SQL you have is only an example (because you should update directly without a php loop).
The fetch on the table rows is executed on the DB row by row.
So, if one or more of these rows are updated in the while loop, in next iterations you will retrive and update (again) the previous updated rows.
I think that you have to be careful "only" if you are updating a field that is part of an index or a field that is used in the SQL to retrieve data (es. a field used in the ORDER BY, etc.).

Mysql with PHP - returning values from a database?

Im following a video tutorial on mysql and php, and a certain line of code has me a bit confused:
<?php
$result = mysql_query("SELECT * FROM subjects", $connection);
if(!$result){
die("Database query failed: " .mysql_error());
}
while($row = mysql_fetch_array($result)){
echo $row["Menu_Name"]." ".$row["position"]."<br/>";
}
?>
I want to really understand what this code is doing, so let me see if i got it straight. Basically, what it does on my screen is return the various items store in my table subjects and displays them in their position. It does this by returning them in two arrays, one is the [menu-name] which stores the text for each item and the other is [position] which stores the order in which they come out. So, my while loop goes through this array and outputs. But that's what I dont get. What does $row do and how does it manage to go though and loop through. I may be way off here and was hoping someone could shed some light on this.
mysql_query sends a MySQL query. mysql_query() sends a unique query (multiple queries are not supported) to the currently active database on the server that's associated with the specified. mysql_query() will also fail and return FALSE if the user does not have permission to access the table(s) referenced by the query.
mysql_fetch_array fetches a result row as an associative array, a numeric array, or both. Returns an array of strings that corresponds to the fetched row, or FALSE if there are no more rows.
One last thing if you want to know what's happening with a function try referring the documentation. It helps most of the time.
According to the question you have asked I guess you should go through the basic MYSQL and PHP lessons.
Those are not two arrays. That is one array which is Multi dimensional
while($row = mysql_fetch_array($result)){
When you run that line of code then it grabs one complete row from the list of your results and assigns it to an array named $row. You can then give your Index names to get data from it just like you wrote
$row["Menu_Name"]
So Menu_Name is an index of an array $row containing some value which came from your database. Since this statement is present in a loop, it will loop through all the rows of your returned result and do the same for each of them
this line is retrieving table records, line by line. This is actually an array representing a table record.
$row = mysql_fetch_array($result)
Now, this array in indexed by the table field names. Because your query is 'select *', it means that its retrieving all fields.
So,
$row["Menu_Name"]
has the value of the field 'Menu_Name' of the table 'subjects', for the current row.
SEE tutorial example http://www.devmanuals.com/tutorials/php/phpmysql/php-mysql-fetch-array-example.html.It may clear your doubt

Can I add a new row to a table if a checkbox is checked using one query rather than nested? PHP, MySQL

After much head-scratching, I've got this query working - but it looks clunky and feels slow when it runs.
I have a table called UserTable which has a field called 'Item' populated if the specific user says 'yes' to that item. I only want to add a row for that item into UserTable in that instance - in other words, I don't want to have lots of user_ID/Item/'no' relationships in the table, only the user_ID/Item/'yes' responses.
I've built some code which shows the user the whole dataset and allows them to change their preference and then press update. When they update, an array called $checkbox is output which includes the item numbers (eg "1","3","6") which they've ticked as 'yes'. If they don't tick anything, $checkbox is set to "".
Here's the relevant code - as I say, it's very clunky, with a WHILE inside a FOREACH as well as two validating IF statements. Can I get rid of one (or both!) of the loops and replace with a SELECT type command?
foreach($checkbox as $value)
{if($value!="") {
$sql= "SELECT count(Item) as row_exists
FROM UserTable
WHERE Item = '$value' and
User_ID = '$current_user_id'";
$result = mysqli_query($mysqli,$sql) or die(mysqli_error($mysqli));
while ($iteminfo = mysqli_fetch_array($result)) {
If ((int)$iteminfo['row_exists']==0) {
$sql = "INSERT INTO UserTable
(User_ID,Item,Date) VALUES
('$current_user_id','$value',now() )";
$add_new_row = mysqli_query($mysqli,$sql) or die(mysqli_error($mysqli));
}
}
}
}
Many thanks in advance.
You can eliminate both if statements:
Filter your checkbox array on != "" and loop over those results. That gets rid of the first if that checks for != "".
Augment your initial query to include row_exists = 0, and iterate over those results. That gets rid of the second if.
In fact, you could probably merge your two sql statements into one composite conditional insertion. You are allowed to do insertions of the form:
INSERT INTO table (SELECT ...)
So you could look at taking your first query and adapting/substituting it for the SELECT... part of the query above, and taking your second insertion and adapting/substituting it in place of the INSERT INTO... above.
So if one user can be associated with multiple items, it seems that you should normalize this and have probably three tables - one for users, one for items, and one many-to-many table relating users to items.

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.

Select nth record from a SQL result set in php

I run a query and get a result set. I need to get the nth record from this result set. Any ideas how I can do this?
I cannot select the nth record from the database directly coz I need to filter it and don't know how many records there are in the result set. So I cannot be certain which number to pass to the mysql_result method i.e.
Based on certain conditions, get a few rows from a table
From these rows, select the nth row (the number n is not fixed. It depends on the number of records returned)
The basic idea is to get all results based on a set condition and get a random result from these.
Any ideas? Thanks.
Your question seems unclear. However here's a guess:
You want to select the record in the middle:
$count = mysql_num_rows($result);
$middle_name = mysql_result($result, intval($count/2), 'name');
Besides that, you can also do that if you have really less records:
$rs = array();
while ($row = mysql_fetch_assoc($result)){
$rs[] = $row;
}
and then you can use $rs[N-1] to reach Nth record.
Read mysql_data_seek from PHP Manual if you will fetch just one record.
The basic idea is to get all results based on a set condition and get a random result from these.
SELECT ... ORDER BY RAND() LIMIT 1
I know this is not best practice, but as the given information is rather sparse, this could be starting point for further reading. And to be honest, in an small enough application, this is often the easiest solution.

Categories