Is it possible to select all id's without a while-loop - php

I'm not sure if there is an answer for this, but I was thinking about the fact that PHP isn't very fast with while loops. That got me thinking about a basic function, which does something like this:
$array = array();
$sItem = DB::cms_query("SELECT id FROM someTable");
while($fItem = $sItem->fetch_assoc() ){
$array[] = $fItem['id']; // store the id in an array
}
That will give me an array with all found id's. What I was wondering is this:
Is it possible to select all those id's in 1 query and only use one fetch (so no loops to fetch), without creating difficult code. The goal is a simple piece of code to select all id's.
Small edit: I could replace fetch_assoc() with fetch_row() to improve a tiny bit, but I'm looking to replace the loop
To answer some questions:
I'm using mysqli, in my own custom database class (I'm new to OO, so in time I might improve that, but thats another story)

No, the mysqli extension doesn't provide any way to fetch all rows with a single operation, you can only fetch them one at a time. The only PHP API that currently offers this feature is PDO.

but I was thinking about the fact that php isnt very fast with while loops
How much ids are you fetching and what is called "not fast" for you?
I think the reason for a bad performance would most likely not be a while loop, but some other glitch with your code...

Related

PHP get the max value from database

Hey I am trying to get the max id from in my database using a one line of code.
Have this code that is working, however I know that there is a better way to do without using three line of code. One more thing I am using xammp for my database.
$result = #mysqli_query($connection, "SELECT MAX(Cust_ID) FROM customer");
$row = mysqli_fetch_row($result);
$getlastID = $row[0];
I was hoping that someone can help me, please.
The fact is, with mysqli there are three steps to what you are doing. If you were using PDO, you could use fetchColumn to combine the last two steps into one.
Just for the sake of argument, you can actually combine those three lines of code into one, by wrapping the query in the fetch row and dereferencing the result directly:
$id = mysqli_fetch_row(mysqli_query($connection, 'SELECT MAX(Cust_ID) FROM customer'))[0];
I would not recommend doing it this way, though. It will be easier to debug your script if each of these instructions is executed in a separate statement. Less code is generally better, but not at the expense of maintainability.
Incidentally, you should avoid using the error control operator (#). If there are errors, you want to know about them so you can handle them rather than ignoring them. There may be some valid uses for it, but this is probably not one of them.

Alternative to while loop

I am a newbie. I asked a question earlier regarding retrieving duplicates of the data i need from the db, for example the opening times from each takeaway duplicating on each take away (see image below); and i received a very helpful comment. The comment suggested that my while loop is causing my problem of query results duplication, as it is overriding my data.
duplication example
After looking at my code and working out which while loops are causing this problem (as I have a few), and playing around with them to understand my issue, I am now intrigued to know what loop can be used in replacement or as alternative to a while loop.
$rest_query = "SELECT Resturant_ID FROM Rest_Details";
$res_results = $dbc->query($rest_query);
//while($row_results = $res_results->fetch_assoc()){
$row_results = $res_results->fetch_assoc();{
{
$rests = $row_results['Resturant_ID'];
}
}
Above is one of the while loops I have removed, I know I will need a loop to gain all the information needed. And I do not know the number of repetitions I will need, therefore a for loop is not helpful.
Just trying to gain a better understanding, as I am building this website to teach myself.
"SELECT DISTINCT my_column_with_duplicates FROM Rest_Details"
and then
while($row_results = $res_results->fetch_assoc())
will work just fine.
Also there are other ways like $res_results->fetchAll() to get all the results in an array then use foreach loop. Just an idea.

How do i prevent duplicate output among multiple, nested sql queries?

I have a query which lists 10 different items in a database.
Within this query, i have a nested query which, for each of items 1-10 listed above, finds related subcategories in another table.
So ultimately, 11 queries occur. 1 to iterate through the major categories, and the other 10 to query and output for each of those categories.
Problem is, collectively, they output duplicated values.
Since it is done over 10 queries, i cant use DISTINCT, because even if the output is distinct within its own query, it is not distinct in the overall group.
So how can i make sure that i multiquery list like this is unique? Does js or php have a built in function that can do such?
Your code is not really scaleable. You're already reaching large numbers of queries, imagine if you had 100 items...
Instead, consider creating a subquery within the original query, since this would allow you to only run one query and the MySQL engine can do all the crunch work more easily (since it knows what you're actually asking for).
Make use of JOINs if possible, and pay close attention to indexes. I can't really help more without seeing some code, but this should help because DISTINCT would suddenly be usable again.
Actually, I found a way to solve it without reworking my code. I just put the entire output from all queries into the same array using a non-resetting incremental $array[$i] and then used php's array_unique. :). PHP is a fantastically versatile language. My humble (noob) opinion.

Take SQL input in PHP and output query results to the page

Basically I'm looking to create a page using PHP that will take SQL input, and output the results returned by the DB (MySQL). This is not for a production website (I understand the security implications). It's more for learning and practice. Kind of like the SQL console section of phpMyAdmin, or even similar to what sqlzoo.net can do (I think they are using perl, but I'd like to do it in PHP). Is there a practical way to accomplish this?
For example, how can I create a page in PHP/HTML to display a table of results when I don't know how many columns the query will return?
Also, what is the most practical way to allow a visitor to this web page to restore the DB to a default state with the original data? (e.g. create a sql dump of the original state and make a button that runs it? or is there a better way?)
Thanks!
Use * in your SQL query to fetch all columns and loop over the results from mysql_fetch_row() or mysql_fetch_assoc() with foreach.
Besides that, have you thought of using the mysql CLI ? It's useful for those requirements.
This question should be more specific than it is now.
"create a sql dump of the original state and make a button that runs it?" - Yes. But make sure you drop/delete the existing data.
You may have to run at least two queries... first return one row using LIMIT 1, and count the returning elements (using PHP count($row) if you use mysql $row = fetch_row($handle) ) to count the columns, and you can use SQL COUNT() to find out how many rows would be returned.
As for returning data to original state, I think a drop/recreation from a dump like you said may be the simplest and most reliable option.
Your best option is just running the query, checking if the amount of rows > 0, and then if it is, loop through the query resultset in a foreach and just show whatever you like.

PHP next MySQL row - how to move pointer until function checks true?

I have a PHP script which takes a value from a row in my MySQL database, runs it through a function, and if it determines it's true returns one value, and if it's false, it needs to go to the next value in the database and check that one until eventually one returns true.
I think I need to use mysql_fetch_assoc, but I'm not really sure in what way to use it... I wish I could post my code to be more specific, but it's a lot of code and most of it has no bearing on this issue...
Is the "function" something you could do in the database instead? It's really inefficient to process every row in the table to check for some type of condition. That's exactly what databases are good at, namely, processing queries efficiently and getting answers to you quickly.
So I'd recommend looking at how to do it all on the database side so that your PHP code is just fetching the end result (i.e. rows filtered by the function). Maybe if you provide more details of what your "function" is doing, a more specific answer can be provided.
You can use mysql_fetch_array, and just jump on the values fetched using $row[id] and not $row['name'].
Say your function returns true, you'd just use $row[lastid+1].
If the ID isn`t incremental, this could work :
$qry_result = mysql_query($qry) or die(mysql_error());
while ($row = mysql_fetch_array($qry_result)) {
$result = yourfunction($row['whatever');
if ($result != false)
break;
}
Also there is a php function next() which advances a pointer to the next array element. In your function you could implement an array builder, and then cycle between the elements with this. Depends on what your function actually does or script purpose is. It could lead to some load if there are alot of results.
You should not check database this way, as mentioned above. Database has a little difference from the plain text file.
You should not have a field in your database that has a bunch of values separated by value1:value2|value1:value2|value1:value2. It must be separate fields. Database has a little difference from the plain text file and you better learn it.
You could try something like this:
SELECT *
FROM table
WHERE field NOT LIKE '%$sessionvar:%';
I think that is what you are after?

Categories