I'm trying to make a paginating blog using PHP, HTML, and MySQL. I wrote the code but for some reason the webpage shows up blank. What's wrong with my code? Chrome's console returns a 500 internal server error.
<div id="article">
<?php
include 'php/mysql_connect.php';
if(empty($_GET)){
$current_id = SELECT max(id) FROM posts;
}
else{
$current_id = mysql_safe_string($_GET['id']);
}
$result = mysql_safe_query('SELECT * FROM posts WHERE id=%s LIMIT 1',$current_id);
if(!mysql_num_rows($result)){
echo '<h2>No Posts Found</h2>';
exit;
}
$row = mysql_fetch_assoc($result)
echo '<h2>'.$row['title'].'</h2>';
echo '<div class="row">';
echo ' <div class="group1 col-sm-6 col-md-6">';
echo ' <span class="glyphicon glyphicon-pencil"></span><a data-toggle="collapse" data-target="#comments" class"collapsed">'.$row['num_comments'].' Comments </a>';
echo ' <span class="glyphicon glyphicon-time"></span>'.date('F j<\s\up>S</\s\up>, Y', $row['date']);
echo ' </div>';
echo '</div>';
echo '<br />';
echo '<p class="lead">'.n12br($row['body']).'</p>';
?>
<div id="comments" class="collapse" >
<div class="well">
<h4>Leave a comment</h4>
<?php echo '<form role="form" method="post" action="php/comment_add.php?id=($current_id)" class="clearfix">'; ?>
<div class="col-md-6 form-group">
<label class="sr-only" for="name">Name</label>
<input type="text" class="form-control" id="name" placeholder="Name" required />
</div>
<div class="col-md-6 form-group">
<label class="sr-only" for="email">Email</label>
<input type="email" class="form-control" id="email" placeholder="Email" required />
</div>
<div class="col-md-12 form-group">
<label class="sr-only" for="content">Comment</label>
<textarea class="form-control" id="content" placeholder="Comment" required></textarea>
</div>
<div class="col-md-12 form-group text-right">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
</div>
<br>
<?php
$result = mysql_safe_query('SELECT * FROM comments WHERE post_id=%s ORDER BY date ASC',$current_id);
echo ' <ul id="comments" class="comments">';
while($row = mysql_fetch_assoc($result)){
echo ' <li class="comment">';
echo ' <div id="inline" ><h4 style="display:inline;">'.$row['name'].'</h1><sup><p style="display:inline; font-size:10px;"> '.date('j-M-Y g:ia', $row['date']).'</p></sup></div>';
echo ' <em>'.n12br($row['content']).'</em>';
echo ' </li>';
echo ' </ul>';
}
?>
<hr>
</div>
</div>
<nav>
<ul class="pager">
<?php
$newer_id = IFNULL(mysql_safe_query('SELECT min(id) FROM posts WHERE id > $current_id ORDER BY id ASC LIMIT 1'),-1);
$older_id = IFNULL (mysql_safe_query('SELECT max(id) FROM posts WHERE id < $current_id ORDER BY id ASC LIMIT 1'),-1);
if($newer_id != -1){
echo '<li>Newer</li>';
}
if ($older_id != -1){
echo '<li>Older</li>';
}
?>
</ul>
</nav>
This is php/mysql_connect.php, which is supposed to prevent sql injection (i got this from a tutorial):
<?php
// mysql.php
function mysql_safe_string($value) {
$value = trim($value);
if(empty($value)) return 'NULL';
elseif(is_numeric($value)) return $value;
else return "'".mysql_real_escape_string($value)."'";
}
function mysql_safe_query($query) {
$args = array_slice(func_get_args(),1);
$args = array_map('mysql_safe_string',$args);
return mysql_query(vsprintf($query,$args));
}
function redirect($uri) {
header('location:'.$uri);
exit;
}
mysql_connect('localhost','(username)','(password)');
mysql_select_db('(database)');
From the logs I locate the failure which is:
Syntax error, unexpected 'max' (T_STRING) on line 6 (if(empty($_GET)){$current_id = SELECT max(id) FROM posts})
As other pointed out (and it should be immediately clear by the syntax error you are facing), your $current_id query is not being quoted. A good beginning is to fix the first block as such:
if(empty($_GET)) {
$current_id = "SELECT max(id) FROM posts;";
} else {
$current_id = mysql_safe_string($_GET['id']);
}
if(empty($_GET)){
$current_id = SELECT max(id) FROM posts;
}
no quotes around the sql is a mistake.
If your file is myfile.html and you don't have permission for embedded PHP it will not execute on the server.
Related
I want all the records(i.e seats selected by the user) should be disabled but this code only fetches the last record and disables it.
<?php
$sqlcheck = "select * from booknow where hotel ='$test'";
$resultcheck = mysqli_query($conn,$sqlcheck);
while($rowcheck = mysqli_fetch_array($resultcheck))
{
$checkedcheck = $rowcheck['book'];
$expcheck=explode(",",$checkedcheck);
}
?>
<?php $i=1;
while ($i<=$tab)
{?>
<div class="TWO">
<div class="check"style="height:40px;width:120px;">
<div class="seconda">
</div>
<div class="secondb">
<input type ="checkbox"name="checky[]"class="tabtwo"style="width:30px;height:30px;"
value="<?php echo "Two-seater A".$i;?>"
<?php if(in_array("Two-seater A".$i, $expcheck)) {?>
onclick="this.checked=this.defaultChecked"<?php } else {echo "none";}?>>
</div>
<div class="secondc">
</div>
<label for="c1"style="margin-left:40px;"><b>A<?php echo$i?></b>
</label>
</div>
</div>
<?php
$i++;
}
?>
Try below code
while($rowcheck = mysqli_fetch_array($resultcheck))
{
$checkedcheck = $rowcheck['book'];
$expcheck[] =explode(",",$checkedcheck);
}
How do make my search work from a class... i can display my search results on the major page but i want it to display all results and if it is more than the paginated result, client can easily move to another page.
<?php
// if it's going to need the database, then it's
//probably smart to require it before we start.
#require_once(LIB_PATH.DS.'database.php');
class Product extends DatabaseObject {
protected static $table_name="products";
protected static $db_fields=array('id', 'product_id', 'image', 'title', 'slug', 'description', 'price');
public $id;
public $product_id;
public $image;
public $title;
public $slug;
public $description;
public $price;
public static function search(){
global $database;
$sql = "SELECT * FROM products WHERE image LIKE '{%$search%'";
$sql .= " OR title LIKE '{%$search%}'";
$sql .= " OR slug LIKE '%$search%'";
$sql .= " OR description LIKE '%$search%'";
$sql .= " OR price LIKE '%$search%'";
$total_count = count($sql);
$result_set = $database->query($total_count);
$row = $database->fetch_assoc($result_set);
return array_shift($row);
}
?>
Please check my code... i am a bit confused.
<?php if(empty($_POST['search'])){
$session->message("<div class='error-msg'>Search cannot be empty</div>");
redirect_to('photos.php');
}
?>
<?php include_layout_template('header2.php'); ?>
<div class="container">
<div class="row">
<?php
if(isset($_POST['submit'])){
// 1. the current page number ($current_page)
$page = !empty($_GET['page']) ? (int)$_GET['page'] : 1;
// 2. records per page ($per_page)
$per_page = 10;
// 3. total record count ($total_count)
//$total_count = Product::count_all();
$total_count = Product::search();
// Find all photos
// use pagination instead
$pagination = new Pagination($page, $per_page, $total_count);
// Instead of finding all records, just find the records
$search = $database->escape_value($_POST['search']);
// $sql = "SELECT * FROM products WHERE image LIKE '%$search%'";
// $sql .= " OR title LIKE '%$search%'";
// $sql .= " OR slug LIKE '%$search%'";
// $sql .= " OR description LIKE '%$search%'";
// $sql .= " OR price LIKE '%$search%'";
// $sql .= " LIMIT {$per_page} ";
// $sql .= "OFFSET {$pagination->offset()}";
$search = new Product();
$search->search = $search;
$photos = Product::find_by_sql($search);
//$total_count = count($photos);
//echo $numresults = '<p class="error-msg">There are '.$total_count.' results in your search</p><br/><br/>';
foreach ($photos as $photo): ?>
<div class="col-md-4 col-sm-6">
<div class="row">
<div id="pagination" style="clear: both;">
<nav aria-label="Page navigation example">
<ul class="pagination">
<?php
for($i=1; $i <= $pagination->total_pages(); $i++){
if($i == $page) {
// echo " <span class=\"selected\">{$i}</span> ";
// } else{
// echo " {$i} ";
}
}
if($pagination->total_pages() > 1) {
if($pagination->has_previous_page()) {
echo "<li class='page-item'><a class='page-link' href=\"search.php?page=";
echo $pagination->previous_page();
echo "\">« Previous</a></li> ";
}
if($pagination->has_next_page()){
echo "<li class='page-item'><a class='page-link' href=\"search.php?page=";
echo $pagination->next_page();
echo "\">Next »</a></li>";
}
}
?>
</ul>
</nav>
</div>
</div>
<div class="thumbnail">
<form method="post" action="cart.php?action=add&id=<?php echo $photo->id; ?>" role="form" class="form-vertical">
<a href="order_review.php?id=<?php echo $photo->id; ?>"><img src="<?php echo $photo->image_path();
?>" class="img-thumbnail" alt="responsive image"></a>
<div class="caption">
<h3 class="text-info text-center"><?php echo $photo->title; ?></h3>
<p class="text-muted text-center price card-header"><span class="currency">N</span><?php echo $photo->price; ?></p>
<p class="text-center"><em><?php echo $photo->description; ?></em></p>
<input type="hidden" name="id" class="form-control" value="<?php echo $photo->id; ?>" />
<input type="hidden" name="title" class="form-control" value="<?php echo $photo->title; ?>" />
<input type="hidden" name="slug" class="form-control" value="<?php echo $photo->slug; ?>" />
<input type="hidden" name="description" class="form-control" value="<?php echo $photo->description; ?>" />
<input type="hidden" name="price" class="form-control" value="<?php echo $photo->price; ?>"/>
<div class="col-sm-4 mx-auto d-block">
<select name="quantity" class="form-control" name="quantity">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
</div>
</div>
<div class="col-sm-4 col-sm-push-3 mx-auto d-block">
<input type="submit" name="add_to_cart" class="btn bg-success" value="Add to cart" />
</div><br/>
</form>
</div>
</div>
<?php endforeach; }
?>
</div>
</div>
PLease take note of the code i commented out... I am a bit confused.
This is my whole code....
I am facing the problem while replacing the %20 with - in url. I have tried many codes but failed. please help me out. I am attaching my full code. I am getting problem in
/">Visit
where i am displaying both id as well as firm name. I just want to show both id as well as firm name and they are separated by /
<?php
error_reporting("0");
$rowperpage =10 ;
#$select_city=$_GET['city'];
if(isset($_REQUEST['search'])){
$allcount_query = "SELECT count(*) as allcount FROM inventory_details";
$allcount_result = mysqli_query($conn, $allcount_query);
$allcount_fetch = mysqli_fetch_array($allcount_result);
$allcount = $allcount_fetch['allcount'];
$sql="SELECT * FROM inventory_details";
$search_item = mysqli_real_escape_string($conn, $_REQUEST['search_box']);
$sql .= " WHERE (firm_name LIKE '%$search_item%'";
$sql .= " OR catagory_name LIKE'%$search_item%'";
$sql .= " OR mobile_no LIKE'%$search_item%'";
$sql .= " OR product_key LIKE'%$search_item%')";
$sql .= " AND city='$select_city' AND status='0' ";
$sql .="ORDER BY today_date DESC limit 0,$rowperpage";
// $sql .= " ORDER BY catagory_name LIMIT 0,5";
// echo $sql;
if($_GET['search_box']==""){
$msg=include"error_msg.php";
}
else{
$fquery=mysqli_query($conn, $sql);
$totalrec=mysqli_num_rows($fquery);
if ($totalrec=='0'){
$msg=include"error_msg.php";
}
}
}
// if($selct_city=$_GET['city']){
// SELECT * FROM inventory_details WHERE city LIKE '%DELHI%' && catagory_name LIKE '%belts%'
// SELECT * FROM inventory_details WHERE firm_name='keyboard' OR catagory_name='keyboard' OR mobile_no='keyboard' OR city='keyboard' OR product_key='keyboard' && city="delhi"
// echo $sql . $fquery;
// SELECT * FROM inventory_details WHERE city='delhi' AND catagory_name like '%foot%' OR firm_name LIKE'%foot%' OR product_key like '%foot%' OR mobile_no like '%foot%'
// SELECT * FROM inventory_details WHERE city='Delhi' AND firm_name LIKE '%foot%' OR catagory_name LIKE'%foot%' OR mobile_no LIKE'%foot%' OR product_key LIKE'%foot%'
// // }
?>
<?php
?>
<!-- Brand and toggle get grouped for better mobile display -->
<!-- <div class="container">
<form class="navbar-form" role="search">
<div class="input-group col-md-12 col-xs-12 ">
<div class=" col-md-offset-7 col-md-5">
<select class="form-control select country" name="city" required="">please select city
<?php ;?>
</select>
<select class="form-control input-lg" placeholder="Search By Firm name,Category name,Mobile no....." name="search_box">
<option>select city</option>
<option>Delhi</option>
<option>Mumbai</option>
<option>Channai</option>
<option>Kolkata</option>
</select>
</div>
<div class="input-group-btn ">
</div>
<div class=" col-md-12">
<input type="text" class="form-control" placeholder="Just Type Anything..." name="search_box">
</div>
<div class="input-group-btn ">
<button class="btn btn-info" type="submit" name="search"><span class=""></span>search</button>
</div>
</div>
</form>
</div> -->
<?php
while($row=mysqli_fetch_assoc(#$fquery)){ //handle rows.
$id=$row['id'];
$catagory_name=$row['catagory_name'];
$firm_name=$row['firm_name'];
// $user_pass=md5($_POST ['user_pass']);
$city=$row ['city'];
$product_key=$row ['product_key'];
$firm_email=$row ['firm_email'];
$mobile_no=$row ['mobile_no'];
$phone_no=$row ['phone_no'];
$address=$row ['address'];
$Fax_no=$row ['Fax_no'];
$Website=$row ['Website'];
$product_key=$row['product_key'];
$sotime=$row ['sotime'];
$sctime=$row ['sctime'];
$Contact_person=$row ['Contact_person'];
$Contact_person_mobile=$row ['Contact_person_mobile'];
$colorname=$row ['colorname'];
$textcolor=$row ['textcolor'];
$compLogo=$row ['compLogo'];
////////////////////////////////////////
$banner=$row ['banner'];
if(empty($banner))
{
$banner="default.jpg";
}
?>
<div class="container post" id="post_<?php echo $id; ?>">
<div class="col-md-12 inv_data" style="background:<?php echo $colorname; ?>; color:<?php echo $textcolor; ?>;">
<div class="col-md-3">
<!-- <?php ?>
<img src="image/banner/<?php echo $banner; ?>" class="img_style"> -->
<?php
$imageArr = explode(',',$compLogo);
foreach ($imageArr as $k=>$val) { if($val!=""){
?>
<img class="mySlides" src="image/logo/<?php echo $val; ?>">
<?php
}}
?>
<img class="mySlides" src="image/logo/defualt.jpg">
</div>
<div class="col-md-7">
<h3><strong><?php echo strtoupper($firm_name); ?></strong></h3>
<strong></strong> <?php echo $product_key; ?><br>
<strong> <span class="glyphicon glyphicon-home"></span> </strong> <?php echo $address; ?><br>
<!-- <strong>Category : -</strong> <?php echo $catagory_name." , " . $product_key;?><br> -->
<!-- <strong>Phone no : -</strong> <?php echo $phone_no; ?>
<strong>Mobile no : -</strong> <?php echo $mobile_no; ?>
<br>
<strong> Whatsapp no : -</strong> <?php echo $Contact_person_mobile ; ?>
<strong> Contact Person : -</strong> <?php echo $Contact_person ; ?>
<br>
<strong>Email : -</strong> <?php echo $firm_email;?>
<strong>Timing : -</strong> <?php echo $sotime. " to ".$sctime?><br>
<strong>Website : -</strong> <?php echo $Website;?><br> -->
</div>
<div class="col-md-2">
<span> <br> <br> <br></span>
<button type="button" class="btn btn-info btn-lg">Visit</button>
<!--<a href="/jyp/<?php echo $id;?><?php echo $firm_name;?>"><button type="button" class="btn btn-info btn-lg">Visit</button>-->
</a>
</div>
</div>
</div>
<?php
}
?>
<?php
if(isset($_REQUEST['search'])){
?>
<h1 id="loadbtn"><span class="load-more">Load More</span></h1>
<input type="hidden" id="row" value="0">
<input type="hidden" id="cityname" name="cityname" value="<?php echo $city; ?>">
<input type="hidden" id="search_item" name="search_item" value="<?php echo $search_item; ?>">
<input type="hidden" id="all" value="<?php echo $allcount; ?>">
<?php
}
?>
The %20 gives a hint that the string is most probably Url Encoded (%20 is a single space character). So what you should probably be doing is trying to first Url Decode the string (then you will get the original string). Then afterwards you can remove/replace any characters that you do not want.
So in your question, you said you do not want %20 (a space) but a dash (-) instead. This could be achieved as follows...
<?php
error_reporting("0");
$rowperpage =10 ;
#$select_city=$_GET['city'];
if(isset($_REQUEST['search'])){
$allcount_query = "SELECT count(*) as allcount FROM inventory_details";
$allcount_result = mysqli_query($conn, $allcount_query);
$allcount_fetch = mysqli_fetch_array($allcount_result);
$allcount = $allcount_fetch['allcount'];
$sql="SELECT * FROM inventory_details";
$search_item = mysqli_real_escape_string($conn, $_REQUEST['search_box']);
$sql .= " WHERE (firm_name LIKE '%$search_item%'";
$sql .= " OR catagory_name LIKE'%$search_item%'";
$sql .= " OR mobile_no LIKE'%$search_item%'";
$sql .= " OR product_key LIKE'%$search_item%')";
$sql .= " AND city='$select_city' AND status='0' ";
$sql .="ORDER BY today_date DESC limit 0,$rowperpage";
// $sql .= " ORDER BY catagory_name LIMIT 0,5";
// echo $sql;
if($_GET['search_box']==""){
$msg=include"error_msg.php";
}
else{
$fquery=mysqli_query($conn, $sql);
$totalrec=mysqli_num_rows($fquery);
if ($totalrec=='0'){
$msg=include"error_msg.php";
}
}
}
// if($selct_city=$_GET['city']){
// SELECT * FROM inventory_details WHERE city LIKE '%DELHI%' && catagory_name LIKE '%belts%'
// SELECT * FROM inventory_details WHERE firm_name='keyboard' OR catagory_name='keyboard' OR mobile_no='keyboard' OR city='keyboard' OR product_key='keyboard' && city="delhi"
// echo $sql . $fquery;
// SELECT * FROM inventory_details WHERE city='delhi' AND catagory_name like '%foot%' OR firm_name LIKE'%foot%' OR product_key like '%foot%' OR mobile_no like '%foot%'
// SELECT * FROM inventory_details WHERE city='Delhi' AND firm_name LIKE '%foot%' OR catagory_name LIKE'%foot%' OR mobile_no LIKE'%foot%' OR product_key LIKE'%foot%'
// // }
?>
<?php
?>
<!-- Brand and toggle get grouped for better mobile display -->
<!-- <div class="container">
<form class="navbar-form" role="search">
<div class="input-group col-md-12 col-xs-12 ">
<div class=" col-md-offset-7 col-md-5">
<select class="form-control select country" name="city" required="">please select city
<?php ;?>
</select>
<select class="form-control input-lg" placeholder="Search By Firm name,Category name,Mobile no....." name="search_box">
<option>select city</option>
<option>Delhi</option>
<option>Mumbai</option>
<option>Channai</option>
<option>Kolkata</option>
</select>
</div>
<div class="input-group-btn ">
</div>
<div class=" col-md-12">
<input type="text" class="form-control" placeholder="Just Type Anything..." name="search_box">
</div>
<div class="input-group-btn ">
<button class="btn btn-info" type="submit" name="search"><span class=""></span>search</button>
</div>
</div>
</form>
</div> -->
<?php
while($row=mysqli_fetch_assoc(#$fquery)){ //handle rows.
$id=$row['id'];
$catagory_name=$row['catagory_name'];
$firm_name=$row['firm_name'];
// $user_pass=md5($_POST ['user_pass']);
$city=$row ['city'];
$product_key=$row ['product_key'];
$firm_email=$row ['firm_email'];
$mobile_no=$row ['mobile_no'];
$phone_no=$row ['phone_no'];
$address=$row ['address'];
$Fax_no=$row ['Fax_no'];
$Website=$row ['Website'];
$product_key=$row['product_key'];
$sotime=$row ['sotime'];
$sctime=$row ['sctime'];
$Contact_person=$row ['Contact_person'];
$Contact_person_mobile=$row ['Contact_person_mobile'];
$colorname=$row ['colorname'];
$textcolor=$row ['textcolor'];
$compLogo=$row ['compLogo'];
////////////////////////////////////////
$banner=$row ['banner'];
if(empty($banner))
{
$banner="default.jpg";
}
?>
<div class="container post" id="post_<?php echo $id; ?>">
<div class="col-md-12 inv_data" style="background:<?php echo $colorname; ?>; color:<?php echo $textcolor; ?>;">
<div class="col-md-3">
<!-- <?php ?>
<img src="image/banner/<?php echo $banner; ?>" class="img_style"> -->
<?php
$imageArr = explode(',',$compLogo);
foreach ($imageArr as $k=>$val) { if($val!=""){
?>
<img class="mySlides" src="image/logo/<?php echo $val; ?>">
<?php
}}
?>
<img class="mySlides" src="image/logo/defualt.jpg">
</div>
<div class="col-md-7">
<h3><strong><?php echo strtoupper($firm_name); ?></strong></h3>
<strong></strong> <?php echo $product_key; ?><br>
<strong> <span class="glyphicon glyphicon-home"></span> </strong> <?php echo $address; ?><br>
<!-- <strong>Category : -</strong> <?php echo $catagory_name." , " . $product_key;?><br> -->
<!-- <strong>Phone no : -</strong> <?php echo $phone_no; ?>
<strong>Mobile no : -</strong> <?php echo $mobile_no; ?>
<br>
<strong> Whatsapp no : -</strong> <?php echo $Contact_person_mobile ; ?>
<strong> Contact Person : -</strong> <?php echo $Contact_person ; ?>
<br>
<strong>Email : -</strong> <?php echo $firm_email;?>
<strong>Timing : -</strong> <?php echo $sotime. " to ".$sctime?><br>
<strong>Website : -</strong> <?php echo $Website;?><br> -->
</div>
<div class="col-md-2">
<span> <br> <br> <br></span>
<!-- there's the solution below -->
<?php
$firm_name = urldecode($firm_name); # decode the string (like converting %20 to a space character)
$firm_name = str_replace(' ', '-', $firm_name); # then replace any characters you don't want (like converting a space character to a -
$url = "category.php?edit=" . urlencode($id) . '/' . urlencode($firm_name);
?>
<button type="button" class="btn btn-info btn-lg">Visit</button>
<?php
// probably don't need these now.
$firm_name = urldecode($firm_name);
$firm_name = str_replace(' ', '-', $firm_name);
# are you missing a / here ???
$url = '/jyp/' . urlencode($id) . '' . urlencode($firm_name);
?>
<a href="<?php echo $url ?>"><button type="button" class="btn btn-info btn-lg">Visit</button>
</a>
</div>
</div>
</div>
<?php
}
?>
<?php
if(isset($_REQUEST['search'])){
?>
<h1 id="loadbtn"><span class="load-more">Load More</span></h1>
<input type="hidden" id="row" value="0">
<input type="hidden" id="cityname" name="cityname" value="<?php echo $city; ?>">
<input type="hidden" id="search_item" name="search_item" value="<?php echo $search_item; ?>">
<input type="hidden" id="all" value="<?php echo $allcount; ?>">
<?php
}
?>
You probably should encode whatever you echo to the browser using htmlspecialchars.
Disclaimer: The website where I was testing my PHP code gave the same result when using rawurldecode('hi%20you'); and urldecode('hi%20you');.
I have this code:
$q = 'SELECT * FROM languages ORDER BY id DESC';
$r = mysqli_query($dbc, $q);
while($langs = mysqli_fetch_assoc($r)){
$l_id = $langs['id'];
$l_name = $langs['name_en'];
?>
<li <?php if($l_id == '1'){ echo 'class="active"'; }?>><?php echo $l_name;?></li>
<?php } // closing 1st while loop
?>
</ul>
<div class="tab-content">
<?php
$q = 'SELECT * FROM languages ORDER BY id DESC';
$r = mysqli_query($dbc, $q);
while($langs = mysqli_fetch_assoc($r)){
$l_id = $langs['id'];
$l_lang = $langs['language'];
$l_name = $langs['name_en'];
?>
<div class="tab-pane fade <?php if($l_id == '1'){ echo 'in active'; }?>" id="<?php echo $l_name;?>">
<div class="form-group col-xs-4">
<label for="title_<?php echo $l_lang;?>">Title:</label>
<input class="form-control" type="text" name="title_<?php echo $l_lang;?>" id="title_<?php echo $l_lang;?>" value="<?php echo $opened['title_'.$l_lang.'']; ?>" placeholder="Page Title">
</div>
<div class="form-group col-xs-4">
<label for="header_<?php echo $l_lang;?>">Header:</label>
<input class="form-control" type="text" name="header_<?php echo $l_lang;?>" id="header_<?php echo $l_lang;?>" value="<?php echo $opened['header_'.$l_lang.'']; ?>" placeholder="Page Header">
</div>
<div class="form-group col-xs-<?php if($page_type == 'tour'){ echo 8;}else {echo 12;} ?>">
<label for="body_<?php echo $l_lang;?>">Body:</label>
<textarea class="form-control editor" name="body_<?php echo $l_lang;?>" id="body_<?php echo $l_lang;?>" rows="7" placeholder="Page Body"><?php echo $opened['body_'.$l_lang.'']; ?></textarea>
</div>
</div>
<?php } //closing 2nd while loop
?>
</div>
When running it, the result is a tabbed form (I skipped the form tags and some html from above, to reduce the code writen) and everything is OK.
My questions are:
How to have the same output, but with a single query and while loop?
Is it possible to make this a function? Any hints?
Thank you!
I think you will have to loop twice, but you don't need to make two queries at all!
Use mysqli_fetch_all to store the results in an array and then loop through it
For example:
$q = 'SELECT * FROM languages ORDER BY id DESC';
$r = mysqli_query($dbc, $q);
$langs = mysqli_fetch_all($r);
foreach($langs as $lang){
//render links
}
//...
foreach($langs as $lang){
//render tabs
}
Your script will run much faster
Try
<?php
function get_rows()
{
$q = 'SELECT * FROM languages ORDER BY id DESC';
$r = mysqli_query($dbc, $q);
$languages = array();
while($langs = mysqli_fetch_assoc($r))
{
$languages[] = $langs;
}
return $languages;
}
$languages = get_rows();
if($languages != false)
{
?>
<ul>
<?php
foreach($languages as $langs)
{
$l_id = $langs['id'];
$l_name = $langs['name_en'];
?>
<li <?php
if($l_id == '1')
{
echo 'class="active"';
}
?>><?php echo $l_name; ?></li>
<?php
}
?>
</ul>
<div class="tab-content">
<?php
foreach($languages as $langs)
{
$l_id = $langs['id'];
$l_lang = $langs['language'];
$l_name = $langs['name_en'];
?>
<div class="tab-pane fade <?php
if($l_id == '1')
{
echo 'in active';
}
?>" id="<?php echo $l_name; ?>">
<div class="form-group col-xs-4">
<label for="title_<?php echo $l_lang; ?>">Title:</label>
<input class="form-control" type="text" name="title_<?php echo $l_lang; ?>" id="title_<?php echo $l_lang; ?>" value="<?php echo $opened['title_' . $l_lang . '']; ?>" placeholder="Page Title">
</div>
<div class="form-group col-xs-4">
<label for="header_<?php echo $l_lang; ?>">Header:</label>
<input class="form-control" type="text" name="header_<?php echo $l_lang; ?>" id="header_<?php echo $l_lang; ?>" value="<?php echo $opened['header_' . $l_lang . '']; ?>" placeholder="Page Header">
</div>
<div class="form-group col-xs-<?php
if($page_type == 'tour')
{
echo 8;
}
else
{
echo 12;
}
?>">
<label for="body_<?php echo $l_lang; ?>">Body:</label>
<textarea class="form-control editor" name="body_<?php echo $l_lang; ?>" id="body_<?php echo $l_lang; ?>" rows="7" placeholder="Page Body"><?php echo $opened['body_' . $l_lang . '']; ?></textarea>
</div>
</div>
<?php } ?>
</div>
<?php
}
?>
Save results while first iterating in some array and the iterate over this array for the second time:
$tmp_array = array();
while ($langs = mysqli_fetch_assoc($r)){
$tmp_array[] = $langs;
}
//some code here
//and second array
foreach ($tmp_array as $langs) {
//more code here
}
I have a form that has a select field that loads the options dynamically from a db result query. Here is what the code looks like. See the description text input afterwards? I need the code to return the description of the item selected under productID. How do I go about this? Thanks very much for all replies.
<div class="row-fluid">
<div class="span3">
<label>SKU</label>
<?php echo '<select name="ITEM" id="user" class="textfield1">';
while($res= mysql_fetch_assoc($sql))
{
echo '<option value="'.$res['productID'].'">';
echo $res['SKU'] ;
echo'</option>';
}
echo'</select>';
?>
</div>
</div>
<div class="row-fluid">
<div class="span3">
<label>Description</label>
<input type="text" name="description" value=""/>
</div>
</div>
You can do this in 2 ways:
First way is by redirecting the page having a $_GET parameter which will contain the product id:
<div class="row-fluid">
<div class="span3">
<label>SKU</label>
<?php echo '<select name="ITEM" id="user" class="textfield1"
onchange="document.location=\'my-page.php?pid=\' + this.value">';
while($res= mysql_fetch_assoc($sql))
{
echo '<option value="'.$res['productID'].'"';
// LATER EDIT
if(isset($_GET['pid']) && $_GET['pid'] == $res['productID'])
echo 'selected="selected"';
// END LATER EDIT
echo '>';
echo $res['SKU'] ;
echo'</option>';
}
echo'</select>';
?>
</div>
</div>
<div class="row-fluid">
<div class="span3">
<label>Description</label>
<?php
if(isset($_GET['pid']) && is_numeric($_GET['pid'])) {
$sql = mysql_query("SELECT description
FROM products
WHERE product_id='" . mysql_real_escape_string($_GET['pid']) . "'");
$row = mysql_fetch_assoc($sql);
}
?>
<input type="text" name="description" value="<?=$row['description']?>"/>
</div>
</div>
Second way is to have an ajax call and fill description input dynamically, without refresing the page
// this is the JS code
$(document).ready(function(){
$('#user').change(function(){
$.POST("my-ajax-call-page.php",
{pid: $("#user").val()},
function(data){
$('input[name="description"]').val(data.description);
}, "json");
});
});
and your my-ajax-call-page.php should be like this:
<?php
include("mysql-connection.php");
$sql = mysql_query("SELECT description
FROM products
WHERE product_id='" . mysql_real_escape_string($_POST['pid']) . "'");
$row = mysql_fetch_assoc($sql);
echo json_encode("description" => $row['description']);
?>
You will find many examples and documentation for using jQuery library on jQuery library website
<div class="row-fluid">
<div class="span3">
<label>SKU</label>
<?php echo '<select name="ITEM" id="user" class="textfield1" onchange="showDesc()">';
$desHTML = "";
echo "<option value='0'>Please select</option>"
while($res= mysql_fetch_assoc($sql))
{
echo '<option value="'.$res['productID'].'">';
echo $res["SKU"] ;
echo'</option>';
$desHTML .="<div class'descBox' id='".$res['productID']."' style='display:none'>".$res['description']."</div>";
}
echo'</select>';
?>
</div>
</div>
<div class="row-fluid">
<div class="span3">
<label>Description</label>
<?php echo $desHTML; ?>
</div>
</div>
Now create one js function and call on onchange of select box.
Js function Hint:
$(".descBox").hide();
$("#"+selectedItemValue).show();
Let me know if you need any help for JS function.
You haven't shown us your SQL query, but I assume that you have a column named description and you are selecting this column in your query too.
So then, you can use jQuery to insert description of selected item to input
<div class="row-fluid">
<div class="span3">
<label>SKU</label>
<?php echo '<select name="ITEM" id="user" class="textfield1">';
$js_array = array(); // This variable will contain your Javascript array with descriptions
while($res= mysql_fetch_assoc($sql))
{
echo '<option value="'.$res['productID'].'">';
echo $res['SKU'] ;
echo'</option>';
// Fill your array with descriptions; ID of item will be the index of array
$js_array[$res['productID']] = $res['description'];
}
echo'</select>';
?>
<script>
var description;
<?php
foreach($js_array as $description => $id)
{
echo("description['".$id."'] = '".$description."';\n");
}
?>
$(document).ready(function(){
$('#user').change(function(){
$("#description").val(description[$('#user').val()]);
})
});
</script>
</div>
</div>
<div class="row-fluid">
<div class="span3">
<label>Description</label>
<input type="text" name="description" id="description" value=""/>
</div>
</div>
Be sure to not forget to add id attribute to your input type="text"