PHP For loop issue with Mysqli - php

I'm trying to get this PHP script to paginate the data pulled from the mysql database.
It is going wrong somewhere in the second for loop. Instead of pulling the data through it is just returning blank or empty fields.
I need it to display the title, description and content fields from the database, along with the ID.
require_once("../controls/config.php");
$connection = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if ($connection->connect_errno) {
printf("Connect failed: %s\n", $connection->connect_error);
exit();
}
// number of results to show per page
$per_page = 3;
// figure out the total pages in the database
$result = $connection->query("SELECT * FROM pages");
$total_results = $result->num_rows;
$total_pages = ceil($total_results / $per_page);
// check if the 'page' variable is set in the URL (ex: view-paginated.php?page=1)
if (isset($_GET['page']) && is_numeric($_GET['page']))
{
$show_page = $_GET['page'];
// make sure the $show_page value is valid
if ($show_page > 0 && $show_page <= $total_pages)
{
$start = ($show_page -1) * $per_page;
$end = $start + $per_page;
}
else
{
// error - show first set of results
$start = 0;
$end = $per_page;
}
}
else
{
// if page isn't set, show first set of results
$start = 0;
$end = $per_page;
}
for ($i = 1; $i <= $total_pages; $i++)
{
echo "<a href='?page=$i'>$i</a><br>";
}
// loop through results of database query, displaying them in the table
for ($i = $start; $i < $end; $i++)
{
// make sure that PHP doesn't try to show results that don't exist
if ($i == $total_results) { break; }
echo $i["id"].' ';
echo $i["title"].' ';
echo $i["description"].' ';
echo $i["content"].' ';
echo 'Edit ';
echo 'Delete<br>';
}
?>
<p>Add a new record</p>
Can anyone point me in the right direction?

It looks like you are trying to treat $i as an associative array. Though $i is only a integer. Additionally, you do not have an array the contains the results from your mysqli query. You should try:
// this will loop through results and assign to $rows array
while($row = $result->fetch_array())
{
$rows[] = $row;
}
// this will loop through $rows array and provide each column result
foreach($rows as $row)
{
echo $row["id"];
echo $row["title"];
echo $row["description"];
echo $row["content"];
}
For further information please refer to: http://us2.php.net/mysqli_fetch_array

Related

How do I display content with PDO based on num_rows?

Apparently, the num_rows property does not work in PDO as it would with mysqli.
Normally, with mysqli, my code would look like this:
<?php
$conn = new mysqli('127.0.0.1','root','mypassword','mydbname');
if($conn->connect_errno){
die("Sorry, could not connect.");
}
$id = 1;
$qry = "SELECT * FROM customers WHERE id = ?";
$getCustomers = $conn->prepare($qry);
$getCustomers->bind_param("i",$id);
$getCustomers->execute();
$result = $getCustomers->get_result();
$count = $result->num_rows;
if($count == 0){
echo "Sorry, there are no results";
}else{
while($row = $result->fetch_object()){
echo $row->id;
echo $row->fname;
echo $row->lname;
echo $row->entry_date;
}
}
?>
How do I create the equivalent with PDO? Here is what I have tried so far:
<?php
try{
$conn = new PDO('mysql:host=127.0.0.1;dbname=mydbname','root','mypassword');
}catch(PDOException $e){
echo $e;
}
$id = 1;
$qry = $conn->prepare("SELECT * FROM customers WHERE id = :id");
$qry->execute([':id'=>$id]);
$rows = $qry->fetchAll(PDO::FETCH_OBJ);
$count = count($rows);
if($count == 0){
echo "Sorry, there are no results for your criteria";
}else{
for($i = 0; $i < $count; $i++){
echo $rows->fname;
}
}
?>
Yeah isn't PDO great ;p no need to count rows when you have already got them.
To loop over your result as you have an array.
Change:
for ($i = 0; $i < $count; $i++){
echo $rows->fname;
}
To:
for ($i = 0; $i < $count; $i++){
echo $rows[$i]->fname;
}
Or better just use a foreach.
foreach ($rows as $row) {
echo $row->fname;
}
The statement
fetchAll(PDO::FETCH_OBJ) returns an array containing all of the result set rows as described here. To get the size of the array use sizeof($count). That should give you the size of the array.
To answer your question specifically. You can use rowCount() to retrieve the number of rows in a result:
$qry = $conn->prepare("SELECT * FROM customers WHERE id = :id");
$qry->execute([':id'=>$id]);
$count = $qry->rowCount();
$rows = $qry->fetchAll(PDO::FETCH_ASSOC); //my personal preference
for($i=0; $i < $count; $i++) {
echo $rows[$i]['fname'];
}
To more closely replicate your mysqli code:
while($row = $qry->fetch(PDO::FETCH_OBJ) {
echo $row->fname;
}
Of course, you should always check $conn->errorCode() after each database execution to ensure something go sideways on you.
UPDATE:
As Lawrence points out, rowCount() does not work with MS SQL Server. An alternative in that case is to use fetchAll() and count().

JSON pagination blank after include few page

Config.php
<?php
define('HOST','localhost');
define('USER','root');
define('PASS','mypass');
define('DB','db_news');
$con = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect');
?>
Listnews.php
<?php
include'con_db.php';
if (isset($_GET['page']) && is_numeric($_GET['page'])) {
$page= (int) $_GET['page'];
} else {
$page= 1;
}
$all_row = "SELECT COUNT(*) FROM berita";
$data_page = mysqli_query($con, $all_row);
$r = mysqli_fetch_row($data_page);
$numrows = $r[0];
$rowsperpage = 10;
$totalpages = ceil($numrows / $rowsperpage);
//if current page is greater than total pages
if ($page > $totalpages) {
//set current page to last page
$page= $totalpages;
}
//if current page is less than first page
if ($page < 1) {
//set current page to first page
$page= 1;
}
// the offset of the list, based on current page
$offset = ($page - 1) * $rowsperpage;
$query = "SELECT * FROM berita order by id_berita DESC LIMIT $offset, $rowsperpage";
$result = mysqli_query($con, $query);
if(mysqli_num_rows($result)>0) {
$response["list_data"] = array();
while ($row = mysqli_fetch_assoc($result)) {
$temp = array("id" => $row["id_berita"],
"judul" => $row["judul"],
"isi" => $row["isi_berita"],
"tgl" => $row["tanggal"].' '.$row["jam"],
"dibaca" => $row["dibaca"].' Dibaca',
"url_berita" => $row["judul_seo"],
"gambar" => $row["gambar"]);
array_push($response["list_data"], $temp);
}
if($result){
$response["success"] = 1;
$response["message"] = "Successfully Displayed";
$response["page"] = $page;
$response["total_pages"] = $totalpages;
$data = json_encode($response);
echo $data;
}
else{
$response["success"] = 0;
$response["message"] = "Try Again";
$response["page"] = $page;
$response["total_pages"] = $totalpages;
$data = json_encode($response);
echo $data;
}
}else{
$response["success"] = 2;
$response["message"] = "No Details Found";
$response["page"] = $page;
$response["total_pages"] = $totalpages;
$data = json_encode($response);
echo $data;
}
/*
**$data = json_encode($response);
**echo $data;
*/
?>
after test with postman myhost/news/berita.php?page=1,2,3,4,5,6 it showing json data.
showing json data with page 1-6
then i include page 7 myhost/news/berita.php?page=7 its blank
after incluse page 7
please help me sir, i'm sorry for bad my language
finally done my problem, just add utf8ize function
function utf8ize($d) {
if (is_array($d)) {
foreach ($d as $k => $v) {
$d[$k] = utf8ize($v);
}
} else if (is_string ($d)) {
return utf8_encode($d);
}
return $d;
}
and use it for json_encode
$response["success"] = 1;
$response["message"] = "Successfully Displayed";
$response["page"] = $halaman;
$response["total_pages"] = $totalpages;
$data = json_encode(utf8ize($response));
echo $data;

i wrote some code for fetch data from database ,in mysql code is working and in pdo it is not working

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 );

Passing Multiple Variables Through Pages PHP MYSQL

The following code is working fine for the first page. It is a query based on user input from a form. I have 2 issues. The first one is when i click next page i get undefined index and undefined variable error which means the variables are not passed. The second question is how can i make a query and paginate it based on the user filled/selected values in the form? Some users may not fill all the values.
Here is my code: NB: The form method is GET. I have tried REQUEST and POST too. All the same error. Thanks in advance guys.
<?php
if (isset($_POST['Submit']))
$name = mysql_real_escape_string($_GET['name']);
$email = mysql_real_escape_string($_GET['email']);
$age = mysql_real_escape_string($_GET['age']);
$height = mysql_real_escape_string($_GET['height']);
include_once "conn.php"; //connect to db and table
$rs = mysql_query("SELECT COUNT(*) FROM people WHERE name='$name' AND email='$email' AND age='$age' AND height='$height'");
$rw = mysql_fetch_array($rs);
$numrows = $rw[0];
if ($numrows== 0) die("No Results Found");
$rowsperpage = 7;
$totalpages = ceil($numrows / $rowsperpage);
if (isset($_GET['currentpage']) && is_numeric($_GET['currentpage'])) {
$currentpage = (int) $_GET['currentpage'];
} else {
$currentpage = 1;
}
if ($currentpage > $totalpages) {
$currentpage = $totalpages;
}
if ($currentpage < 1) {
$currentpage = 1;
}
$offset = ($currentpage - 1) * $rowsperpage;
$query = mysql_query("SELECT * FROM people WHERE name='$name' AND email='$email' AND age='$age' AND height='$height' ORDER BY time DESC LIMIT $offset, $rowsperpage");
//print my tables here
while($row = mysql_fetch_array($query))
{
$uniqueid = $row['age'];
//output stuff here
}
//close sql
$range = 3;
if ($currentpage > 1) {
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=1&name=$name&email=$email&age=$age&height=$height'> Go To Page 1</a> ";
$prevpage = $currentpage - 1;
echo "<a href='{$_SERVER['PHP_SELF']}?currentpage=$prevpage&name=$name&email=$email&age=$age&height=$height'> Previous Page</a>";
}
for ($x = ($currentpage - $range); $x < (($currentpage + $range) + 1); $x++) {
if (($x > 0) && ($x <= $totalpages)) {
if ($x == $currentpage) {
echo " <font size=4 color=red>[<b>$x</b>] </font>";
} else {
echo "<a href='{$_SERVER['PHP_SELF']}?currentpage=$x&name=$name&email=$email&age=$age&height=$height'>$x</a>";
}
}
}
if ($currentpage != $totalpages) {
$nextpage = $currentpage + 1;
echo "<a href='{$_SERVER['PHP_SELF']}?currentpage=$nextpage&name=$name&email=$email&age=$age&height=$height'>Next Page</font></a>";
echo "<a href='{$_SERVER['PHP_SELF']}?currentpage=$totalpages&name=$name&email=$email&age=$age&height=$height'>Last Page</a> ";
}
?>
The form submits as GET. Because this one, the POST variable isn't set. And you're not defining the first variable (missing brackets?). Furthermore, Submit is the only submitted value with a capital. Is this intentional?
if (isset($_GET['Submit'])) {
$name = mysql_real_escape_string($_GET['name']);
$email = mysql_real_escape_string($_GET['email']);
$age = mysql_real_escape_string($_GET['age']);
$height = mysql_real_escape_string($_GET['height']);
}
More ideally, because you want to ommit values, you'll probably want to check each variable individually for existence. And if it's not set (or empty), don't add that field in your WHERE clause.
$name = isset($_GET['name']) ? mysql_real_escape_string($_GET['name']) : null;
// ... process the other fields in same way ...
or spanned over multiple lines: EDIT: just noticed I was missing a closing ) in the two blocks below.
$name = null;
if (isset($_GET['name'])) {
$name = mysql_real_escape_string($_GET['name']);
}
// ... process the other fields in same way ...
or even:
$name = null;
if (isset($_GET['name']))
$name = mysql_real_escape_string($_GET['name']);
// ... process the other fields in same way ...
Dynamic query
Then, make your query a bit more dynamic. Like, adding all your available WHERE parameters to an array. It makes things easier.
// Store conditions in array
$whereConditions = array();
if (!empty($name)) {
$whereConditions['name'] = $name;
}
if (!empty($email)) {
$whereConditions['email'] = $email;
}
if ($age && $age > 0) {
$whereConditions['age'] = $age;
}
if ($height && $height > 0) {
$whereConditions['height'] = $height;
}
// Start building your query dynamically
$query = 'SELECT * FROM people';
// Making things easier here. Just flatten your array down.
$conditions = array();
foreach ($whereConditions as $field => $value) {
$conditions[] = sprintf("%s = '%s'", $field, $value);
}
// Join all conditions with AND
$where = implode(' AND ', $conditions);
// Add where clause, if there are conditions
if (!empty($where)) {
$query .= ' WHERE ' . $where;
}
$query .= " ORDER BY time DESC LIMIT {$offset}, {$rowsperpage}";
Final notes
Keep in mind to use prepared queries if you're allowing user input. And the mysql_ extension is deprecated. Switch to mysqli_ or PDO.

MySQLi not returning rows in order

This is probably not a very difficult question to answer. I'm having trouble with this PHP function I wrote... it returns the rows line by line, but it's returning them incremented by 4 each time. So the the 1st row will output, then the 5th, then the 9th...
function showDatabases() {
# $_GET variables from the URL.
$database = mysql_real_escape_string($_GET['database']);
$table = mysql_real_escape_string($_GET['table']);
$mysqli = new mysqli('127.0.0.1', 'root', '', $database);
$query_one = $mysqli->query("SELECT * from $table");
$num_rows = mysqli_num_rows($query_one);
$num_fields = mysqli_num_fields($query_one);
for ($x = 0; $x < $num_rows; $x++) {
for ($c = 0; $c < $num_fields; $c++) {
$row = mysqli_fetch_row($query_one);
echo($row[$c]." ");
}
echo("<br/>");
}
}
Thanks!
mysqli_fetch_row fetched an entire row and moves the pointer to the following row. You should call it only once per each row; now you are calling it once per column.
That is,
for ($x = 0; $x < $num_rows; $x++) {
$row = mysqli_fetch_row($query_one);
for ($c = 0; $c < $num_fields; $c++) {
echo($row[$c]." ");
}
echo("<br/>");
}
you are complicating things
you can do it with just one loop
$query = "SELECT * from $table";
if ($result = $mysqli->query($query)) {
while ($row = $result->fetch_assoc()) {
echo $row['fieldname']." ";
}
}
I advice you to add order by some time the default order is not the id order.

Categories