Select particular fields from a database using a checkbox in PHP - php

I want to select particular fields from a database using a checkbox in PHP.
My code is:
<?php
echo "<table border='1' class='tabtext'>";
$result = mysql_query("SELECT * FROM orders");
$numfields = mysql_num_fields($result);
echo "<table>\n<tr>";
for ($i=0; $i < $numfields; $i++) // Header
{
echo '<th>'.mysql_field_name($result, $i).'</th>';
echo '<tr><td><input type="hidden" name="checkbox[]" value="false"/></td></tr>';
echo '<tr><td><input type="checkbox" name="checkbox[]" value="true"/></td></tr>';
$checkbox[$i] = isset($_POST['checkbox'][$i]) ? true : false;
if(isset($checkbox))
{
foreach($checkbox as $value)
{
echo $value."<br>"; //it will print the value of your checkbox that you checked
}
}
}

I think something like this will give you better results.
<?php
echo "<table border='1' class='tabtext'>";
$result = mysql_query("SELECT * FROM orders");
$numrows = mysql_num_rows($result);
$numfields = mysql_num_fields($result);
// show headers
echo '<thead><tr>';
for ($field = 0; $field < $numfields; $field++) {
$field_name = mysql_field_name($result, $i);
echo '<th><label><input type="checkbox" name="checkbox[' . $field_name . ']" value="1"/> ' . $field_name . '</label></th>';
}
echo '</tr></thead>';
echo '<tbody>';
for ($row = 0; $row < $numrows; $row++) {
$data = mysql_fetch_assoc($result);
echo '<tr>';
for ($field = 0; $field < $numfields; $field++) {
$field_name = mysql_field_name($result, $i);
if (isset($_POST['checkbox'][$field_name])) {
echo '<td>' . $data[$field_name] . '</td>';
}
}
echo '</tr>';
}
echo '</tbody>';
echo '</table>';

Related

PHP Split Search Bar Keywords By Spaces

OK let me be as specific as possible.... I would like to change the way my search bar behaves. Right now the string has to match the MySQL query exactly!!! or it won't show my products.
Here is what I got:
A search for "case iphone"
searchitems.php?tosearch=case+iphone&Search=Search
Now a search for "iphone case"
searchitems.php?tosearch=iphone+case&Search=Search
Now based on how the query would work...if I type in the URL manually to this... it works how I want it to:
searchitems.php?tosearch=%iphone%&%case%&Search=Search
So how do I go about changing the URL from
searchitems.php?tosearch=case+iphone&Search=Search
to
searchitems.php?tosearch=%iphone%&%case%&Search=Search
Here is the code that I have so far:
Search Form In index.php
<form method="GET" action="searchitems.php">
<input size="50" type="text" name="tosearch" value="Search" name="keyword" id="keyword" title="keyword" onfocus="clearText(this)" onblur="clearText(this)" class="txt_field">
<input type="submit" name="Search" value="Search" alt="Search" id="searchbutton" title="Search" class="sub_btn">
</form>
searchitems.php (Sorry if it isn't tabbed correctly just copied and pasted)
<?php
include('core/header2.php');
include ('core/connectdb.php');
if(isset($_GET['tosearch'])) {
$tosearch=$_GET['tosearch'];
$tosearch=urldecode($tosearch);
$tosearch = preg_replace('!\s+!', ' ', trim($tosearch));
$search_terms = explode(' ',$tosearch);
$search_terms[] = $tosearch;
$search_terms=array_unique($search_terms);
$query = "select * from products where ";
$query_fields = Array();
$sql = "SHOW COLUMNS FROM products";
$columnlist = $connect->query($sql);
while($arr = $columnlist->fetch_assoc()){
extract($arr);
$query_fields[] = $Field . " LIKE ('%". $tosearch . "%')";
}
$query .= implode(" OR ", $query_fields);
$results = mysqli_query($connect, $query) or die(mysql_error());
$rows = $results->num_rows;
if ($rows > 0) {
$cols = 5;
$counter = 1;
$nbsp = $cols - ($rows % $cols);
echo '<div id="content" class="float_r">';
echo "<table border=\"0\">";
while ($row = mysqli_fetch_array($results, MYSQLI_ASSOC)) {
if(($counter % $cols) == 1) { // Check if it's new row
echo '<tr align="center">';
}
extract($row);
echo '<td valign="top" style="padding-right:15px;">';
echo "<a href=itemdetails.php?itemcode=$item_code>";
echo '<img src=' . $imagename . ' style="max-width:120px;max-height:140px;
width:auto;height:auto;"></img><br/>';
echo $item_name .'<br/>';
echo "</a>";
echo '<div class="product_price">$'. $price .'</div>';
echo "<form method=\"POST\" action=\"cart.php?action=add&icode=$item_code&iname=$item_name&iprice=$price&ilocation=$location\">";
echo "<input type=\"submit\" name=\"addtocart\" value=\"Add To Cart\"></form>";
echo "</td>";
if(($counter % $cols) == 0 ){
echo "</tr>";
}
$counter++;
}
if($nbsp > 0) { // Add unused column in last row
for ($i = 0; $i < $nbsp; $i++) {
echo '<td> </td>';
}
echo '</tr>';
}
}
}
echo '</table></div><div class="cleaner"></div>';
include('core/footer.php');
?>
well, brother, it's a bad approach how you doing it. But for learning, its fine. For + sign issue, you can use php urldecode, example:
<?php
$tosearch = 'a+b';
echo urldecode($tosearch);
it has its own pro/con thing but on high-level it will work for you, you can dig more into it if you like.

pagination on php limit 50

Can anyone help me with the pagination? I am trying this code on pagination and the pages are showing but when clicked on the pages like Next or the number with links it gives a syntax error.
"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?page=2' at line 1"
My tables data is around 250 and I wanted to limit it to 50 data per page.
Here is my code: (pagination section - is the problem)
<link rel="stylesheet" type="text/css" href="css/navbar.css">
<?php include 'navbar.php';?>
<br>
<?php
if(!isset($_GET['table'])){
echo 'You must assign a table to view.';
exit;
}
session_start();
//Connect here
$conn = mysqli_connect("localhost", "root", "", "dkusers");
$table = mysqli_real_escape_string($conn, $_GET['table']);
$fields = array();
$q = mysqli_query($conn, "SHOW COLUMNS FROM " . $table) or die(mysqli_error($conn));
while($r = mysqli_fetch_assoc($q)) $fields[count($fields)] = $r['Field'];
echo '<b><font size="4">Table: </b>', $table, '</font><br>';
// -----------------INSERT-----------------
if(isset($_POST['action']) && $_POST['action'] == "Insert"){
if(!isset($_POST['insert'])){
echo '<h3>Insert Row</h3>';
echo '<form method="post"><input type="hidden" name="action" value="' . $_POST['action'] . '" />';
echo '<table border="1" cellpadding="7"><tr><th>Field</th><th>Value</th><th>MD5</th></tr>';
foreach($fields as $key => $value){
echo '<tr><td>' . $value . ':</td><td><input type="text" name="field_' . $value . '" /></td><td><input type="checkbox" name="md5_' . $value . '" /></td></tr>';
}
echo '<tr><td><input type="submit" name="insert" value="Submit" /></td><td colspan="2">Back</td></tr></table></form>';
exit;
}else{
$first = true;
$query = "INSERT INTO " . $table;
foreach($_POST as $key => $value){
if(strrpos($key, "field_", -strlen($key)) !== false){
$key = substr($key, 6);
$query .= sprintf("%s%s", ($first) ? " (" : ",", $key);
$first = false;
}
}
$query .= ") VALUES";
$first = true;
foreach($_POST as $key => $value){
if(strrpos($key, "field_", -strlen($key)) !== false){
$key = substr($key, 6);
$query .= sprintf("%s'%s'", ($first) ? " (" : ",", (isset($_POST['md5_' . $key])) ? md5($value) : $value);
$first = false;
}
}
$q = mysqli_query($conn, $query . ")");
if($q) echo 'Successfully inserted row into table!<br/><br/>'; else echo mysqli_error($conn) . '<br/><br/>';
}
}
// -----------------DELETE-----------------
if(isset($_POST['action']) && $_POST['action'] == "Delete"){
if(!isset($_POST['rows'])){
echo 'You didn\'t send any rows to delete.<br/><br/>';
}else{
$count = 0;
for($i = 0;$i < count($_POST['rows']);$i++){
if($_POST['rows'][$i] >= count($_SESSION['store'])) continue;
$query = "DELETE FROM " . $table . "";
$row = $_SESSION['store'][$_POST['rows'][$i]];
$first = true;
foreach($row as $key => $value){
$query .= sprintf(" %s %s = '%s'", ($first) ? "WHERE" : "AND", $key, $value);
$first = false;
}
$q = mysqli_query($conn, $query . " LIMIT 1");
if(!$q) echo mysqli_error($conn) . '<br/>';
$count += mysqli_affected_rows($conn);
}
echo 'Successfully deleted ' . $count . ' row(s)!<br/><br/>';
}
}
// -----------------MODIFY-----------------
if(isset($_POST['action']) && $_POST['action'] == "Modify"){
if(!isset($_POST['rows'])){
echo 'You didn\'t send any rows to modify.<br/><br/>';
}else if(isset($_POST['modify'])){
$count = 0;
for($i = 0;$i < count($_POST['rows']);$i++){
if($_POST['rows'][$i] >= count($_SESSION['store'])) continue;
$first = true;
$query = "UPDATE " . $table . " SET";
foreach($_POST as $key => $value){
if(strrpos($key, "field_", -strlen($key)) !== false){
$key = explode("_", $key, 3);
if($key[1] == $i){
$query .= sprintf(((!$first) ? "," : "") . " %s = '%s'", $key[2], (isset($_POST['md5_' . $key[1] . '_' . $key[2]])) ? md5($value) : $value);
$first = false;
}
}
}
$row = $_SESSION['store'][$_POST['rows'][$i]];
$first = true;
foreach($row as $key => $value){
$query .= sprintf(" %s %s = '%s'", ($first) ? "WHERE" : "AND", $key, $value);
$first = false;
}
$q = mysqli_query($conn, $query . " LIMIT 1");
if(!$q) echo mysqli_error($conn) . '<br/>';
$count += mysqli_affected_rows($conn);
}
echo 'Successfully updated ' . $count . ' row(s)!<br/><br/>';
}else{
echo '<h3>Modify Row</h3>';
echo '<form method="post"><input type="hidden" name="action" value="' . $_POST['action'] . '" />';
for($i = 0;$i < count($_POST['rows']);$i++) if($_POST['rows'][$i] < count($_SESSION['store'])) echo '<input type="hidden" name="rows[]" value="' . $_POST['rows'][$i] . '" />';
echo '<table border="1" cellpadding="7"><tr><th>Field</th><th>Value</th><th>MD5</th></tr>';
for($i = 0;$i < count($_POST['rows']);$i++){
if($_POST['rows'][$i] >= count($_SESSION['store'])) continue;
if($i != 0) echo '<tr><td colspan="3"><hr/></td></tr>';
$row = $_SESSION['store'][$_POST['rows'][$i]];
foreach($row as $key => $value){
echo '<tr><td>' . $key . ':</td><td><input type="text" name="field_' . $i . '_' . $key . '" value="' . $value . '" /></td><td><input type="checkbox" name="md5_' . $i . '_' . $key . '" /></td></tr>';
}
}
echo '<tr><td><input type="submit" name="modify" value="Submit" /></td><td colspan="2">Back</td></tr></table></form>';
exit;
}
}
// -----------------SEARCH-----------------
echo '<br><form method="post">Search: <input type="text" name="filter" value="' . ((isset($_POST['filter'])) ? $_POST['filter'] : '') . '"/><br/>Filter by: <br/>';
for($i = 0;$i < count($fields);$i++) echo '<input type="checkbox" name="' . $fields[$i] . '"' . ((isset($_POST['filter']) && isset($_POST[$fields[$i]])) ? ' checked' : '') . '/>' . $fields[$i] . ' ';
echo '</form><form method="post"><table border="1" cellpadding="7"><tr>';
for($i = 0;$i < count($fields);$i++) echo '<th>' . $fields[$i] . '</th>';
echo '<th>-</th></tr>';
$sql = "SELECT * FROM " . $table;
if(isset($_POST['filter'])){
$filter = mysqli_real_escape_string($conn, $_POST['filter']);
foreach($fields as $key => $value) if(!isset($_POST[$fields[$key]])) unset($fields[$key]);
if(count($fields) > 0){
$first = true;
foreach($fields as $key => $value){
$sql .= " " . (($first) ? "WHERE" : "OR") . " " . $value . " LIKE '%" . $filter . "%'";
$first = false;
}
}
}
// -----------------Bottoms (Above table)-----------------
echo '<input type="submit" name="action" value="Modify" /> <input onclick="return confirm(\'Are you sure you want to delete these rows?\')" type="submit" name="action" value="Delete" /> <input type="submit" name="action" value="Insert" /><br><br></form>';
$_SESSION['store'] = array();
$q = mysqli_query($conn, $sql) or die(mysqli_error($conn));
while($r = mysqli_fetch_assoc($q)){
echo '<tr>';
foreach($r as $key => $value) echo '<td>' . $value. '</td>';
echo '<td><input type="checkbox" name="rows[]" value="' . count($_SESSION['store']) . '" /></td></tr>';
$_SESSION['store'][count($_SESSION['store'])] = $r;
}
// -----------------Bottoms (Below table)-----------------
echo '</table>';
//echo '<br><input type="submit" name="action" value="Modify" /> <input onclick="return confirm(\'Are you sure you want to delete these rows?\')" type="submit" name="action" value="Delete" /> <input type="submit" name="action" value="Insert" /></form>';
?>
<br>
// -----------------Pagination-----------------
<br>
<?php
$start=0;
$limit=50;
if(isset($_GET['page']))
{
$page=$_GET['page'];
$start=($page-1)*$limit;
}
else{
$page=1;
}
//Fetch from database first 10 items which is its limit. For that when page open you can see first 10 items.
$query=mysqli_query($conn,"select * from $table LIMIT $start, $limit");
?>
<?php
//print 10 items
while($result=mysqli_fetch_array($query))
{
//echo "<li>".$result['username']."</li>";
}
?>
<?php
//fetch all the data from database.
$rows=mysqli_num_rows(mysqli_query($conn,"select * from $table"));
//calculate total page number for the given table in the database
$total=ceil($rows/$limit);
if($page>1)
{
//Go to previous page to show previous 10 items. If its in page 1 then it is inactive
echo 'PREVIOUS';
}
if($page!=$total)
{
////Go to previous page to show next 10 items.
echo 'NEXT';
}
?>
<?php
//show all the page link with page number. When click on these numbers go to particular page.
for($i=1;$i<=$total;$i++)
{
if($i==$page) { echo "<li class='current'>".$i."</li>"; }
else { echo '<li>'.$i.'</li>'; }
}
?>
You have error on html URL syntax
echo 'NEXT';
The correct would be
echo 'NEXT';
You have to use ? only for the first URL parameter, & for the following, if any.

how to update an array from input box in php mysql

This is my code:
$uid=$_POST['uid'];
$fields = '';
if($uid==1){
//having some error in this line
foreach($query as $key => $value) {
if ($i++ != 0) $fields .= ', ';
$key = mysql_real_escape_string($key);
$value = mysql_real_escape_string($value);
$fields .= "$key = $value";
}
$query = mysql_query("UPDATE 2mcom SET $fields");
}
echo "<table>" ;
$result = mysql_query("select * from 2mcom where roll_no='138218600004'");
$i=1;
while (false != ($data = mysql_fetch_array($result, MYSQL_ASSOC)))
foreach ($data as $key => $value)
//echo "$key: $value <br />";
{
echo "<tr><td>";
echo "$key: ";
echo "</td>";
echo '<form method="post" action="">';
echo "<td>";
echo '<input type="text" name="fld'.$i.'" value="'.$value.'"/>';
echo '<input type="hidden" name="uid" value="1"/>';
$i++;
echo "</td></tr>";
}
echo "<tr><td>";
echo'<input type="submit" name="submit" value="submit"/>';
echo "</tr></td>";
echo'</form></table>';
I want to update this table 2mcom from the input text-box. Here i am fetching the field-name along with their values in input field from table "2mcom" using array.. now i want to update the field after editing.it is for result correction .
This should give your text field a name, then you can do separate UPDATE queries to update each field individually.
UPDATE, consolidated version of previous code:
$i = 0;
while($row = mysqli_fetch_assoc($result)) {
foreach($row as $key => $value) {
$name = 'field';
$id = $row['id']; //rename this with your row id, this will give you identifiable input names
echo '<tr><td>';
echo $key . ': ';
echo '</td>';
echo '<form method="POST">';
echo '<td>';
echo '<input type="hidden" name="id[]" value="'. $row['id'] .'"/>';
echo '<input type="hidden" name="column[]" value="'. $key .'"/>';
echo '<input type="text" name="field[]" value="'. $value .'"/>';
echo '</td></tr>';
}
$i++;
}
UPDATE QUERY:
function update_table($table, $col, $value, $id) {
global $link; //mysqli object
//escape values
$value = mysqli_real_escape_string($link, $value);
$col = mysqli_real_escape_string($link, $col);
//update the database field
$query = "UPDATE `$table` SET `$col` = '$value' WHERE `roll_id` = '$id'";
mysqli_query($link, $query) or die(mysqli_error($link));
return true;
}
CONTROLLER:
if(isset($_POST['submit'])) {
$col_count = count($_POST['column']);
$field_count = count($_POST['field']);
if($field_count == $col_count) {
} else {
trigger_error("Col - Field mismatch", E_USER_ERROR);
}
for($i=0; $i<count($_POST['column']); $i++) {
if(!update_table($table, $_POST['column'][$i], $_POST['field'][$i], $_POST['id'][$i])) {
trigger_error("Error updating field", E_USER_ERROR);
}
}
}
Try that.

Retrieve checkbox options after submit

I am building this function which echo-s all table fields and has a checkbox along with it.
I need to print this fields after submission, i have this code, and no i haven't started something, not because i don't want but because i don't have any idea how to.. so i'm asking your help.
I need to print information in report.php please help.
<form action='report.php' method='post'>
<?php // Script 12.7 - sopping.php
$db = mysql_connect('localhost', 'root', '');
mysql_select_db('db_up', $db);
echo "<table border='1' class='tabtext'>";
$result = mysql_query("SELECT * FROM hostess");
$numrows = mysql_num_rows($result);
$numfields = mysql_num_fields($result);
// show headers
echo '<thead><tr>';
for ($field = 0; $field < $numfields; $field++) {
$field_name = mysql_field_name($result, $field); // instead of $i
echo '<th><label><input type="checkbox" name="checkbox[' . $field_name . '][]" value="1"/> ' . $field_name . '</label></th>';
}
echo '</tr></thead>';
echo '<tbody>';
for ($row = 0; $row < $numrows; $row++) {
$data = mysql_fetch_assoc($result);
echo '<tr>';
for ($field = 0; $field < $numfields; $field++) {
$field_name = mysql_field_name($result, $field);
if (isset($_POST['checkbox'][$field_name])) {
echo '<td>' . $data[$field_name] . '</td>';
}
}
echo '</tr>';
}
echo '</tbody>';
echo '</table>';
?>
<input type='submit' value='Submit' />
</form>
The report.php
<?php // Script 12.7 - sopping.php
$db = mysql_connect('localhost', 'root', '');
mysql_select_db('db_up', $db);
foreach($_POST['checkbox'] as $key => $value)
?>
Try this one:
if(isset($_POST['Submit'])) {
echo "<pre>";
$checked = implode(',', $_POST['checkbox']);
echo $checked;
}

html table to display php photo gallery

I need to display a photo gallery in a table, I want five pictures on each line, but can't find the way to insert </tr><tr> after each fifth picture.
Here's my code:
<?php
// table name
$tbl_name=gallery1;
$sql="SELECT * FROM $tbl_name";
$result=mysql_query($sql);
while($rows= mysql_fetch_assoc($result)){
$id = $rows['id'];
$path = $rows['path'];
$image_name = $rows['image_name'];
$title = $rows['title'];
?>
<img src="<?php echo $path."/".$image_name;?>" height="120"/>Name:<?php echo $title;?>
<?php
echo "<form action='pictry.php' enctype='multipart/form-data' method='post'>
<input name='file[]' type='hidden' value='".$image_name."' />
<input name='id' type='hidden' id='id' value='".$id."'/>
<input type='submit' name='button' id='button' value='Delete Picture' /></form>";
}
?>
Replace the line
while($rows= mysql_fetch_assoc($result)){
with
for($i = 0; $rows= mysql_fetch_assoc($result); ++$i) {
Then you place something like this into the for loop.
if($i % 5 == 0) { /* insert stuff */ }
Untested Code
<?php
$perrow = 5;
$i = 0;
echo '<table>';
echo '<tr>';
while($rows = mysql_fetch_assoc($result)) {
echo '<td><img src=[grapresultfromrows] /></td>';
++$i;
if($i == $perrow) {
$i = 0;
echo '</tr>';
echo '<tr>';
}
}
// If not a multiple of $perrow you need to add extra cells
for($i; $i < $perrow; ++$i) {
echo '<td></td>';
}
echo '</tr>';
echo '</table>';
?>

Categories