PHP MySql Query performance with variable declaration - php

Alright - this may be a dumb question, but my desire for perfection is fueling me, so, if it is stupid and pointless, just let me know.
I have a mysql query where I fetch rows from a database table, and I need the value in some shape or form for all the columns I collect. Look at the following sample code (this could use an array to gather output instead - the fundamental question should be the same):
$query="SELECT A,B,C,D FROM table1 WHERE 'X'='Y'";
$result=mysql_query($query,$resource);
while($row=mysql_fetch_assoc($result)){
$var1=$row['A']; $var2=$row['B'];
echo '<li class="' . $row['C'] . '" id="' . $row['D'] . '">';
}
My question is as follows:
I only need $row['A'] and $row['B'] once since they are the same value for every row in this case, but I do need them once. The other values will be different for every row, and I need them as well, as in the example.
Is there a problem with continuously setting the variable throughout the loop? Or is it better to use if(!isset...? or is there some other way to do this? Or is the performance hit so minimal as to make this question irrelevant?
Thanks

why not just set the variables outside the loop.
$result=mysql_query($query,$resource);
$result_new = mysql_fetch_assoc($result);
$var1 = $result_new['A']; //considering $result_new['A'] always exists
$var2=$result_new['B']; //considering $result_new['B'] always exists
while($row=$result_new){
echo '<li class="' . $row['C'] . '" id="' . $row['D'] . '">';
}

Really don't bother with that. Unless you're looping over millions of records.
If you need more speed, don't echo in the while loop:
$result=mysql_query($query,$resource);
$string ='';
if ($result) {
$row=mysql_fetch_assoc($result);
$string .= '<li class="' . $row['C'] . '" id="' . $row['D'] . '">';
$var1=$row['A'];
$var2=$row['B'];
while($row=mysql_fetch_assoc($result)){
$var1=$row['A']; $var2=$row['B'];
$string .= '<li class="' . $row['C'] . '" id="' . $row['D'] . '">';
}
}
echo $string;
Two more things. Don't use mysql_*: Use of this extension is discouraged!
And (like I thought someone else said) if a/b is always the same, you should rethink you're database structure.
Edit:
To give a real answer to your question:
I did a small test.
Setting the value on each loop (1,000 times) takes 0.00027s. Checking inside the loop if the value was already set takes 0.00030s. So just setting it each time is even faster than checking.

the performance hit in this scenario is irrelevant, in fact i would speculate if if(isset..) guards would take a tiny bit longer - only scenario I can think of, where this question would matter would be a situation where you assign (larger) objects or arrays to $var1 and somehow force php to make a copy, not a reference
if it bothers you for aesthetic reasons (I could relate ;)), you could use a do - while loop:
//assuming you always get at least one result
$result=mysql_query($query,$resource);
$row=mysql_fetch_assoc($result);
$var1=$row['A']; $var2=$row['B'];
do {
// the loop stuff - stringify or echo the list
} while ($row=mysql_fetch_assoc($result)) ;

you can do it with a do-while expression
$query="SELECT A,B,C,D FROM table1 WHERE 'X'='Y'";
$result=mysql_query($query,$resource);
if($row=mysql_fetch_assoc($result)) {
$var1=$row['A']; $var2=$row['B'];
do {
echo '<li class="' . $row['C'] . '" id="' . $row['D'] . '">';
} while($row=mysql_fetch_assoc($result));
}

Related

PHP ECHO table with dynamic dropdown as one column using FOR EACH

I am a bit stuck I am attempting to build out a table with HTML and PHP. Ok got that done. Now I want to add a dynamic dropdown as one of the column options but cant seem to figure out how to mix the PHP, the HTML and the needed FOR EACH loop.
I know its currently wrong but am posting a variable of what I have been trying below.
echo '<td>' . "<select>". "<option value =" . $sf_name . ' '. $sl_name . ">" . $sf_name . ' '. $sl_name . "</option>" .
foreach($Staff_On_Duty as $person){
"<option value =" . $sf_name_option=$person->Staff_First_Name . ' '. $sl_name_option=$person->Staff_Last_Name . ">" . $sf_name_option . ' '. $sl_name_option . "</option>"
}
. "</select>" .'</td>';
I need to have the currently selected individual at the top of the dropdown with the option to change that person out. the first .sf_name comes from higher in the code and gives me the name of the individual currently selected. The foreach runs from the $Staff_On_Duty query to give me everyone working right now. What is the right way to do this?
This is how I would do it, essentially only fill the dropdown and mark the option that should have been selected (other stuff is a matter of preference):
echo("<td><select>");
foreach($Staff_On_Duty as $person){
$sf_name_option=$person->Staff_First_Name; // separated for clarity, you could also use $person->Staff_First_Name everywhere
$sl_name_option=$person->Staff_Last_Name;
echo("<option value = $sf_name_option $sl_name_option");
if (($sf_name_option == $sf_name) && ($sl_name_option == $sl_name)) echo (" selected"); // this is the relevant part, but make sure variable values match!
echo(">$sf_name_option $sl_name_option</option>");
}
echo("</select></td>");
Note that I did not put any quotation marks cause I have no idea what your variables entail, but it would need them if you don't have them in yet, i.e.:
... value=\"$sf_name_option $sl_name_option\" ...

PHP while loop multiple conditions returning no data?

I have a PHP page that is returning data from a MySQL table. I decided to add a feature that would allow the user to set the number of results they want displayed, in case there are thousands of records for example.
Here is the PHP code that displays the data:
while ($row = mysql_fetch_array($result) && ($row <= $noOfResults)) {
echo '<p class="display-date">' . $row['date'] . '</p><p class="display">' . $row['id'] . ' - ' . base64_decode( $row['packetdata']) . '</p>';
echo '<hr align="center" width="100%" />';
echo $noOfResults;
}
I was hoping that this would only display the data up to the point that the user has selected. So if the user selects 10 results, $noOfResults is set to 10, and it will only fetch the first 10 results from the database. This is currently however only displaying a "-" and the $noOfResults variable (which is desired at this point). Is my syntax wrong or is this not the correct method of going about such a problem?
Thanks, got it working with LIMIT, didn't even think to do that.
Can someone explain why this was downvoted, just trying to learn, so as to write better questions in the future, thanks.
the best way to get limited data from database is LIMIT statement in query .
i assume that your query is
$result= "SELECT * FROM `mytable`";
Just add limit statement in
$result= "SELECT * FROM `mytable` LIMIT '$noOfResults'";
then your while loop will be
while ($row = mysql_fetch_array($result) ) {
echo '<p class="display-date">' . $row['date'] . '</p><p class="display">' . $row['id'] . ' - ' . base64_decode( $row['packetdata']) . '</p>';
echo '<hr align="center" width="100%" />';
echo $noOfResults;
}
You are doing it wrong $row will be an array. So to correct this use mysql_num_rows() function in php to check the number of the rows. Try the code below.
if(mysql_num_rows($result)<=$noOfResults){
while ($row = mysql_fetch_array($result) ) {
echo '<p class="display-date">' . $row['date'] . '</p><p class="display">' . $row['id'] . ' - ' . base64_decode( $row['packetdata']) . '</p>';
echo '<hr align="center" width="100%" />';
echo $noOfResults;
}
}
Hope this helps you

How do I use quotation marks properly when echoing properties and attributes through PHP and SQL)?

while ($row = $arr_result ) {
echo "<option value='" . $row['fallacytype'] . "'>" . $row['fallacytype'] . "</option>";
}
I am trying to create a and menu in html by using the string values in my SQL table.
I've confirmed that the rest of my code (not shown here, but can be provided if needed to diagnose), is working. The only thing that goes wrong is that my loop up there becomes infinite (i know this because it creates infinite sql value).
I've looked up and tried all the variations of quotation marks to no avail.
I've checked in w3shool.com, and other video tutorials that my loop syntax is correct.
It seems that the $row variable is not incrementing or moving on to the next value in the loop for some curious reason.
Thanks in advance.
You have to loop via following way for all the elements:
foreach($arr_result as $row) {
echo "<option value='" . $row['fallacytype'] . "'>" . $row['fallacytype'] . "</option>";
}

Dynamically setting the selected option in a HTML drop down list - PHP

I am aware there are examples out there that hover around the issue of dynamically setting the selected tag in a HTML option tag, but I am hitting a pretty difficult issue of break statements and quotations in what I am trying to accomplish.
while($info = mysql_fetch_array($companydesc))
{
$output3 .= '<option value="'. $info['company_code'] . if ($result['company']==$info['description']){echo 'selected=\"selected\"'} . '">' . $info['description'] . '</option>';
}
echo $output3;
The error that I receive is a unexpected T_IF on the line with the if statement. Is it not legal to put an if statement in there? Or is it a matter of doing proper breaks? Any help would be greatly appreciated (and hopefully the formatting for the code worked)
Use a ternary statement:
while($info = mysql_fetch_array($companydesc)) {
$output3 .= '<option value="'. $info['company_code'].'"'.($result['company']==$info['description'] ? ' selected=\"selected\"' : '') . '>' . $info['description'] . '</option>';
}
echo $output3;
yeah, it is illegal, my suggestion is:
while($info = mysql_fetch_array($companydesc))
{
if($result['company']==$info['description'])
{
$output3 .= '<option value="' . $info['company_code'] . '" selected = selected>' . $info['description'] . '</option>';
}
else
{
$output3 .= '<option value="' . $info['company_code'] . '">' . $info['description'] . '</option>';
}
}
echo $output3;
Trying to fix everything with an individual solution in the way that you originally intended to with stuff like
while($info = mysql_fetch_array($companydesc))
is, I feel, one of the big things that is holding php back and eventually makes the code extremely difficult to maintain, although it's very easy on the learning curve.
This function takes an optional selected parameter and will build out your select box. This is much much better than doing every single select box for every query with its own custom code.
There might be a syntax error in here, but generally,
function selectBox($array, $selected=false){
foreach($array as $name => $value){
$options .= '
<option value=" . $name . '"'
. ($selected != false && $selected == $value) ? 'SELECTED' : ''
. '>".$name."</option>";
}
}
Worth mentioning that select box is requiring you to pass a predefined array of key=>value pairs, so you'll need to have an additional helper function (you can't just pass it your database return)
Also probably worth mentioning is that using mysql_fetch_array($companydesc) is not abstracting the database level at all. Down the line, code like this will prohibit a migration to something like Postgres or a different database system entirely.

Loading table column names with spaces with ms sql in php

I am using php to connect to my ms sql server. I am using php 5.3, using the microsoft database dll to connect. The problem i have is that in my database, i have tables wich there column's names have blank spaces, mean there is a table called bills whit a column named "Shipper Code" or "Shipper name"... something like that... i want to know how i can read the rows using fetch_object
while($row = sqlsrv_fetch_object($stmt))
{
echo "<li>" . $row->Code . $row->MasterId . "</li>";
echo "<li>". $row->Shipper Code . "</li>"; <== HERE HOW I MUST PUT SHIPPER CODE?
}
Do i must use () or {} or []...
thank you in advanced!
You should avoid the usage of spaces in column or object names. If you wish to separate the strings then use an underscore _ instead. This will retain the readability and ensure that the item can be accessed properly.
Other than that you can use the following:
while($row = sqlsrv_fetch_object($stmt)) {
$results[] = $row;
echo "<li>" . $results['Code'] . $results['MasterId'] . "</li>";
echo "<li>". $results['Shipper Code'] . "</li>";
}
I've got the answer. I only need to use "{" and "}". Something like this
while($row = sqlsrv_fetch_object($stmt))
{
echo "<li>" . $row->{"Num"} . $row->{"MasterId"} . "</li>";
echo "<li>". $row->{"Shipper Code"}. "</li>";
}
Thanks for all your help.

Categories