I'm writing an accounting system with PHP and MySQL and using PDO for working with database. In the payment page, I must have 2 drop down lists from defined accounts.
At the first, I've used a simple query to fetch all records for accounts.
$sql = "SELECT id,title FROM tbl_accounts WHERE uid = ? ORDER BY title";
$q = $db->prepare($sql);
$q->execute(array($uid));
I have put fetched rows in a drop down list and everything was ok.
<select name="account_id2" class="medium" id="account_id2">
<option value="null">---</option>
<?php
while ($r = $q->fetch()) {
echo '<option value="'.$r['id'].'">'.$r['title'].'</option>';
}
?>
</select>
But when I wanted to make second drop down list using fetched records, nothing have been shown. So I thought I had to create another query for it. I did it and second one made correctly.
But my question is: Can not we use fetched data more than 1 time ? If I needed 3rd drop down, I had to write another query?
Depending on your conditional loop, you may need to reset the array pointer using reset().
Update:
To reset a result set you can use data_seek() or built a separate array as noted in the other answers.
Save the fetched results to an array using $r = $q->fetchAll() then loop through $r instead of fetching while you're looping.
Why not save the data to an array the first time you use it, so you don't have to bother your Database again for the same data.
Related
Basically I have coded a PHP script to pull information from a JSON file and store it all in one column inside of my MySQL database, here is the format upon which I am storing the data.
(37.50!03:37:42pm PST)
So i basically have multiple entries of similar results stored inside brackets inside of one column.
Now i want limit the results displayed when i pull that information back from the database and display it on my webpage and i cant figure out how? Is there a simple way?
I have tried using LIMIT in my SQL statement but to my understanding(maybe i am wrong) that is used for limiting the number of rows returned and not used for one unique column.
Thank you for your time.
Honestly, it might be easier to accomplish this using PHP. You haven't posted the details of what the multiple data looks like but guessing it is something like this '(37.50!03:37:42pm PST),(37.50!03:37:42pm PST),(37.50!03:37:42pm PST)'.
When fetching the data you split the data and turn it into an array and with preg_split you can have it only return you a limited number of the split array (in the example it uses 50). Post a comment if this doesn't work or if you are able to clarify the format of what multiple entries looks like in the field.
Example:
$rs = mysqli_query($conn, "SELECT yourColumn FROM your_table order by write_here_your_dec_name desc, your_desc_name");
while ($row=mysqli_fetch_assoc($rs)) {
$parts = preg_split('~,~', $row['yourColumn'], 50, PREG_SPLIT_NO_EMPTY);
foreach ($parts as $part ) {
echo "$part<br>";
}
}
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
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.
I'm learning currently php/mysql and I'm confused about this bit.
After some heads scratching I have figured out that mysql_fetch_array remembers which row it last accessed and accesses the next one. (I was originally trying to work out how the code was communicating this to it in example code)
so for database:
parent | job
-------+-------------
mom | receptionist
-------+-------------
dad | taxi driver
the code
mysql_fetch_array($result)[job]
returns 'receptionist' the first time and 'taxi driver' the second.
Where/how is it keeping track of this?
What happens if I don't want to access them in order?
thanks
internal implementation in PHP. Don't try to figure it out ;)
if you want a different order, then specify it in your database query.
Where/how is it keeping track of this?
The mySQL server has an internal result pointer. In some databases / wrappers / libraries you can rewind that pointer, but as far as I know, this is not possible in the mysql_* library of functions.
What happens if I don't want to access them in order?
You have to access them in some order. The only alternative to that is to fetch all rows into an array: Then you can access each row randomly.
If you want to change the order of records, do that in the query using the ORDER clause.
Some database wrappers like PDO have a fetchAll() method that does exactly that. For large result sets, this can be memory intensive and break the script's memory limit, which is why it's usually not done this way.
There is another way to attack this question.
If you want to know how YOU TOO can make functions that do what this one does. Here is how:
<?php
function count_off()
{
static $count = 1;
echo $count++;
}
count_off();
count_off();
count_off();
count_off();
count_off();
?>
the above will output 12345
I should mention. You shouldn't do this without a very good reason. It is SUPER hard to trace when debugging.
If you want to access them in a different order, use an ORDER BY clause in your SQL to change the order that the results are retrieved from the database.
The result of mysql_fetch_array is always the next result/row of the query (first the first row off course)
Intern it will keep a pointer how for it has fetched.
If you want to get them in an alternate order, you have to define it in the query.
Like said the result will always be in the order specified by the query (implicit or explicit)
If you wrote typical looking code like this:
$result = mysql_query("SELECT parent, job FROM table");
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo $row['parent'] . ' - ' . $row['job'];
}
Each time mysql_fetch_array() is called, if there is another row in the result, it will return the row as an associative array into the $row variable. Otherwise, it will return false, and the execution of the while loop will end.
Also, because you didn't specify an ORDER BY clause, it defaults to returning rows in the order they were inserted into the table.
The mysql_fetch_array() function grabs one row from the database, in the order that MySQL returns it from the query you gave.
To obtain all the rows, you can put the function in a loop.
while($row = mysql_fetch_array($result)) {
echo $row["job"];
}
This will output:
receptionist
taxi driver
You can change the order by using the sql term order by, which can alphabetically or numerically order your results by a certain column
select * from parent order by job
The above query will order the results alphabetically by the parent job field (results closer to A will come first in the mysql_fetch_*
I have a friend who's using FluxBB and he has just installed a modification for this forum software. The viewtopic.php file has a while-loop which does a mysql_fetch_assoc() on a result object. Inside of this loop there's a second mysql_fetch_assoc() on a second result object.
The reason for the nested while loop is that there are many posts, and each posts HasMany thank-you's.
Here's some code to better illustrate what I mean:
$result = mysql_query("some-query");
while($cur_post = mysql_fetch_assoc($result)) {
// For every post, execute this second query
$secondResult = mysql_query("some-query that uses the $cur_post id");
while($thank_you = mysql_fetch_assoc($secondResult)) {
// Display the thank_you
}
}
The problem is that the outer-most while loop stops after just one iteration when using the second mysql_query. It does work if the first query is run again, which is a ridiculously dirty hack that works fine with OFFSET.
To me it seems that when the second mysql query is run, whatever $result is pointing at is invalidated. However, I barely know PHP so that's why I've come to SO with this problem.
How would you go about solving this issue? Is it correct that the $result pointer is affected by the second 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 link_identifier.
Youll have to grab all your posts (or a batch of them) and store the ids or whatever other data you need into an array or object and then iterate over it making the appropriate query and displaying output.
Or you could use some sql like this:
SELECT thank_you.* FROM thank_you, post WHERE post.id = thank_you.post_id ORDER BY thank_you.post_id;
Of course with this you lose grouping youd have to add some extra logic to build the proper presentation structures based on if the post_id has changed within the loop.