I want to create a function so that I won't repeat myself.
This is my current code
<?php
$targetpage = "index.php";
$limit = 20;
$sql1 = $db->prepare("SELECT * FROM classified ORDER BY date DESC");
/*** fetch Number of results ***/
$total_pages =$sql1->rowCount();
$stages = 3;
$page = ($_GET['page']);
if($page){
$start = ($page - 1) * $limit;
}else{
$start = 0;
}
$sql = $db->prepare("SELECT * FROM classified ORDER BY date DESC LIMIT $start,
$limit ")or die(print_r($sql->errorInfo(), true));
$sql->execute();
$result = $sql->fetchAll();
//Include pagination
require_once("pagination.php");
// pagination
echo $paginate;
foreach($result as $row){
$id = htmlentities($row['id'], ENT_QUOTES);
$id_city = htmlentities($row['id_city'], ENT_QUOTES);
$title = htmlentities($row['title'], ENT_QUOTES ,'utf-8');
$querya = $db->prepare("SELECT * FROM city WHERE id = :id_city");
/*** bind the paramaters ***/
$querya->bindParam(':id_city', $id_city, PDO::PARAM_INT);
/*** execute the prepared statement ***/
$querya->execute();
/*** fetch the results ***/
$resultya = $querya->fetchAll();
foreach($resultya as $rowa)
{
$city_name = htmlentities($rowa['city'], ENT_QUOTES, 'utf-8');
}
}
?>
Now I have another file that uses the same code except it has a condition when retrieving data from database.
So instead of:
$sql1 = $db->prepare("SELECT * FROM classified ORDER BY date DESC");
$sql = $db->prepare("SELECT * FROM classified ORDER BY date DESC LIMIT $start,
$limit ")or die(print_r($sql->errorInfo(), true));
The other file:
$sql1 = $db->prepare("SELECT * FROM classified where type = '1' ORDER BY date DESC");
$sql = $db->prepare("SELECT * FROM classified where type = '1' ORDER BY date DESC
LIMIT $start, $limit ")or die(print_r($sql->errorInfo(), true));
The difference is where type = 1
Is it possible to combine all this in one function?
Thanks
I added some notes into the code, does this make sense?
See below:
<?php
/*
$db - PDO object
$limit - number of listings to show on the page
$page - page to show
$where - the additional where condition to pass in
*/
function getItems($db=null,$limit=20,$page='',$where='') {
// check if $db exists before doing anything
if ($db) {
$sql1 = $db->prepare("SELECT * FROM classified ORDER BY date DESC");
/*** fetch Number of results ***/
$total_pages =$sql1->rowCount();
$stages = 3;
if($page){
$start = ($page - 1) * $limit;
}else{
$start = 0;
}
$sql = $db->prepare("SELECT * FROM classified $where ORDER BY date DESC LIMIT $start,
$limit ")or die(print_r($sql->errorInfo(), true));
$sql->execute();
$result = $sql->fetchAll();
} else {
// I return an empty array here so that if something should fail $result will still be populated with an array
return array();
}
}
$targetpage = "index.php";
$result = getItems($db,20,$_GET['page'],'where type = "1"');
//Include pagination
require_once("pagination.php");
// pagination
echo $paginate;
foreach($result as $row){
$id = htmlentities($row['id'], ENT_QUOTES);
$id_city = htmlentities($row['id_city'], ENT_QUOTES);
$title = htmlentities($row['title'], ENT_QUOTES ,'utf-8');
$querya = $db->prepare("SELECT * FROM city WHERE id = :id_city");
/*** bind the paramaters ***/
$querya->bindParam(':id_city', $id_city, PDO::PARAM_INT);
/*** execute the prepared statement ***/
$querya->execute();
/*** fetch the results ***/
$resultya = $querya->fetchAll();
foreach ($resultya as $rowa) {
$city_name = htmlentities($rowa['city'], ENT_QUOTES, 'utf-8');
}
}
?>
Yes. Have one file and either send a POST or GET to it that tells the page if type==1.
Example
if ($_GET['t']==1){ $type = "WHERE type = '1'"; }else{ $type = ""; }
$sql1 = $db->prepare("SELECT * FROM classified " . $type . " ORDER BY date DESC");
$sql = $db->prepare("SELECT * FROM classified " . $type . " ORDER BY date DESC
LIMIT $start, $limit ")or die(print_r($sql->errorInfo(), true));
If you call the page this is listed on with page.php?t=1, then it will put the where statement in there. If you just call page.php, it will not put anything there.
Related
I created this simple filter for date interval, and different levels (0,1,2). I have this code so far:
if(isset($_POST['filtersubmit'])){
$datex = str_replace('/', '-', $_POST['firstdate']);
$date1 = date("Y-m-d", strtotime($datex));
$datey = str_replace('/', '-', $_POST['lastdate']);
$date2 = date("Y-m-d", strtotime($datey));
$projects = $_POST['projekt'];
if(isset($date1) && isset($date2)){
$query = mysqli_query($conn, "SELECT * FROM zapasy WHERE datum BETWEEN
'$date1' AND '$date2' ORDER BY id DESC");
}
if($projects == 0){
$query = mysqli_query($conn, "SELECT * FROM zapasy WHERE projekt = '0' ORDER BY id DESC") or die(mysqli_errno($conn). '-'. mysqli_error($conn));
} elseif($projects == 1){
$query = mysqli_query($conn, "SELECT * FROM zapasy WHERE projekt = '1' ORDER BY id DESC") or die(mysqli_errno($conn). '-'. mysqli_error($conn));
} elseif($projects == 2){
$query = mysqli_query($conn, "SELECT * FROM zapasy WHERE projekt = '2' ORDER BY id DESC") or die(mysqli_errno($conn). '-'. mysqli_error($conn));
}
}
Now if I select just one of these filters, it works good, but if I want both interval and level filters, it doesn't work. I am not really sure how to do it. I am really grateful for any help.
I would use something along these lines, using a prepared statement to protect you from SQL injection. Basically we form arrays of WHERE clauses, parameters and parameter types from each filter if it is present in the $_POST array. These are then imploded into the query, parameters are bound and the query executed.
if (isset($_POST['filtersubmit'])) {
$params = array();
$paramtypes = array();
$wheres = array();
if (isset($_POST['firstdate'], $_POST['lastdate'])) {
$date1 = date_create_from_format('m/d/Y', $_POST['firstdate']);
$date2 = date_create_from_format('m/d/Y', $_POST['lastdate']);
if (!empty($date1) && !empty($date2)) {
array_push($params, $date1->format('Y-m-d'), $date2->format('Y-m-d'));
array_push($paramtypes, 's', 's');
array_push($wheres, 'datum BETWEEN ? AND ?');
}
}
if (isset($_POST['projekt'])) {
$project = $_POST['projekt'];
if (is_numeric($project) && $project >= 0 && $project <= 2) {
array_push($params, $project);
array_push($paramtypes, 'i');
array_push($wheres, 'projekt = ?');
}
}
$sql = 'SELECT * FROM zapasy';
if (count($wheres)) {
$sql .= ' WHERE ' . implode(' AND ', $wheres);
}
$sql .= ' ORDER BY id DESC';
$stmt = $conn->prepare($sql) or die($conn->error);
if (count($wheres)) {
$stmt->bind_param(implode('', $paramtypes), ...$params);
}
$stmt->execute() or die($stmt->error);
// bind results
$stmt->bind_result(/* variables corresponding to each field in SELECT */);
while ($stmt->fetch()) {
// do something with the data
}
}
This is mysql connection coding, it is working fine
the same code i wrote with pdo connection,it is not working i'm new to php please help me to get out of this problem.
thanks in advance
<?php
error_reporting(0);
ini_set('max_execution_time', 600);
require_once 'config.php';
if(isset($_GET["nm_mask"]))
$nm_mask = $_GET['nm_mask'];
else
$nm_mask = "";
if(isset($_GET["cd_mask"]))
$cd_mask = $_GET['cd_mask'];
else
$cd_mask = "";
if(isset($_GET["func"]))
$func = $_GET['func'];
else
$func = "";
$where = "WHERE 1=1";
if($nm_mask!='')
$where.= " AND Login LIKE '$nm_mask%'";
if($cd_mask!='')
$where.= " AND Manager_Login LIKE '$cd_mask%'";
if($func!='')
$where.= " AND Function LIKE '$func%'";
$page = $_GET['page']; // get the requested page
$limit = $_GET['rows']; // get how many rows we want to have into the grid
$sidx = $_GET['sidx']; // get index row - i.e. user click to sort
$sord = $_GET['sord']; // get the direction
if(!$sidx) $sidx =1; // connect to the database
$result = mysqli_query("SELECT COUNT(*) AS count FROM EmpMasterTB ".$where);
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
$count = $row['count'];
if( $count >0 ) {
$total_pages = ceil($count/$limit);
} else {
$total_pages = 0;
}
if ($page > $total_pages) $page=$total_pages;
if ($limit<0) $limit = 0;
$start = $limit*$page - $limit; // do not put $limit*($page - 1)
if ($start<0) $start = 0;
$SQL = "SELECT * from EmpMasterTB ". $where ." ORDER BY $sidx $sord LIMIT $start , $limit";
$result = mysqli_query( $SQL ) or die("Couldn?t execute query.".mysqli_error());
$responce->page = $page;
$responce->total = $total_pages;
$responce->records = $count;
$i=0;
while($row = mysqli_fetch_array($result,MYSQLI_ASSOC)) {
$responce->rows[$i]['id']=$row[WeekNo].$row[Login];
$responce->rows[$i]['cell']=array($row['WeekNo'],$row['WeekBeginning'],$row['SITE'],$row['Name'],$row['WFH'],$row['Login'],$row['Manager_Login'],$row['Lead'],$row['Cost_center'],$row['Business_Title'],$row['Function'],$row['Workgroup'],$row['Login_time'],$row['ROLE'],$row['Secondary_Skill'],$row['Weekoff'],""); $i++;
}
echo json_encode($responce);
?>
PDO connection code
<?php
error_reporting(0);
ini_set('max_execution_time', 600);
require_once 'config.php';
if(isset($_GET["nm_mask"]))
$nm_mask = $_GET['nm_mask'];
else
$nm_mask = "";
if(isset($_GET["cd_mask"]))
$cd_mask = $_GET['cd_mask'];
else
$cd_mask = "";
if(isset($_GET["func"]))
$func = $_GET['func'];
else
$func = "";
$where = "WHERE 1=1";
if($nm_mask!='')
$where.= " AND Login LIKE '$nm_mask%'";
if($cd_mask!='')
$where.= " AND Manager_Login LIKE '$cd_mask%'";
if($func!='')
$where.= " AND Function LIKE '$func%'";
$page = $_GET['page']; // get the requested page
$limit = $_GET['rows']; // get how many rows we want to have into the grid
$sidx = $_GET['sidx']; // get index row - i.e. user click to sort
$sord = $_GET['sord']; // get the direction
if(!$sidx) $sidx =1; // connect to the database
$count = $dbh->exec("SELECT COUNT(*) AS count FROM EmpMasterTB ".$where);
if( $count >0 ) {
$total_pages = ceil($count/$limit);
} else {
$total_pages = 0;
}
if ($page > $total_pages) $page=$total_pages;
if ($limit<0) $limit = 0;
$start = $limit*$page - $limit; // do not put $limit*($page - 1)
if ($start<0) $start = 0;
$SQL = "SELECT * from EmpMasterTB ". $where ." ORDER BY $sidx $sord LIMIT $start , $limit"; /*** The SQL SELECT statement ***/
$stmt = $dbh->query($SQL); /*** fetch into an PDOStatement object ***/
$responce->page = $page;
$responce->total = $total_pages;
$responce->records = $count;
$i=0;
/*** echo number of columns ***/
$obj = $stmt->fetch(PDO::FETCH_OBJ);
/*** loop over the object directly ***/
{
$responce->rows[$i]['id']=$obj->WeekNo.$obj->Login;
$responce->rows[$i]['cell']=array($obj->WeekNo ,$obj->WeekBeginning ,$obj->SITE ,$obj->Name ,$obj->WFH ,$obj->Login ,$obj->Manager_Login ,$obj->Lead ,$obj->Cost_center ,$obj->Business_Title ,$obj->Function ,$obj->Workgroup ,$obj->Login_time ,$obj->ROLE ,$obj->Secondary_Skill ,$obj->Weekoff ); $i++;
}
echo json_encode($ );
?>
You have missed for loop and you didn't pass response in json_encode().
Please check my below code:
/*** echo number of columns ***/
$objs = $stmt->fetch(PDO::FETCH_OBJ);
/*** loop over the object directly ***/
foreach($objs as $obj)
{
$responce->rows[$i]['id']=$obj->WeekNo.$obj->Login;
$responce->rows[$i]['cell']=array($obj->WeekNo ,$obj->WeekBeginning ,$obj->SITE ,$obj->Name ,$obj->WFH ,$obj->Login ,$obj->Manager_Login ,$obj->Lead ,$obj->Cost_center ,$obj->Business_Title ,$obj->Function ,$obj->Workgroup ,$obj->Login_time ,$obj->ROLE ,$obj->Secondary_Skill ,$obj->Weekoff ); $i++;
}
echo json_encode($responce );
I'm having a hard time getting this search results with pagination code to work. It does successfully grab the search keyword entered in the html form on another page and brings it into this search.php page. if I echo $search I see the keyword on the page. But I get no results even though I should for the query. Can anyone see what might be going on?
require "PDO_Pagination.php";
if(isset($_REQUEST["search_text"]) && $_REQUEST["search_text"] != "")
{
$search = htmlspecialchars($_REQUEST["search_text"]);
$pagination->param = "&search=$search";
echo $search;
$pagination->rowCount("SELECT * FROM stories WHERE stories.genre = $search");
$pagination->config(3, 5);
$sql = "SELECT * FROM stories WHERE stories.genre = $search ORDER BY SID ASC LIMIT $pagination->start_row, $pagination->max_rows";
$query = $connection->prepare($sql);
$query->execute();
$model = array();
while($rows = $query->fetch())
{
$model[] = $rows;
}
}
else
{
$pagination->rowCount("SELECT * FROM stories");
$pagination->config(3, 5);
$sql = "SELECT * FROM stories ORDER BY SID ASC LIMIT $pagination->start_row, $pagination->max_rows";
$query = $connection->prepare($sql);
$query->execute();
$model = array();
while($rows = $query->fetch())
{
$model[] = $rows;
}
}
$query = "SELECT * FROM stories";
if(isset($_REQUEST["search_text"]) && $_REQUEST["search_text"] != "")
{
$search = htmlspecialchars($_REQUEST["search_text"]);
$pagination->param = "&search=$search";
$query .= " WHERE genre LIKE '%$search%'";
}
// No need for else statement.
$pagination->rowCount($query);
$pagination->config(3, 5);
$query .= " ORDER BY SID ASC LIMIT {$pagination->start_row}, {$pagination->max_rows}";
$stmt = $connection->prepare($query);
$stmt->execute();
$model = $stmt->fetchAll();
var_dump($model);
In your query do:
WHERE stories.genre LIKE '%string%');
instead of:
WHERE stories.genre = 'string');
Because the equals will want to literally equal the field.
<?php
require('db_info.php');
$recordsPerPage = 5;
if (isset($_GET['page']))
$curPage = $_GET['page'];
else
$curPage = 1;
$startIndex = ($curPage-1) * $recordsPerPage;
try {
$pdoObject = new PDO("mysql:host=$dbhost; dbname=$dbname;", $dbuser, $dbpass);
$sql = "SELECT count(id) FROM usercom";
$statement = $pdoObject->query($sql);
$record = $statement->fetch(PDO::FETCH_ASSOC);
$pages = ceil($record['count(id)']/$recordsPerPage);
$record=null;
$sql = "SELECT * FROM usercom LIMIT $startIndex, $recordsPerPage ORDER BY date DESC";
$statement = $pdoObject->query($sql);
while ( $record = $statement->fetch(PDO::FETCH_ASSOC) ) {
echo '<p>'.$record['date'].'<br/>'.$record['userComment'].'<br/>';
}
$statement->closeCursor();
$pdoObject = null;
} catch (PDOException $e) {
echo 'PDO Exception: '.$e->getMessage();
die();
}?></p>
I'm trying to fetch result from a database and use pagination. The problem is that the descending order asked in the statement never applies. Why isn't this working? If I don't add the line "ORDER BY date DESC" it works just fine, but when I do it prints error that I'm trying to fetch a non-object.
Your syntax isn't quite correct,
Use this one instead,
$sql = "SELECT * FROM `usercom` ORDER BY `date` DESC LIMIT $startIndex, $recordsPerPage";
I have PHP function which checks to see if variables are set and then adds them onto my SQL query. However I am don't seem to be getting any results back?
$where_array = array();
if (array_key_exists("location", $_GET)) {
$location = addslashes($_GET['location']);
$where_array[] = "`mainID` = '".$location."'";
}
if (array_key_exists("gender", $_GET)) {
$gender = addslashes($_GET["gender"]);
$where_array[] = "`gender` = '".$gender."'";
}
if (array_key_exists("hair", $_GET)) {
$hair = addslashes($_GET["hair"]);
$where_array[] = "`hair` = '".$hair."'";
}
if (array_key_exists("area", $_GET)) {
$area = addslashes($_GET["area"]);
$where_array[] = "`locationID` = '".$area."'";
}
$where_expr = '';
if ($where_array) {
$where_expr = "WHERE " . implode(" AND ", $where_array);
}
$sql = "SELECT `postID` FROM `posts` ". $where_expr;
$dbi = new db();
$result = $dbi->query($sql);
$r = mysql_fetch_row($result);
I'm trying to call the data after in a list like so:
$dbi = new db();
$offset = ($currentpage - 1) * $rowsperpage;
// get the info from the db
$sql .= " ORDER BY `time` DESC LIMIT $offset, $rowsperpage";
$result = $dbi->query($sql);
// while there are rows to be fetched...
while ($row = mysql_fetch_object($result)){
// echo data
echo $row['text'];
} // end while
Anyone got any ideas why I am not retrieving any data?
while ($row = mysql_fetch_object($result)){
// echo data
echo $row->text;
} // end while
I forgot it wasn't coming from an array!