I am having trouble in loading time. I tried removing the first if-else statement and it works Very fast but not when added back. I have more than 40000 rows in the tables.
while ($qry->fetch()){
$form .= "
<div class='formSections' id='formSections-$formSectionCounter'>
<h4 style='text-align: center; color: white; width: 100%; font-size: 20px; margin: 10px auto;'>$sname</h4>
";
$qry2 = $con->prepare("SELECT FieldId, FieldName, FieldType, FieldFilter, DisplaySubSection from qrp.agency_webform_section_fields where SectionId = ? ORDER BY FieldOrder ASC");
// $response_array['data'] .= $con->error;
$qry2->bind_param("s", $sid);
$qry2->execute();
$qry2->store_result();
if ($qry2->num_rows > 0)
{
$qry2->bind_result($fid, $fname, $ftype, $ffilter, $DisplaySubSection);
while ($qry2->fetch())
{
if($DisplaySubSection != ''){
$form .= "
<h4 style='text-align: center; color: white; width: 100%; font-size: 20px; margin: 10px auto;'>$DisplaySubSection</h4>
";
}
unset($defval);
unset($dov);
unset($doid);
unset($iof);
unset($reqf);
$qry3 = $con->prepare("SELECT DefaultValue,IncludeOnForm,Required from qrp.agency_webform_fields where WebformId = ? and FieldId = ?");
$qry3->bind_param("ss", $wfid, $fid);
$qry3->execute();
$qry3->store_result();
if ($qry3->num_rows > 0)
{
//FOUND FIELD IN Webform
$qry3->bind_result($defval, $iof, $reqf);
$qry3->fetch();
if ($defval != '')
{
$qry4 = $con->prepare("SELECT OptionValue,OptionId from qrp.agency_webform_field_options where OptionId = ?");
$qry4->bind_param("s", $defval);
$qry4->execute();
$qry4->store_result();
if ($qry4->num_rows > 0)
{
$qry4->bind_result($dov, $doid);
$qry4->fetch();
}
else
{
$dov = $defval;
}
}
}
$form .= "
<div class='BothinputsAndLabelsAndCheckbox'>
<div class='inputsAndLabels'>
<label>$fname</label>";
if ($ftype == 'String' || $ftype == 'INT'){
$form .= "
<input name='$fid-default' id='$fid-default' type='text' class='' value='$dov' data-toggle='tooltip' data-placement='top' title='If you set an answer here, it will be the default value in the form'>
";
} else if ($ftype == 'Date'){
$date = date('Y-m-d', strtotime($dov));
$form .= "
<input name='$fid-default' id='$fid-default' type='date' class='' value='$date' data-toggle='tooltip' data-placement='top' title='If you set an answer here, it will be the default value in the form'>
";
} else if ($ftype == 'Checkbox'){
$form .= "
<input name='$fid-default' id='$fid-default' type='checkbox' class='' value='$dov' data-toggle='tooltip' data-placement='top' title='If you set an answer here, it will be the default value in the form'>
";
} else if ($ftype == 'SelectList'){
$form .= "
<select name='$fid-default' id='$fid-default' class='' data-toggle='tooltip' data-placement='top' title='If you set an answer here, it will be the default value in the form'>";
$qry3 = $con->prepare("SELECT OptionValue,OptionId,FieldFilterId from qrp.agency_webform_field_options where FieldId = ? Order By OptionValue");
$qry3->bind_param("s", $fid);
$qry3->execute();
$qry3->store_result();
$form .= "<option value=''>Please Select an Option</option>";
if ($qry3->num_rows > 0)
{
$qry3->bind_result($optv, $optid, $filid);
while ($qry3->fetch())
{
if (!isset($defval))
{
$form .= "<option value='$optid' id='$filid' class='$filid'>$optv</option>";
}
else
{
if ($doid == $optid)
{
$form .= "<option value='$optid' id='$filid' class='$filid' selected>$optv</option>";
}
else
{
$form .= "<option value='$optid' id='$filid' class='$filid'>$optv</option>";
}
}
}
}
$form .= "
</select>
";
}
$form .= "
</div>"; // end inputsAndLabels div
$form .= "
<div class=''>
<div class='includeDiv'>
<input type='checkbox' class='includeButton' id='$fid-include' data-value='$fid' name='$fid-include' "; if ($iof > 0){ $form .= " checked"; }$form .= " data-toggle='tooltip' data-placement='top' title='If you set an answer here, it will be the default value in the form'>
<label class='' for='$fid-include'> Include</label>
</div>";
if ($ftype != 'Checkbox'){
$form .= "
<div class='requiredDiv'>
<input type='checkbox' class=' requiredButton' id='$fid-required' data-value='$fid' name='$fid-required' "; if ($reqf > 0){ $form .= " checked"; }$form .= " data-toggle='tooltip' data-placement='top' title='If you set an answer here, it will be the default value in the form'>
<label class='' for='$fid-required'> Require </label>
</div>
";
}
$form .= "
</div>
</div>
";
}
}
$form .= "
</div> <!-- close formSections -->
";
$formSectionCounter++;
}
If you are doing a loop over 40000 Rows, this is basically not a problem. The Problem begins if, for every fetched row, you prepare a new SQL Statement to select related information for each row id. In your example, you are creating at least 40000 times the number of rows in subsequent SQL selects, new select statements, and that is slowing down the page load
You can solve it, by extending your first SQL Statement with a Left Join or a subselect to get all Data within one SQL fetch iteration.
I suggest saving your results into arrays. Don't mix up SQL preparation and HTML Markup. This makes the code much cleaner, and once you got your data with optimized SQL into arrays, you can search for the problem much better. Create your HTML Markup as usual with nested loops, but inside those loops access your Arrays, which you have prefilled with the Data from the Database.
Related
I have this following PHP code in search.php to gather information from the form in the same file. It's a search engine and when I put something into the search bar I get only one row even when I should get more than one row.
Here is php script:
<?php
$error = "";
$con=mysqli_connect('localhost', 'root', '');
$db=mysqli_select_db($con, 'vodici');
if(isset($_POST['button'])){ //trigger button click
$search=$_POST['search'];
$query=mysqli_query($con,"select distinct * from users where meno like '%{$search}%' || priezvisko like '%{$search}%' || mesto like '%{$search}%' || kraj like '%{$search}%' || rok_narodenia like '%{$search}%' || email like '%{$search}%' ");
if (mysqli_num_rows($query) > 0) {
while($row = mysqli_fetch_array($query)) {
$div = "<div style='border: 1px solid black; border-radius: 5px;'>".$row['id'];
$vysledok = "<h2 style='text-decoration: underline; padding-left: 2%;'>".$row['meno']." ".$row['priezvisko']."</h2>";
$mail = "<p style='padding-left : 2%; font-size: 11px;'><strong>Rok narodenia:</strong> ".$row['rok_narodenia']." <br><strong>E-mail: </strong> ".$row['email']."</p>";
$mesto = "<p style='padding-left: 2%'><strong>Mesto:</strong> ".$row['mesto']." <strong>Kraj:</strong> ".$row['kraj']."</p>";
$div_end = "</div>";
}
}else{
$error = "Nič sme nenašli :/ <br><br>";
}
}
mysqli_close($con);
?>
Here is form:
<form class="search-form" action="" method="post">
<div class="input-group">
<input name="search" type="text" class="form-control" placeholder="Vyhľadať...">
<div class="input-group-append">
<button class="btn btn-secondary" type="submit" name="button"><i class="fa fa-search"></button></i>
</div>
</div>
</form>
<p><?php if(isset($_POST['button']) && $error == "") {
while($row = mysqli_fetch_array($query)) {
echo $div,$vysledok,$mail,$mesto,$div_end;
}
}?></p>
<p><?php if(isset($_POST['button']) && $error !== "") {echo $error;}?></p>
What can I do here? I am out of ideas
Thanks
You only added one row. You need to add each row to the generated html.
$result = '';
if (mysqli_num_rows($query) > 0) {
while($row = mysqli_fetch_array($query)) {
$div = "<div style='border: 1px solid black; border-radius: 5px;'>".$row['id'];
$vysledok = "<h2 style='text-decoration: underline; padding-left: 2%;'>".$row['meno']." ".$row['priezvisko']."</h2>";
$mail = "<p style='padding-left : 2%; font-size: 11px;'><strong>Rok narodenia:</strong> ".$row['rok_narodenia']." <br><strong>E-mail: </strong> ".$row['email']."</p>";
$mesto = "<p style='padding-left: 2%'><strong>Mesto:</strong> ".$row['mesto']." <strong>Kraj:</strong> ".$row['kraj']."</p>";
$div_end = "</div>";
$result .= $div. $vysledok. $mail.$mesto. $div_end ;
}
}else{
$error = "Nič sme nenašli :/ <br><br>";
}
echo $result;
}
In compensation to wakeels answer, that is correct, I would like to ask you to use prepared statements like in my example below
$sql="
SELECT `id`,`meno`,`priezvisko`,`rok_narodenia`,`email`,`mesto`,`kraj`
FROM `users`
WHERE
`meno` LIKE '%?%'
OR `priezvisko` LIKE '%?%'
OR `mesto` LIKE '%?%'
OR `kraj` LIKE '%?%'
OR `rok_narodenia` LIKE '%?%'
OR `email` LIKE '%?%'
;"
$stmt = $con->prepare($sql);
$stmt->bind_param("s", $search);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
echo $div,$vysledok,$mail,$mesto,$div_end;
}
When i keep search field blank and hit on search button, then show all results from mysql database, Why.... here is my php code....
I want to create it, when i keep search field blank and click search button... have to show error "no search result" and want to create disallowed white spacing search and need extra one HTML button for all Entries. By one click so that i get all entries......
please help me....
<?php
$con=mysql_connect('localhost', '1093913', 'tanim1996');
$db=mysql_select_db('1093913');
if(isset($_POST['button'])){ //trigger button click
$search=$_POST['search'];
$query=mysql_query("select * from iconic19 where student_id like '%{$search}%' || name like '%{$search}%' || phone like '%{$search}%' || blood like '%{$search}%' || district like '%{$search}%' ");
if (mysql_num_rows($query) > 0) {
while ($row = mysql_fetch_array($query)) {
echo "<tbody>";
echo "<tr>";
echo "<td data-label='Student ID'>".$row['student_id']."</td>";
echo "<td data-label='Name' style='font-weight:bold;' >".$row['name']."</td>";
echo "<td data-label='Mobile No'>"."<a href='tel:".$row['phone']."'>".$row['phone']."</a>"."</td>";
echo "<td data-label='Blood' style='color:red; font-weight:bold;' >".$row['blood']."</td>";
echo "<td data-label='Email'>"."<a href='mailto:".$row['email']."'>".$row['email']."</a>"."</td>";
echo "<td data-label='District'>".$row['district']."</td>";
echo "</tr>";
echo "</tbody>";
}
}else{
echo "<div class='error-text'>No results</div><br><br>";
}
}else{ //while not in use of search returns all the values
$query=mysql_query("select * from iconic19");
while ($row = mysql_fetch_array($query)) {
}
}
mysql_close();
?>
Its Html Code
<form id="nbc-searchblue1" method="post" enctype="multipart/form-data" autocomplete="off">
<input id='wc-searchblueinput1' placeholder="Search Iconic..." name="search" type="search" autofocus>
<br>
<input id='nbc-searchbluesubmit1' value="Search" type="submit" name="button">
<div class="view-all"> Show all</div>
</form>
Its css Code..
.view-all a {
background: red;
padding: 10px;
border-radius: 4px;
color: #fff;
text-decoration: none;
}
<?php
$con=mysql_connect('localhost', '1093913', 'tanim1996');
$db=mysql_select_db('1093913');
if(isset($_POST['button'])){ //trigger button click
$numRows = 0;
if(!empty($_POST['search'])) {
$search = mysql_real_escape_string($_POST['search']);
$query = mysql_query("select * from iconic19 where student_id like '%{$search}%' || name like '%{$search}%' || phone like '%{$search}%' || blood like '%{$search}%' || district like '%{$search}%' ");
$numRows = (int)mysql_num_rows($query);
}
if ($numRows > 0) {
while ($row = mysql_fetch_array($query)) {
echo "<tbody>";
echo "<tr>";
echo "<td data-label='Student ID'>".$row['student_id']."</td>";
echo "<td data-label='Name' style='font-weight:bold;' >".$row['name']."</td>";
echo "<td data-label='Mobile No'>"."<a href='tel:".$row['phone']."'>".$row['phone']."</a>"."</td>";
echo "<td data-label='Blood' style='color:red; font-weight:bold;' >".$row['blood']."</td>";
echo "<td data-label='Email'>"."<a href='mailto:".$row['email']."'>".$row['email']."</a>"."</td>";
echo "<td data-label='District'>".$row['district']."</td>";
echo "</tr>";
echo "</tbody>";
}
} else {
echo "<div class='error-text'>No results</div><br><br>";
}
} else { //while not in use of search returns all the values
$query = mysql_query("select * from iconic19");
while ($row = mysql_fetch_array($query)) {
}
}
mysql_close();
?>
What I have done was creating a new variable $numRows with a default value of 0. If your search is empty there is no query to the database. I escaped your $search variable.
BTW: Please change to mysqli, the mysql extension is no longer supported in newer php versions.
Just check if $_POST['search'] is blank then display your message else execute your query.
<?php
// this is where selecting of number of rooms in database
$sql = mysqli_query($con, 'SELECT * FROM roomtype');
$get_room1 = mysqli_query ($con, "SELECT * from room where status='Activated' and type_id=2");
$get_room2 = mysqli_query ($con, "SELECT * from room where status='Activated' and type_id=3");
$get_room3 = mysqli_query ($con, "SELECT * from room where status='Activated' and type_id=4");
$get_room4 = mysqli_query ($con, "SELECT * from room where status='Activated' and type_id=5");
$standard = mysqli_num_rows($get_room1);
$deluxe = mysqli_num_rows($get_room2);
$family = mysqli_num_rows($get_room3);
$regular = mysqli_num_rows($get_room4);
// this is the loop for the drop down and it will display the number of rooms available
while($row = mysqli_fetch_array($sql))
{
$a=$row['type_id'];
$b = $row['rmtype'];
$_SESSION['room_type'] = $row['rmtype'];
echo '<div style="height: 300px;">';
echo '<div style="float: left; width: 100px; margin-top: 15px; margin-left: 60px;">';
echo "<img width=250 height=200 alt='Unable to View' src='" . $row["image"] . "'>";
echo '</div>';
echo '<div class="well" style="float: right; width: 780px; margin-top: 5px;">';
echo '<div style="float: right;">';
echo '</div>';
echo '<br />';
echo "<label style='margin-left: px;'>Number of rooms:";
echo "<select name='select_no_rooms[]' value='" .$row['rmtype']." ' />";
echo "<option> </option>";
if ($row['rmtype']=="Standard Room")
{
for ($x = 1; $x<=$standard; $x++){
echo "<option name='standard'>$x</option>";}
}
if ($row['rmtype']=="Deluxe Room")
{
for ($x = 1; $x<=$deluxe; $x++){
echo "<option name='deluxe'>$x</option>";}
}
if ($row['rmtype']=="Family Room")
{
for ($x = 1; $x<=$family; $x++){
echo "<option name='family'>$x</option>";}
}
if ($row['rmtype']=="Regular Room")
{
for ($x = 1; $x<=$regular; $x++){
echo "<option name='regular'>$x</option>";}
}
echo "</select>";
}
?>
This is the design of drop down,
add [ ] tag to name tag, so you will get your value in array.
<option name='deluxe[]'>$x</option>
First thing that I notice is that in you select statement, you cannot have value as an attribute. Please check the documentation select tag
And the option tag does not include name attribute. Please check the documentation option tag
If you want to get multiple values from a drop down list. Please check this article
I'm working on a real basic chat that is mostly php powered. I'd like to use jQuery to check for new messages and update the #cbox div every few seconds. So far I have tried accomplishing that using the code below. For a frame of reference, this is my first time including jQuery into any of my scripts, so the problem is likely a very simple error that I am overlooking in my newbishness.
The problem I'm running into is the #cbox div displays blank, it doesn't seem to be calling to chat_post.php at all. I will post that code as well, in case the problem is with that and not with my jQuery. To fix, I tried also including <div id='cbox'> in chat_post.php, but that yielded no results. At this point, I'm pretty much grasping at straws.
<div id='sb_content'>
<center><div id='chat'>
<div id='ribbon' style='position: relative; margin-top:-50px; margin-left:-32px;'><center><span class='ribbon'>chat box</span></center></div>
<div style='margin-top: -20px;'><center><span style='text-shadow: 0 0 0.2em #000;' class='admin'>admin</span> || <span style='text-shadow: 0 0 0.2em #000;' class='mod'>mod</span></center></div>
<div id="cbox">
<script>
$(document).ready(function() {
setInterval(function(){getUpdates()}, 2000);
});
function getUpdates() {
$("#cbox").load("chat_post.php");
}
</script>
</div>
<form name="message" method='post' action="chat_post.php" id="cbox_input">
<input name="usermsg"id='usermsg' type="text" size="63" maxlength="255" />
</form>
</div></center>
</div>
chat_post.php
<div id='cbox' align='left'>
<?php
$username = $_SESSION['login'];
$ug = $_SESSION['user_group'];
// Display messages
$sql = <<<SQL
SELECT *
FROM `chat_entries`
ORDER BY `ts` DESC
LIMIT 0,50
SQL;
$result = $db->query($sql);
$count = $result->num_rows;
if ($count != 0){
while ($row = mysqli_fetch_array($result)) {
$c_name = $row['author'];
$c_text = $row['text'];
$c_ts = $row['ts'];
$c_id = $row['id'];
$sqlm = <<<SQL
SELECT *
FROM `users`
WHERE username = '$c_name'
SQL;
$resultm = $db->query($sqlm);
$countm = $resultm->num_rows;
if ($count != 0){
while ($rowm = mysqli_fetch_array($resultm)) {
$c_level = $rowm['user_group'];
}
}
if ($c_level == 'mod') {
echo "
<a href='/user/" . $c_name . "' class='mod'>" . $c_name . "</a>
";
}
if ($c_level == 'admin') {
echo "
<a href='/user/" . $c_name . "' class='admin'>" . $c_name . "</a>
";
}
if ($c_level == 'member') {
echo "
<a href='/user/" . $c_name . "' class='member'>" . $c_name . "</a>
";
}
if ($c_level == 'guest') {
echo "
<i>" . $c_name . "</i>
";
}
echo "
: " . $c_text . "<div id='cbox_div'>";
echo "<span style='float:left;'><i>" . $c_ts . "</i></span>";
echo "<span style='float:right;'>";
if ($ug == 'mod' || $ug == 'admin'){
echo " <a href='#'>Delete</a> || <a href='#'>Block</a> ||";
}
if ($_SESSION['login']) {
echo "Report</span></div>
";
}
}
}
?>
After removing the extra id on chat_post.php, my code worked just fine. Funny how something so simple can really mess things up. (: Thank you everyone for your help!
I'm trying to find a way to upload a value to SQL using a checkbox but no luck
this is my code:
/////////////////////////// FOR RXTRA ////////////////////////////////////////////////////////////
$sql = "SELECT ext_id,ext_price,ext_name,ext_description FROM tbl_extra ORDER by ext_id ASC";
$result = mysql_query($sql) or trigger_error(mysql_error(),E_USER_ERROR);
$number = mysql_num_rows($result);
$i = 0;
while ($number > $i) {
$ID = mysql_result($result,$i,"ext_id");
$NA= mysql_result($result,$i,"ext_name");
$PR= mysql_result($result,$i,"ext_price");
$DES= mysql_result($result,$i,"ext_description");
//this part chack if the value is "0" and show with "tooltip" the value\/
if ( $PR == 0 ) {
print ''.$NA.'<span>' .' free '.'</span>!';
} else {
print ''. $NA .'<span>' .' add '.' '. $PR .' $ '. '</span>!';
}
print "<input style='width: 30px; height: 15px;' type='checkbox' name='extra[]' value='$NA'></td>\n";
//this java calculate the value add to extra ant outpot the total extra that pass to sql table
print "<input type='hidden' name='item_name'/>";
print "<input type='hidden' name='amount'/>";
print "<input style='width: 30px; height: 15px;' type='checkbox' onClick='ReadForm (this.form, false);' value='+$PR'></td>\n";
$i++;
}
?>
</div></div>
<?
} else {
}
?>
<!----->
<div class="item_add_cart">
<span class="title">total extra $</span>
<div class="content">
<?
print "<input style='color:#000;font-size:13px;' size='7' name='tot' type='text'/>";
?>
</div></div>
<!----->
my problem is that I have two table's one is the total price and one is the names I try to insert all value with one checkbox and it's not working
If I create 2 checkboxes and click on them then the value uploads ok
but I need only one checkbox that sends value from $NA to Table ext_name and total price from name='tot' to ext_price table
Please note that the above code doesn't work, #Majid Fouladpour suggests the following code instead.
/////////////////////////// FOR RXTRA ////////////////////////////////////////////////////////////
$sql = "SELECT ext_id,ext_price,ext_name,ext_description FROM tbl_extra ORDER by ext_id ASC";
$result = mysql_query($sql) or trigger_error(mysql_error(),E_USER_ERROR);
$number = mysql_num_rows($result);
$i = 0;
while ($number > > $i) {
$ID = mysql_result($result,$i,"ext_id");
$NA= mysql_result($result,$i,"ext_name");
$PR= mysql_result($result,$i,"ext_price");
$DES= mysql_result($result,$i,"ext_description");
//this part chack if the value is "0" and show with "tooltip" the value\/
if ( $PR == 0 ) {
print ''.$NA.'' <a href="#" class="tooltip2">'.$NA.'<span>' .' free '.'!';
.'</span></a>!';
} else {
print ''. <a href="#" class="tooltip2">'. $NA .'' '<span>' .' add '.' '. $PR .' $ '. '!';
</span></a>!';
}
print "\n";<input style='width: 30px; height: 15px;' type='checkbox' name='extra[]' value='$NA'></td>\n";
//this java calculate the value add to extra ant outpot the total extra that pass to sql table
print "";
<input type='hidden' name='item_name'/>";
print "";<input type='hidden' name='amount'/>";
print "\n";
<input style='width: 30px; height: 15px;' type='checkbox' onClick='ReadForm (this.form, false);' value='+$PR'></td>\n";
$i++;
}
?>
total >
</div></div>
<?
} else {
}
?>
<!----->
<div class="item_add_cart">
<span class="title">total extra $</span>
<div class="content";
>
<?
print "<input style='color:#000;font-size:13px;' size='7' name='tot' type='text'/>";
?>
>
</div></div>
<!----->
(I've made this answer community wiki so the rep doesn't go to me)