Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
<?php
class dblib {
private $__conn;
function connect(){
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "webtintuc";
if (!$this->__conn){
try {
$this->__conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$this->__conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e){
echo "Error: " . $e->getMessage();
die();
}
}
}
function dis_connect(){
if ($this->__conn){
$this->__conn = null;
}
}
function insert($table, $data)
{
$this->connect();
$field_list = '';
$value_list = '';
foreach ($data as $key => $value){
$field_list .= ",$key";
$value_list .= ",'".$value."'";
}
$sql = 'INSERT INTO '.$table. '('.trim($field_list, ',').') VALUES ('.trim($value_list, ',').')';
$stmt = $this->__conn->prepare($sql);
return $stmt->execute();
}
function update($table, $data, $where){
$this->connect();
$sql = '';
foreach ($data as $key => $value){
$sql .= "$key = '".$value."',";
}
$sql = 'UPDATE '.$table. ' SET '.trim($sql, ',').' WHERE '.$where;
$stmt = $this->__conn->prepare($sql);
return $stmt->execute();
}
function remove($table, $where){
$this->connect();
$sql = "DELETE FROM $table WHERE $where";
$stmt = $this->__conn->prepare($sql);
return $stmt->execute();
}
function get_list($sql){
$this->connect();
$stmt = $this->__conn->prepare($sql);
$stmt->execute();
$stmt->setFetchMode(PDO::FETCH_ASSOC);
return $stmt->fetchALL();
}
function get_row($sql){
$this->connect();
$stmt = $this->__conn->prepare($sql);
$stmt->execute();
$stmt->setFetchMode(PDO::FETCH_ASSOC);
return $stmt->fetch();
}
function get_row_number($sql){
$this->connect();
$stmt = $this->__conn->prepare($sql);
$stmt->execute();
return $stmt->fetchColumn();
}
}
?>
###post.php
<?php
$link = '';
$where = '';
if (isset($_GET["cat"])) {
$cat = intval($_GET["cat"]);
if ($cat != 0)
$where = "WHERE category_id = $cat";
$link = "cat=$cat&";
}
$sql = "SELECT count(*) FROM posts $where";
$total_records = $homelib->get_row_number($sql);
$limit = 3;
$current_page = isset($_GET['page']) ? $_GET['page'] : 1;
$total_page = ceil($total_records / $limit);
if ($current_page > $total_page){
$current_page = $total_page;
}
else if ($current_page < 1) {
$current_page = 1;
}
$start = ($current_page - 1) * $limit;
$sql = "SELECT * FROM posts $where ORDER BY createdate DESC LIMIT $start, $limit";
$data = $homelib->get_list($sql);
?>
<!-- Blog Entries Column -->
<div class="col-md-8">
<h1 class="my-4">Siêu HOT
<small>tin mới nhất</small>
</h1>
<?php
for ($i = 0; $i < count($data); $i++) {
?>
<div class="card mb-4">
<img class="card-img-top" src="images/<?php echo $data[$i]['image'];?>" height="300px" alt="Card image cap">
<div class="card-body">
<h2 class="card-title"><?php echo $data[$i]['title'];?></h2>
<p class="card-text"><?php echo substr($data[$i]['content'], 0, 200).'...';?></p>
Xem thêm →
</div>
</div>
<?php
}
?>
<!-- Pagination -->
<ul class="pagination justify-content-center mb-4">
<?php
if ($current_page > 1 && $total_page > 1){
echo '<li class="page-item"><a class="page-link" href="index.php?'.$link.'page='.($current_page-1).'">Prev</a></li>';
}
for ($i = 1; $i <= $total_page; $i++) {
if ($current_page == $i)
echo '<li class="page-item disabled"><a class="page-link" href="#">'.$i.'</a></li>';
else
echo '<li class="page-item"><a class="page-link" href="index.php?'.$link.'page='.$i.'">'.$i.'</a></li>';
}
if ($current_page < $total_page && $total_page > 1){
echo '<li class="page-item"><a class="page-link" href="index.php?'.$link.'page='.($current_page+1).'">Next</a></li>';
}
?>
</ul>
</div>
result:
Fatal error
: Uncaught PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '-3, 3' at line 1 in C:\xampp\htdocs\webtintuc\incs\class_db.php:100 Stack trace: #0 C:\xampp\htdocs\webtintuc\incs\class_db.php(100): PDOStatement->execute() #1 C:\xampp\htdocs\webtintuc\post.php(30): dblib->get_list('SELECT * FROM p...') #2 C:\xampp\htdocs\webtintuc\index.php(8): include('C:\xampp\htdocs...') #3 {main} thrown in
C:\xampp\htdocs\webtintuc\incs\class_db.php
on line
100
The limit and start in an SQL query cannot be negative in any way. It is a number that is used for limiting the number of rows that should be returned by the SQL statement.
To be useful, the limit should always be an integer that is greater than zero. start should be any integer that is zero and up. It is refer to as the offset.
Your calculations are ending up producing a start that is set to -3. That will never work.
Make sure that you review your logic so that it does not produce a negative $start value.
You can quickly confirm my theory by calculating $start like this ...
$start = max(0, ($current_page - 1) * $limit);
This will ensure that the value will be 0 if your formula returns a negative value.
Bear in mind that this is not a permanent solution. You need to properly figure out the way you are computer the value of the $start value.
Related
This snippet works only when I make a connection with PDO but I want it with mysqli.-->link
<?php
//fetch_comment.php
//$connect = new PDO('mysql:host=localhost;dbname=tbl_comment', 'root', '');
$connect = mysqli_connect('localhost','root','','tbl_comment');
$query = "
SELECT * FROM tbl_comment
WHERE parent_comment_id = '0'
ORDER BY comment_id DESC
";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$output = '';
//
foreach($result as $row)
{
$output .= '
<div class="panel panel-default">
<div class="panel-heading">By <b>'.$row["comment_sender_name"].'</b> on <i>'.$row["date"].'</i></div>
<div class="panel-body">'.$row["comment"].'</div>
<div class="panel-footer" align="right"><button type="button" class="btn btn-default reply" id="'.$row["comment_id"].'">Reply</button></div>
</div>
';
$output .= get_reply_comment($connect, $row["comment_id"]);
echo $output;
}
function get_reply_comment($connect, $parent_id = 0, $marginleft = 0)
{
$query = "
SELECT * FROM tbl_comment WHERE parent_comment_id = '".$parent_id."'
";
$output = '';
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$count = $statement->rowCount();
if($parent_id == 0)
{
$marginleft = 0;
}
else
{
$marginleft = $marginleft + 48;
}
if($count > 0)
{
foreach($result as $row)
{
.....
.....
...
?>
I tried to use mysqli fetch_all
$statement = $connect ->prepare("SELECT * FROM tbl_comment
WHERE parent_comment_id = '0'
ORDER BY comment_id DESC");
$statement->execute();
$resultSet = $statement->get_result();
$result = $resultSet->fetch_all();
$output = '';
.....
$statement = $connect ->prepare("
SELECT * FROM tbl_comment WHERE parent_comment_id = '".$parent_id."'
");
$statement->execute();
$resultSet = $statement->get_result();
$result = $resultSet->fetch_all();
$count = $statement->num_rows();
$output = '';
but I am getting this messages:
Notice: Undefined index: comment_sender_name in C:\xampp\htdocs\tbl_comment\fetch_comment.php on line 46
Notice: Undefined index: date in C:\xampp\htdocs\tbl_comment\fetch_comment.php on line 46
Notice: Undefined index: comment in C:\xampp\htdocs\tbl_comment\fetch_comment.php on line 47
Notice: Undefined index: comment_id in C:\xampp\htdocs\tbl_comment\fetch_comment.php on line 48
Notice: Undefined index: comment_id in C:\xampp\htdocs\tbl_comment\fetch_comment.php on line 51
Update: Thanks to #Dharman when I use the MYSQLI_ASSOC it displays me the comments(first MySQL statement) but not the replies (second MySql statement).It worked on PDO. I also have a file to write a comment but when I change from PDO to mysqli it writes it two times in the database:
<?php
//add_comment.php
//$connect = new PDO('mysql:host=localhost;dbname=tbl_comment', 'root', '');
$connect=mysqli_connect('localhost','root','','tbl_comment');
$error = '';
$comment_name = '';
$comment_content = '';
if(empty($_POST["comment_name"]))
{
$error .= '<p class="text-danger">Name is required</p>';
}
else
{
$comment_name = $_POST["comment_name"];
}
if(empty($_POST["comment_content"]))
{
$error .= '<p class="text-danger">Comment is required</p>';
}
else
{
$comment_content = $_POST["comment_content"];
}
if($error == '')
{
$query = "
INSERT INTO tbl_comment
(parent_comment_id, comment, comment_sender_name)
VALUES (:parent_comment_id, :comment, :comment_sender_name)
";
$statement = $connect->prepare($query);
$statement->execute(
array(
':parent_comment_id' => $_POST["comment_id"],
':comment' => $comment_content,
':comment_sender_name' => $comment_name
)
);
$error = '<label class="text-success">Comment Added</label>';
}
$data = array(
'error' => $error
);
echo json_encode($data);
?>
Just use $result = $resultSet->fetch_all(MYSQLI_ASSOC);
By default fetch_all returns numerical array, but you want an associative array. Pass the constant as an argument to fetch_all
Hello my dear friends,
My goal is to paginate through my database entries, while using SQL_CALC_FOUND_ROWS and FOUND_ROWS, because I also have a search function
The search results are there, I just cannot paginate through them.
Probably my code is a total mess for the PHP Pros here, please don’t worry about commenting on that. Any help is greatly appreciated. I am just starting out on PHP and I am highly motivated to become a Pro one day as well.
What is it that I have to do in order to make the pagination work, so that I can paginate while having a search function on the page?
DETAILS:
check for the page
get the search
SEARCH FORM submit to same page
pagination and search are meant to work in unity
LIMIT in conjunction with SQL_CALC_FOUND_ROWS
LIKE to filter search results
prepared statements
while loop displays results with PDO fetch
FOUND_ROWS to get result of first query
--> that result is an Integer
last page is calculated by dividing
that Integer through the limit
pagination is done inside for loop with if statements
connect
try {
$conn = new PDO($server, $user, $pass);
$conn -> setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$conn -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// echo "success";
} catch (PDOException $e) {
echo "ERROR: " . $e -> getMessage();
}
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL & ~E_NOTICE);
index
if (!isset($_GET['page'])) { $page = 1;
} else { $page = $_GET['page']; }
if ($page < 1) { $page = 1;
} elseif ($page > $last_page) {
$page = $last_page; }
$search = $_GET['search'];
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<form action="<?php $_SERVER['PHP_SELF'] ?>" method="GET">
<input type="text" name="search" value="<?php $search ?>">
<input type="submit" value="search">
</form</body>
</html>
<?php
$start = 0;
$limit = 3;
$query = "
SELECT SQL_CALC_FOUND_ROWS * FROM tbl_articles
WHERE
(art_headline LIKE '%{$search}%')
OR
(art_content LIKE '%{$search}%')
LIMIT $start, $limit
";
$stmt = $conn -> prepare($query);
$stmt -> execute();
while ($res = $stmt -> fetch(PDO::FETCH_ASSOC)) {
echo '<h1>'.$res['art_headline'].'</h1>'."\n";
echo '<p>'.$res['art_content'].'</p>';
echo '<b>'.$res['art_author'].'</b>'."\n";
echo '<span>'.date("d.m.Y", strtotime($res['art_datetime'])).'</span>'."\n\n";
echo '<b>'.$res['art_id'].'</b>'."\n";
}
$query = "
SELECT FOUND_ROWS() AS num FROM tbl_articles
";
$stmt = $conn -> prepare($query);
$stmt -> execute();
$max = $stmt -> fetch(PDO::FETCH_ASSOC);
var_dump($max[num]);
$total_pages = $max[num];
// $stmt = $conn -> query($query) -> fetchColumn();
$last_page = ceil($total_pages / $limit);
// loop through pages
echo "<div><nav>";
for ($i = 1; $i <= $last_page; $i++) {
if (
($i == 1)
||
($i == $last_page)
||
(
($i >= ($page - 2))
&&
($i <= ($page + 2))
)
) {
if ($last_i != ($i - 1)) {
$out .= " ... ";
}
if ($page == $i) { $out .= "["; }
$out .= "$i";
if ($page == $i) { $out .= "] "; }
$out .= " ";
$last_i = $i;
$prev = $page - 1;
$prev_link = "back\n";
$next = $page + 1;
$next_link = "next\n";
}
}
echo $prev_link;
echo $out;
echo $next_link;
echo "</nav></div>";
?>
Any help is greatly appreciated, from a PHP beginner.
ok guys, my PHP Pro Mentor helped me solve it.
Here we go:
to fix the search results display I had to insert
if ($_GET['page'] > 1) {
$start = ($_GET['page'] - 1) * $limit;
}
between the $start and $limit variables and the first $query
to fix the pagination I just had to insert:
$page = $_GET['page'];
on top of the script.
i am trying to add limit each time when button is clicked but is not working
my html code is
<div class="media stream load-more">
<a href="<?php echo $_SERVER['PHP_SELF']; ?>" method ='post' name = 'showmore'>
<i class="icon-refresh shaded"></i>
show more...
</a>
</div>
php code is
$showvalue = 2;
if(isset($_POST['showmore'])) {
$showvalue += 1;
}
$feeds = $db->getfeeds($showvalue);
mysql function
public function getfeeds($showvalue){
$stmt = $this->con->prepare("SELECT id,image,title,status,profilepic,created_at,url FROM news ORDER BY id DESC LIMIT $showvalue");
$stmt->bind_param("s",$showvalue);
$stmt->execute();
$result = $stmt->get_result();
$nrow = array();
while ($r = $result->fetch_assoc()) {
$nrow[] = $r;
}
$frow['news'] = $nrow;
$json = str_replace("\\/", "/",json_encode($frow));
return $json;
}
I have a simple code with select and insert PDO statements..
In this code im inserting data on the basis of $p_id which is a global variable. I have executed the code without using function. But now having function in my code it doesnt work. Here is the code -
<?php
include "connection.php";
$p_id;
if (!empty($_POST['prod_sub']))
{
$sth = $dbo->prepare("SELECT production_ID FROM le_planning.log_production ORDER BY production_ID DESC LIMIT 1");
$sth->execute();
$result = $sth->fetchAll(PDO::FETCH_ASSOC);
$count = $sth->rowCount();
if($count > 0)
{
foreach($result as $arr)
{
$p_id = $arr['production_ID'];
$p_id = $p_id+1;
}
prodExec();
}
else // FIRST TIME INPUT
{
$p_id = 1;
prodExec();
}
function prodExec()
{
global $p_id; // GLOBAL
$q = "INSERT INTO le_planning.transactions (Type, Type_ID) VALUES ('Production', $p_id)";
$stmt = $dbo->prepare($q);
if($stmt->execute())
{echo "";}
else{echo "Error!";}
$sth1 = $dbo->prepare("SELECT * FROM le_planning.temp_prod");
$sth1->execute();
$result1 = $sth1->fetchAll(PDO::FETCH_ASSOC);
$count1 = $sth1->rowCount();
if($count1 > 0)
{
foreach($result1 as $item)
{
$Qty = $item['Qty'];
$group_ID = $item['group_ID'];
$component = $item['component'];
$Component_ID = $item['Component_ID'];
$stock_ID = $item['stock_ID'];
$q1 = "INSERT INTO le_planning.log_production (production_ID, Transaction_ID, datetime, stock_ID, component, Component_ID, Qty) SELECT $p_id, MAX(Transaction_ID), now(), $stock_ID, '$component', '$Component_ID', $Qty FROM le_planning.transactions";
$stmt1 = $dbo->prepare($q1);
if($stmt1->execute())
echo "";
else{echo "Error!";}
}
}
}
}
?>
WHAT I TRIED -
this is the same logic but without the PDO statements and works like a charm.
<?php
$p_id;
$count = 0;
if($count > 0)
{
$p_id=1;
prodExec(); // gives output 1 when $count = 1
}
else
{
$p_id=2;
prodExec(); // gives output 2 when $count = 0
}
function prodExec()
{
global $p_id;
echo $p_id;
}
?>
Can anybody help me spot my mistake in here? Thanks.
I'm doing my own little project converting UserCake (latest) to OOP with PDO, i've finalised a lot of features already. But right now i've been stuck for awhile on this Page functionality. So according to the code it's suppose to read the root folder for PHP files and add them to DB table (uc_pages) if they don't already exist. And if there's pages in the DB that doesn't exist in the root folder to delete those from the db.
I get no errors at all which is kinda interesting... but i'll post the code if anyone would be kind to give me a hand on this one.
Pages.php
<?php
require_once("resources/database.php");
$website_pages = new dbPages($db);
// set number of records per page
$records_per_page = 6;
// calculate for the query LIMIT clause
$from_record_num = ($records_per_page * $page) - $records_per_page;
$website_pages->getPageFiles();
//Retrieve list of pages in root usercake folder
$website_pages->fetchAllPages();
//Retrieve list of pages in pages table
$creations = array();
$deletions = array();
//Check if any pages exist which are not in DB
foreach ($website_pages->getPageFiles() as $web_page){
if(!isset($website_pages->readOne()[$web_page])){
$creations[] = $web_page;
}
}
//Enter new pages in DB if found
if (count($creations) > 0) {
$website_pages->create($creations);
}
if (count($website_pages->fetchAllPages()) > 0){
//Check if DB contains pages that don't exist
foreach ($website_pages->readOne() as $web_page){
if(!isset($website_pages->fetchAllPages()[$web_page['page']])){
$deletions[] = $web_page['id'];
}
}
}
//Delete pages from DB if not found
if (count($deletions) > 0) {
$website_pages->delete($deletions);
}
//Update DB pages
$website_pages->readAll($from_record_num, $records_per_page);
// header settings
$page_url="pages.php?";
$page_title = "UNFINISHED: All pages";
include_once "./resources/header.php";
?>
<div class='container'>
<div class='page-header'>
<h1><?php echo"{$page_title}";?></h1>
</div>
</div>
<div class="jumbotron">
<div class="container">
<?php
// query products
$stmt = $website_pages->readAll($from_record_num, $records_per_page);
$num = $stmt->rowCount();
// display the products if there are any
if($num>0){
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
extract($row);
echo "<div class='col-xs-12 col-md-6'>
<div class='btn-group btn-group-justified' role='group'
aria-label='Justified button group'>
<a href='page.php?id={$id}' class='btn btn-warning' role='button'>
<span class='glyphicon glyphicon-edit'></span> Edit</a>
</div>";
echo "
<div class='panel panel-primary'>
<div class='panel-heading'>
<h3 class='panel-title'>{$page_name}</h3>
</div>
<div class='panel-footer'>";
//Show public/private setting of page
if($private == 0){
echo "This page is Public";
}
else {
echo "This page is Private";
}
echo "</div></div></div>";
}
echo "</div>";
// needed for paging
$total_rows=0;
if($page_url=="pages.php?"){
$total_rows=$website_pages->countAll();
}
// paging buttons
include_once './resources/paging.php';
}
// tell the user there are no products
else{
echo "<div class=\"alert alert-danger alert-dismissable\">";
echo "<button type=\"button\" class=\"close\" data-
dismiss=\"alert\" aria-hidden=\"true\">×</button>";
echo "No pages found.";
echo "</div>";
}
echo "</div>";
?>
</div>
</div>
<?php require("./resources/footer.php")?>
Database.php
<?php
class Database{
// specify your own database credentials
private $host = "###########";
private $db_name = "website";
private $username = "###########";
private $password = "###########";
public $conn;
// get the database connection
public function getConnection(){
$this->conn = null;
try{
$this->conn = new PDO(
"mysql:host=" . $this->host . ";dbname=" . $this->db_name,
$this->username, $this->password);
}catch(PDOException $exception){
echo "Connection error: " . $exception->getMessage();
}
return $this->conn;
}
}
// instantiate database and product object
$database = new Database();
$db = $database->getConnection();
require_once './resources/functions.php';
$website = new Configuration($db);
$website->readConfig();
?>
The part from functions.php that is struggling
class dbPages {
// database connection and table names
private $conn;
private $table_name = "uc_pages";
private $table_name2 = "uc_permission_page_matches";
// object properties
public $id;
public $page_id;
public $permission_id;
public $page_name;
public $private;
public $pages;
public $row;
public function __construct($db){
$this->conn = $db;
}
//Retrieve a list of all .php files in root files folder
function getPageFiles() {
$directory = "";
$pages = glob($directory . "*.php");
//print each file name
foreach ($pages as $web_page){
$row[$web_page] = $web_page;
}
return $row;
}
//Fetch information on all pages
function fetchAllPages() {
$query = "SELECT
id,
page_name,
private
FROM
" . $this->table_name . " ";
// prepare query statement
$stmt = $this->conn->prepare( $query );
$stmt->execute();
while ($stmt->fetch(PDO::FETCH_ASSOC)){
$row[$web_page] = array(
'id' => $id, 'page_name' => $page_name, 'private' => $private);
}
if (isset($row)){
return ($row);
}
}
// read products
function readAll($from_record_num, $records_per_page){
// select query
$query = "SELECT
id,
page_name,
private
FROM
" . $this->table_name . "
ORDER BY
page_name ASC
LIMIT
?, ?";
// prepare query statement
$stmt = $this->conn->prepare( $query );
// bind variable values
$stmt->bindParam(1, $from_record_num, PDO::PARAM_INT);
$stmt->bindParam(2, $records_per_page, PDO::PARAM_INT);
// execute query
$stmt->execute();
// return values from database
return $stmt;
}
// used for paging products
public function countAll(){
$query = "SELECT COUNT(*) as total_rows
FROM " . $this->table_name . "";
$stmt = $this->conn->prepare( $query );
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
return $row['total_rows'];
}
// used when filling up the update product form
function readOne(){
$query = "SELECT
id,
page_name,
private
FROM
" . $this->table_name . "
WHERE
page_name = ?
LIMIT
0,1";
$stmt = $this->conn->prepare( $query );
$stmt->bindParam(1, $this->id);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$this->id = $row['id'];
$this->page_name = $row['page_name'];
$this->private = $row['private'];
}
// create product
function create($pages){
//write query
$query = "INSERT INTO
" . $this->table_name . "
SET
id = ?,
page_name = ?,
private = ?";
$stmt = $this->conn->prepare($query);
$stmt->bindParam(1, $this->id);
$stmt->bindParam(2, $this->page_name);
$stmt->bindParam(3, $this->private);
foreach($pages as $page_name){
if($stmt->execute()){
return true;
}else{
return false;
}
}
}
// delete the product
function delete($pages){
$query = "DELETE FROM " . $this->table_name . " WHERE id = ?";
$stmt = $this->conn->prepare($query);
$stmt->bindParam(1, $this->id);
foreach($pages as $id){
if($result = $stmt->execute()){
return true;
}else{
return false;
}
}
$query2 = "DELETE FROM " . $this->table_name2 . "
WHERE page_id = ?";
$stmt2 = $this->conn->prepare($query);
$stmt2->bindParam(1, $this->page_id);
foreach($pages as $id){
if($result = $stmt2->execute()){
return true;
}else{
return false;
}
}
}
}