Query more slow - php

I do a query but does not show anything on the screen and when I opened the page where I do the query is slow and does not show anything
$query="SELECT * FROM Dettagli_macchina WHERE macchine_id='$macchine' and Email='$_SESSION[login_user]'";
$result = mysqli_query($conne,$query);
while($row=mysqli_num_rows($result)){
echo $row['COMPONENTE'];
}

mysqli_num_rows() will only use for getting no of rows not for row data.
You need yo use mysqli_fetch_*()
while($row=mysqli_fetch_array($result)){
echo $row['COMPONENTE'];
}
Why this query slow? Because you are using infinite loop here, always TRUE.
while($row=mysqli_num_rows($result))
One more story, I hope you are using session_start() in your file, but suppose that if $_SESSION not found or not start than your query will failed.
In last, this is just a suggestion regarding Naming Convention, you are using column name in small letter, capital small, full capital, this is not related to answer but you must need to learn about this art.
this will help you to understand Naming Convention: Database, Table and Column Naming Conventions?
This reference will help you to understand how mysqli_fetch_array() works: http://php.net/manual/en/mysqli-result.fetch-array.php

Please try with this one for return value and if you need number of raw then the statements will be different.
$query="SELECT * FROM Dettagli_macchina WHERE macchine_id='$macchine' and Email='$_SESSION[login_user]'";
$result = mysqli_query($conne,$query);
while($row=mysqli_fetch_array($result)){
echo $row['COMPONENTE'];
}

As others have pointed out, you have mixed up the mysqli_num_rows function, here I am using it to print the number of results found, then loop through the results after converting the mysqli result object to an array named $row
echo 'Found '. mysqli_num_rows($result) .' results';
while ($row = mysqli_fetch_array($result)) {
echo $row['COMPONENTE'];
}

You are fetching record but using mysqli_num_rows() which return total number of rows/records replace it with mysqli_fetch_array() here is the working example.
$query="SELECT * FROM Dettagli_macchina WHERE macchine_id='$macchine' and Email='$_SESSION[login_user]'";
$result = mysqli_query($conne,$query);
while($row = mysqli_fetch_array($result)) { //replace mysqli_num_rows with mysqli_fetch_array
echo $row['COMPONENTE'];
}

Related

PHP while loop. Why does this work?

I'm creating my first php site using tutorial for reference. I can't get my head around why the following works:
while ($row = mysql_fetch_array($result)){
echo $row[1]. " ".row[2]."<br/>";
}
Specifically, how does the loop increment to the next row?
UPDATE:
Thanks to all who bothered to provide an answer, including those who implored me to RTM. My problem was not understanding how while loops work, rather simply I couldn't see how the loop increments.
THE ANSWER:
From the PHP docs,
mysql_fetch_array: Returns an array that corresponds to the fetched row and moves the internal data pointer ahead
I see now, all is well.
You can rewrite that code to this equivalent:
$row = mysql_fetch_array($result); // fetch and advance
while ($row !== false) { // compare result against false
echo $row[1]. " ".row[2]."<br/>";
$row = mysql_fetch_array($result); // fetch and advance
}
An assignment yields a value which can then be used in a condition, though it's a good practice to put parentheses around the assignment:
// fetch and advance, compare fetched result against false
while (($row = mysql_fetch_array($result)) !== false) {
echo $row[1]. " ".row[2]."<br/>";
}
mysql_fetch_array() will take a $result and save into $row in form an array. Using while loop, your program will loop the data in the array from the beginning until the end.
By the way, your codes should be like
while ($row = mysql_fetch_array($result)){
echo $row['someData1']. " ".row['someData2']."<br/>";
}
If you want to iterate through the index, then the code looks like following but it will print the word Array as you will print the result in "that" specific index.
$indexCounter = 0;
while ($row = mysql_fetch_array($result)){
echo $row[$indexCounter]."<br/>";
}
Hope this helps! Thank you.
The mysql_fetch_array take the first element of $result then is $result have elements this work... is like take cards from a deck
Take a read though the PHP While documentation. It might also be useful to learn what mysql_fetch_array() does and how it works. After you're done reading about that, don't use the mysql_* functions again because they're deprecated. Instead, use mysqli_* or PDO.

Counting the values of rows in a column and using the total value in PHP

I know this is something simple. I'm just forgetting something.
I'm counting the values of the rows in the "numberattending" column of my database.
When I run the SQL statement
SELECT COUNT(numberattending) AS Total FROM RSVP
in the mySQL window I get the total I'm looking for.
When I try to extract that value and echo "num_seats" I get "Resource id #3"
$num_seats = mysql_query("SELECT COUNT(numberattending) AS Total FROM RSVP", $connection);
echo $num_seats;
What I'm I missing?
Thanks for any help ahead of time.
$num_seats represents a MySQL Resource, not the value of the field selected. You'll need to use either mysql_fetch_array() or mysql_fetch_object() depending on which you prefer.
For example:
$number = mysql_fetch_array($num_seats);
echo $number['Total'];
It's also worth noting that the mysql_* family of functions are now deprecated, and you should really be using MySQLi or PDO.
You need to loop through the result sets:
From the PHP site:
// Use result // Attempting to print $result won't allow access to
information in the resource // One of the mysql result functions must
be used // See also mysql_result(), mysql_fetch_array(),
mysql_fetch_row(), etc.
$num_seats = mysql_query("SELECT COUNT(numberattending) AS Total FROM RSVP", $connection);
while ($row = mysql_fetch_assoc($num_seats )) {
echo $row['total'];
}
PS: As others will surely tell you, use of the mysql* functions have been deprecated. Look for the mysqli functions instead.
Try
$query = mysql_query("SELECT COUNT(numberattending) AS Total FROM RSVP", $connection);
$result = mysql_fetch_row($query);
echo $result['Total'];

Passing PHP MySQL Result Object to Function

I'm trying to take a MySQL result row and pass it to a function for processing but the row isn't getting passed. I'm assuming this is because the actual row comes back as a object and objects can't get passed to function?
E.G
function ProcessResult($TestID,$Row){
global $ResultArray;
$ResultArray["Sub" . $TestID] = $Row["Foo"] - $Row["Bar"];
$ResultArray["Add" . $TestID] = $Row["Foo"] + $Row["Bar"];
}
$SQL = "SELECT TestID,Foo,Bar FROM TestResults WHERE TestDate !='0000-00-00 00:00:00'";
$Result= mysql_query($SQL$con);
if(!$Result){
// SQL Failed
echo "Couldn't find how many tests to get";
}else{
$nRows = mysql_num_rows($Result);
for ($i=0;$i<$nRows;$i++)
{
$Row = mysql_fetch_assoc($Result);
$TestID = $Row[TestID];
ProcessResult($TestID,$Row);
}
}
What I need is $ResultArray populated with a load of data from the MySQL query. This isn't my actual application (I know there's no need to do this for what's shown) but the principle of passing the result to a function is the same.
Is this actually possible to do some how?
Dan
mysql_query($SQL$con); should be mysql_query($SQL,$con); The first is a syntax error. Not sure if this affects your program or if it was just a typo on here.
I would recommend putting quotes around your array keys. $row[TestID] should be $row["TestID"]
The rest looks like it should work, although there are some strange ideas going on here.
Also you can do this to make your code a little cleaner.
if(!$Result){
// SQL Failed
echo "Couldn't find how many tests to get";
}else{
while($Row = mysql_fetch_assoc($Result))
{
$TestID = $Row['TestID'];
ProcessResult($TestID,$Row);
}
}
mysql_fetch_assoc() returns an associative array - see more
If you need an object, try mysql_fetch_object() function - see more
Both array and object can be passed to a function. Thus, your code seems to be correct, except for one line. It should be:
$Result= mysql_query($SQL, $con);
or just:
$Result= mysql_query($SQL);

PHP while loop Error

My query is right but its fetch zero result so why this while loop is print ones this statement No error please tell thanks in advance
while(mysql_fetch_array($query))
{ echo "<br>"."No Error"."<br>"; }
Please do a small debugging and put "echo mysql_num_rows($query);" just before that. It should tell you the exact number of records - and thus, the number of loops in while. mysql_fetch_array returns FALSE when no more records (or no records from the beginning).
mysql_fetch_array() method takes result of running a query on database as parameter rather than query itself and returns a row as an array.
Correct code would be:
$result = mysql_query($query);
while($row = mysql_fetch_array($result) )
{
echo "<br>"."No Error"."<br>";
}
For more details on mysql_fetch_array(), have a look at:
http://php.net/manual/en/function.mysql-fetch-array.php

Is mysql_num_rows efficient and/or standard practice?

A while ago I was poking around with SQLite, trying to port some of my sites to use it instead of MySQL. I got hung up on the lack of a function to count results, like PHP's mysql_num_rows(). After searching a little I discovered this mail list, which says (as I understand it) that SQLite doesn't have that functionality because it's inefficient. It states that it is bad form to write code that needs to know how many rows are returned.
I generally use mysql_num_rows to check for empty return results. For example:
$query = "SELECT * FROM table WHERE thing = 'whatever'";
$results = mysql_query($query);
if (mysql_num_rows($results)) {
while ($row = mysql_fetch_array($results)) {
echo "<p>$row[whatever]</p>";
}
} else {
echo "<p>No results found</p>";
}
The vehement distaste for the concept of mysql_num_rows() in the SQLite community makes me wonder if it's that terribly efficient for regular MySQL in PHP.
Is there a better, more accepted way for checking the size of a MySQL result set in PHP besides mysql_num_rows()?
EDIT:
I'm not just using mysql_num_rows to get the count--I would use a COUNT query for that. I'm using it to check if there are any results before outputting everything. This is useful for something like displaying search results - it's not always guaranteed that there will be results. In SQLite world, I have to send one COUNT query, check if there is something, and then send a SELECT query to get everything.
You already have something that is telling you if you've got results in mysql_fetch_array(). It returns false if there are no more rows to fetch (from php.net).
$query = "SELECT * FROM table WHERE thing = 'whatever'";
$results = mysql_query($query);
if($results) {
$row = mysql_fetch_array($results);
if($row) {
do {
echo "<p>{$row[whatever]}</p>";
} while($row = mysql_fetch_array($results));
} else {
echo "<p>No results found</p>";
}
} else {
echo "<p>There was an error executing this query.</p>";
}
Regardless of whether or not you actually use what you SELECTed, all of the rows are still returned. This is terribly inefficient because you're just throwing away the results, but you're still making your database do all of the work for you. If all you're doing is counting, you're doing all that processing for nothing. Your solution is to simply use COUNT(*). Just swap COUNT(*) in where you would have your SELECT statement and you're good to go.
However, this mostly applies to people using it as a complete substitute for COUNT. In your case, the usage isn't really bad at all. You will just have to manually count them in your loop (this is the preferred solution for SQLite users).
The reason being is in the underlying SQLite API. It doesn't return the whole result set at once, so it has no way of knowing how many results there are.
As explained on the mailing list you found. It is inefficient to return the count of rows because you need to allocate a lot of memory to hold the entire (remaining) result set. What you could do, is to simply use a boolean to test if you have output anything.
$query = "SELECT * FROM table WHERE thing = 'whatever'";
$results = mysql_query($query);
$empty_result = true;
while ($row = mysql_fetch_array($results)) {
echo "<p>$row[whatever]</p>";
$empty_result = false;
}
if ($empty_result) {
echo "<p>No results found</p>";
}

Categories