I want to update checked values in MySQL with PHP
<?php
require "../../../../config.php";
if (isset($_POST['btn-upload'])) {
try {
$connection = new PDO($dsn, $username, $password, $options);
$status = $_POST['status'];
$ck_id = $_POST['ck_id'];
for ($i = 0; $i < sizeof($ck_id); $i++) {
$sql = "UPDATE form_eg208 SET status=:status where ck_id IN (:ck_id)";
$statement = $connection->prepare($sql);
$statement->bindParam(':status', $status[$i]);
$statement->bindParam(':ck_id', $ck_id[$i]);
$statement->execute();
}
} catch (PDOException $error) {
echo $sql . "<br>" . $error->getMessage();
}
if ($statement->rowcount() >= 0) {
echo '<div class="alert alert-success alert-dismissible" id="flash-
msg">
<a href="#" class="close" data-dismiss="alert" aria-label="close">×
</a>
<h4> <strong>Success!</strong> Insert Record
Successfully</h4>
</div>';
} else {
echo '<div class="alert alert-danger alert-dismissible" id="flash-
msg">
<a href="#" class="close" data-dismiss="alert" aria-label="close">×
</a>
<h4> <strong>Failed!</strong> Duplicate BGLPARTNO</h4>
</div>';
}
}
?>
my html code is
<?php
$id = $_REQUEST['cid'];
try {
$connection = new PDO($dsn, $username, $password, $options);
$j = 1;
$sql = "CALL view_eg208 (:bglpartno)";
$statement = $connection->prepare($sql);
$statement->bindParam(':bglpartno', $id);
$statement->execute();
$result = $statement->fetchAll();
} catch (PDOException $error) {
echo $sql . "<br>" . $error->getMessage();
}
foreach ($result as $row1)
?>
<div class="container-fluid">
<div class="row">
<div class="col-md-12" style="margin-top:40px;">
<div class="card">
<div class="card-body">
<form method="post" action="" enctype='multipart/form-data' class="needs-validation" novalidate>
<div class="table-responsive m-t-40">
<table id="myTable" class="table table-hover table-bordered">
<thead class="thead-dark">
<tr>
<th>No.</th>
<th>Activity</th>
<th style="text-align:center;">Status</th>
</tr>
</thead>
<tbody>
<?php
if ($result && $statement->rowCount() > 0) {
foreach ($result as $row) { ?>
<tr>
<td>
<input type="checkbox" id="ck_id[]" class="filled-in chk-col-blue"
name="ck_id[]" value="<?php echo escape($row["ck_id"]); ?>"/>
</td>
<td style="color:black"><?php echo escape
($row["activity_name"]); ?></td>
<td>
<div class="form-group has-danger"
style="margin-bottom: 0;">
<input type="text" id="status[]" name="status[]" maxlength="100" class="form-control" value="<?php echo escape($row["status"]);?>" autocomplete="off" required="required">
<div class="invalid-feedback">
Please provide a Inputs.
</div>
</div>
</td>
</tr>
<?php }
}
$connection = null;
?>
</tbody>
</table>
When I update all the values then it works correctly but when single value then it updates the value of first box into that box which I selected. Please help me to solve this
Please make your checkbox input like this so you get the right status for the right ck_id index :
if ($result && $statement->rowCount() > 0) {
foreach ($result as $i => $row) { ?>
<tr>
<td>
<input type="checkbox" id="ck_id[]"class="filled-in chk-col-blue"
name="ck_id[<?php echo $i ?>]" value="<?php echo escape ($row["ck_id"]);?>"/>
</td>
<td style="color:black"><?php echo escape
($row["activity_name"]);?></td>
<td>
<div class="form-group has-danger"
style="margin-bottom: 0;">
<input type="text" id="status[]" name="status[<?php echo $i ?>]"
maxlength="100" class="form-control" value="<?
php echo escape ($row["status"]);?>" autocomplete="off"
required="required" >
<div class="invalid-feedback">
Please provide a Inputs.
</div>
</div>
</td>
</tr>
<?php
}
}
Also try to use foreach instead of for loops :
try {
$connection = new PDO($dsn, $username, $password, $options);
$status = $_POST['status'];
$ck_id = $_POST['ck_id'];
// for ($i = 0; $i < sizeof($ck_id); $i++) {
foreach ($ck_id as $i => $value) {
$sql = "UPDATE form_eg208 SET status=:status where ck_id IN (:ck_id)";
$statement = $connection->prepare($sql);
$statement->bindParam(':status', $status[$i]);
$statement->bindParam(':ck_id', $ck_id[$i]);
$statement->execute();
}
} catch (PDOException $error) {
echo $sql . "<br>" . $error->getMessage();
}
Related
I wrote this code:
<div class="container mx-auto">
<!--Add class table-responsive for responsive table -->
<div class="row">
<div class="col-md-6">
<form method="post">
<div class="input-group">
<input size='14' type="text" class="form-control" placeholder="Search for..." name="searchValue">
<span class="input-group-btn">
<button class="btn btn-secondary" name='search' type="submit"><i class="fa fa-search"></i></button>
</span>
</div>
</form>
</div>
</div>
<table class="table mx-auto" id="'table">
<thead>
<tr>
<th>Name</th>
<th>Surname</th>
<th>Email</th>
<th>Phone</th>
<th>Company</th>
<th>More</th>
</tr>
</thead>
<tbody>
<?php
$pagination = new Pagination(7);
$page_max = $pagination->getPageMax();
$start = $pagination->getStart();
if(!isset($_POST['search'])) {
$numberOfPages = $pagination->numberOfPages($database->getData("SELECT count(id) FROM customers"));
$customers = $database->getDataAsArray("SELECT * FROM customers LIMIT $start, $page_max");
}
else{
$searchValue = '%'. $_POST['searchValue'] . '%';
$numberOfPages = $pagination->numberOfPages($database->getData("SELECT count(id) FROM customers WHERE name LIKE '$searchValue' "));
$customers = $database->getDataAsArray("SELECT * FROM customers WHERE name LIKE '$searchValue' LIMIT $start, $page_max");
}
foreach($customers as $customer){
$name = $customer ['name'];
$surname = $customer['surname'];
$email = $customer['email'];
$phone = $customer['phone'];
$company = $customer['company'];
$id = $customer['id'];
echo "<tr>
<td>$name</td>
<td>$surname</td>
<td>$email</td>
<td>$phone</td>
<td>$company</td>
<td><a href='customerInfo.php?id=$id' class='btn btn-sm btn-info'><i class='fa fa-info'></i></a></td>
</tr>";
}
?>
</tbody>
</table>
<ul class="pagination">
<?php
echo $pagination->previous($numberOfPages);
for($i = 0; $i < $numberOfPages; $i++){
echo '<li class="page-item"><a class="page-link" href="?page='. $i . '">'. $i. '</a></li>';
}
echo $pagination->next($numberOfPages);
?>
</ul>
</div>
The getDataAsArray function is like this:
public function getDataAsArray($myQuery){
$this->connection = mysqli_connect($this->host, $this->dbUsername, $this->dbPassword, 'portal');
$query = mysqli_query($this->connection, $myQuery);
$results = array();
while($line = mysqli_fetch_array($query)){
$results[] = $line;
}
return $results;
}
I know I should use :[name] or something to set a parameter in my query,the question is not about that and ofcourse I should use a prepared statment. Will do that later.
The question:
I wrote the code to search in the db records. I works fine but when I search it creates a new pagination with all the new records and when I click on the second page. The page builds the pagination with all the records from the database so I won't use it's searchValue anymore.
I think this issue will be solved with a $_GET parameter like search in the URL or Ajax but I don't know how.
Could anyone help me out?
I have a tbl_employee table and tbl_time table, I want to insert multiple data insert for attendance but when I click submit button it's insert only single data . but where is the problem ,help me to find out this..this is insert code
require './db_connect.php';
class Time extends Db_connect {
protected $link;
public function __construct() {
$this->link = $this->database_connection();
}
public function attendance_insert($data) {
extract($data);
$cur_date = date('Y-m-d');
foreach ($time_attendance as $attn_key => $attn_value) {
if ($attn_value == 'P') {
$SQL = "INSERT INTO tbl_time(employee_id,time_date,time_attendance)VALUES('$attn_key','$cur_date','P')";
$atten_date=mysqli_query($this->link, $SQL);
} else if ($attn_value == 'A') {
$SQL = "INSERT INTO tbl_time(employee_id,time_date,time_attendance)VALUES('$attn_key','$cur_date','A')";
$atten_date=mysqli_query($this->link, $SQL);
}
if ($atten_date) {
$massage = "<div class='alert alert-success text-center'><h5>Attendance insert successfully</h5></div>";
return $massage;
} else {
die('Attendance insert query problem' . mysqli_error($this->link));
}
}
}
}
this is html code
<?php
require_once './time.php';
$obj_time = new Time()
$massage = '';
if (isset($_POST['btn'])) {
$massage = $obj_time->attendance_insert($_POST);
}
$employee_view = $obj_employee->employee_all_view();
?>
<div class="container-fluid">
<div class="row">
<center>
<span style="font-size:1.8em;">Attendance form</span>
</center>
</div>
</div>
<hr/>
<?php echo $massage; ?>
<div class="container-fluid">
<div class="row">
<div class="col-lg-12">
<div class="panel panel-body panel-default">
<div class="well text-center" style="font-size:15px;">
<strong>Date :</strong>
<?php $current_date = date('Y-M-d');
echo $current_date; ?>
</div>
<form class="form-horizontal" method="post">
<table class="table table-striped table-responsive text-center">
<tr>
<td><b>Serial</b></td>
<td><b>Name</b></td>
<td><b>ID</b></td>
<td><b>Attendance</b></td>
</tr>
<?php
$i = 0;
while ($employee_info = mysqli_fetch_assoc($employee_view)) {
extract($employee_info);
$i++;
?>
<tr>
<td><?php echo $i; ?></td>
<td><?php echo $employee_first_name . ' ' . $employee_last_name; ?></td>
<td><?php echo $employee_id; ?></td>
<td>
<input type="radio" name="time_attendance[<?php echo $employee_id; ?>]" value="P">P
<input type="radio" name="time_attendance[<?php echo $employee_id; ?>]" value="A">A
</td>
</tr>
<?php } ?>
<tr>
<td colspan="4">
<input type="submit" class="btn btn-primary btn-block" name="btn" value="submit"/>
</td>
</tr>
</table>
</form>
</div>
</div>
</div>
</div>
This :
foreach($time_attendance as $attn_key => $attn_value){
$SQL = "INSERT INTO tbl_time(employee_id,time_date,time_attendance)
VALUES('$attn_key','$cur_date','A')";
$atten_date = mysqli_query($this->link, $SQL);
if ($atten_date) {
$massage = "<div class=''><h5>Attendance insert successfully</h5></div>";
return $massage;
}
}
Literally ask to break the foreach with return $massage; if you query succeed... So yes, you'll only have one record.
Put your return outside the foreach.
I am trying to make a table in PHP.
There is form where I am taking in Value - Market, Production Date, Sales Date and sending it in POST to Table to get it populated.
At the POST I am calling a set of data from production table from MySQL and populating in the same table.
I am able to populate the table from SQL and Form POST Action but I am not able to align them as per the required output format.
Please help in finding fix for the below Code:
<?php
if(isset($_POST['for_post']))
{
try
{
?>
<div class="card-box" style="padding-left:5px;padding:10px;padding-bottom:50px">
<div class="row">
<div class="col-sm-12">
<?php
if(isset($_POST['for_post_market'])){ $pname = $_POST['for_post_market']; }
if(isset($_POST['for_post_prod_date'])){ $pcat = $_POST['for_post_prod_date']; }
if(isset($_POST['for_post_sale_date'])){ $pprice = $_POST['for_post_sale_date']; }
$query = 'SELECT * FROM product';
$stmt = $DB_con->prepare($query);
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$result[$row['prod_cat_name']][] = $row['prod_name'];
}
?>
<table id="invoices" border="1">
<thead>
<th>Category</th>
<th>Product</th>
<th>Production Date</th>
<th>Sales Date</th>
<th>Market</th>
</thead>
<tbody>
<?php
foreach($result as $id => $invoices) {
echo '<tr>';
echo '<td rowspan='. count($invoices) . '>' . $id . '</td>';
$count = 0;
foreach ($invoices as $invoice) {
if ($count != 0) {
echo '<tr>';
}
echo "<td>$invoice</td>";
echo "<td>".$pcat."</td>";
echo "<td>".$pprice."</td>";
$count++;
}
}
$a=count($pname);
for($i=0;$i<$a;$i++)
{
echo "<td>".$pname[$i]."</td></tr>";
}
echo "</tbody>";
echo "</table>";
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
else
{ ?>
</div>
</div>
</div>
<div class="card-box" style="padding-left:5px;padding:10px;padding-bottom:50px">
<div class="row">
<div class="col-sm-12">
<form class="form-inline" method="post">
<div class="form-group m-r-10">
<label for="exampleInputName2">Market : </label>
<div class="input-group">
<select class="selectpicker" multiple data-selected-text-format="count" data-style="btn-white" name="for_post_market[]">
<?php
$stmt = $DB_con->prepare('Select * from location');
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo '<option>'.$row['location_name'].'</option>';
}
?>
</select>
<div>
 
<div class="form-group m-r-10">
<label for="exampleInputEmail2">Production Date : </label>
<div class="input-group">
<input type="text" class="form-control" placeholder="mm/dd/yyyy" id="datepicker-autoclose" name="for_post_prod_date">
<span class="input-group-addon bg-custom b-0 text-white"><i class="icon-calender"></i></span>
</div>
</div>
<div class="form-group m-r-10">
<label for="exampleInputEmail2">Sales Date : </label>
<div class="input-group">
<input type="text" class="form-control" placeholder="mm/dd/yyyy" id="datepicker2-autoclose" name="for_post_sale_date">
<span class="input-group-addon bg-custom b-0 text-white"><i class="icon-calender"></i></span>
</div>
</div>
<button type="submit" class="btn btn-default waves-effect waves-light btn-md" id="for_post" name="for_post">
Submit
</button>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
<?php
}
?>
The Current Output that I am able to get from this code is :
What I am trying to get is :
Updated Changes Suggested and worked:
<table id="invoices" border="1">
<thead>
<th>Category</th>
<th>Product</th>
<th>Production Date</th>
<th>Sales Date</th>
<th>Market</th>
<th>Input</th>
</thead>
<tbody>
<?php
$a=count($pname);
foreach($result as $id => $invoices) {
echo '<tr>';
echo '<td rowspan='. count($invoices)*$a . '>' . $id . '</td>';
$count = 0;
foreach ($invoices as $invoice) {
if ($count != 0) {
echo '<tr>';
}
echo '<td rowspan='. count($pname) . '>' . $invoice . '</td>';
echo '<td rowspan='. count($pname) . '>' . $pcat . '</td>';
echo '<td rowspan='. count($pname) . '>' . $pprice . '</td>';
for($i=0;$i<$a;$i++)
{
echo '<td>'. $pname[$i] . '</td>';
echo '<td><input type="text" class="form-control"></td></tr>';
}
$count++;
}
}
echo '</tbody>';
echo '</table>';
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
else
{ ?>
You have to set Category column rowspan to count($invoices)*count($pname) and set rowspan to Product, Production date and Sales date columns to count($pname)
The goal is to code php files so I have the ability to perform CRUD functions on categories.
I don't know what I'm doing wrong and why I'm getting an this error . Check the image below!
But after changing it i get Column not found: 1054 Unknown column 'category_category_id' in 'field list' on line 43?
Line 43
$q->execute(array($category_category_id,$category_name,$id));
updateCategory.php
<?php
require 'database.php';
$id = null;
if ( !empty($_GET['id'])) {
$id = $_REQUEST['id'];
}
if ( null==$id ) {
header("Location: index.php");
}
if ( !empty($_POST)) {
// keep track validation errors
$category_nameError = null;
$category_category_idError = null;
// keep track post values
$category_category_id = $_POST['id'];
$category_name = $_POST['category_name'];
// validate input
$valid = true;
if (empty($category_category_id)) {
$category_idError = 'Please enter Category id';
$valid = false;
}
if (empty($category_name)) {
$category_nameError = 'Please enter Category name';
$valid = false;
}
// update data
if ($valid) {
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "UPDATE category set category_category_id = ?, category_name = ? WHERE id = ?";
$q = $pdo->prepare($sql);
$q->execute(array($category_category_id,$category_name,$id));
Database::disconnect();
header("Location: index.php");
}
} else {
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT * FROM category where id = ?";
$q = $pdo->prepare($sql);
$q->execute(array($id));
$data = $q->fetch(PDO::FETCH_ASSOC);
$category_category_id = $data['id'];
$category_name = $data['category_name'];
Database::disconnect();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link href="css/bootstrap.min.css" rel="stylesheet">
<script src="js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="span10 offset1">
<div class="row">
<h3>Update a Category</h3>
</div>
<form class="form-horizontal" action="updateCategory.php?id=<?php echo $id?>" method="post">
<div class="control-group <?php echo !empty($$category_category_idError)?'error':'';?>">
<label class="control-label">Category Id</label>
<div class="controls">
<input name="id" type="text" placeholder="Category Id" value="<?php echo !empty($category_category_id)?$category_category_id:'';?>">
<?php if (!empty($$category_category_id)): ?>
<span class="help-inline"><?php echo $$category_category_id;?></span>
<?php endif; ?>
</div>
</div>
<div class="control-group <?php echo !empty($category_nameError)?'error':'';?>">
<label class="control-label">Category Name</label>
<div class="controls">
<input name="category_name" type="text" placeholder="Category Name" value="<?php echo !empty($category_name)?$category_name:'';?>">
<?php if (!empty($category_nameError)): ?>
<span class="help-inline"><?php echo $category_nameError;?></span>
<?php endif;?>
</div>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-success">Update</button>
<a class="btn" href="index.php">Back</a>
</div>
</form>
</div>
</div> <!-- /container -->
</body>
</html>
index.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link href="css/bootstrap.min.css" rel="stylesheet">
<script src="js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="row">
<h3>Product Menu</h3>
</div>
<div class="row">
<p>
Create
</p>
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>Id</th>
<th>CategoryId</th>
<th>Brand</th>
<th>Name</th>
<th>Barcode</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<?php
include_once 'database.php';
$pdo = Database::connect();
$sql = 'SELECT * FROM product ORDER BY id ASC';
foreach ($pdo->query($sql) as $row) {
echo '<tr>';
echo '<td>'. $row['id'] . '</td>';
echo '<td>'. $row['category_id'] . '</td>';
echo '<td>'. $row['brand'] . '</td>';
echo '<td>'. $row['name'] . '</td>';
echo '<td>'. $row['barcode'] . '</td>';
echo '<td>'. $row['price'] . '</td>';
echo '<td width=250>';
echo '<a class="btn" href="read.php?id='.$row['id'].'">Read</a>';
echo ' ';
echo '<a class="btn btn-success" href="update.php?id='.$row['id'].'">Update</a>';
echo ' ';
echo '<a class="btn btn-danger" href="delete.php?id='.$row['id'].'">Delete</a>';
echo '</td>';
echo '</tr>';
}
?>
</tbody>
</table>
<div class="container">
<div class="row">
<h3>Category Menu</h3>
</div>
<div class="row">
<p>
Create
</p>
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>Category Id</th>
<th>Category Name</th>
</tr>
</thead>
<?php
include_once 'database.php';
$pdo = Database::disconnect();
$pdo = Database::connect();
$sql = 'SELECT * FROM category ORDER BY id ASC';
foreach ($pdo->query($sql) as $row) {
echo '<tr>';
echo '<td>'. $row['id'] . '</td>';
echo '<td>'. $row['category_name'] . '</td>';
echo '<td width=250>';
echo '<a class="btn" href="readCategory.php?id='.$row['id'].'">Read</a>';
echo ' ';
echo '<a class="btn btn-success" href="updateCategory.php?id='.$row['id'].'">Update</a>';
echo ' ';
echo '<a class="btn btn-danger" href="deleteCategory.php?id='.$row['id'].'">Delete</a>';
echo '</td>';
echo '</tr>';
}
Database::disconnect();
?>
</tbody>
</table>
</div>
</div>
</body>
</html>
<!-- <div class="container">
<div class="row">
<h3>PHP CRUD Grid</h3>
</div>
<div class="row">
<p>
Create
</p>
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>CategoryId</th>
<th>Catengory Name</th>
</tr>
</thead>
$sql2 = 'SELECT * FROM category ORDER BY id DESC';
foreach ($pdo->query($sql2) as $row) {
echo '<tr>';
echo '<td>'. $row['id'] . '</td>';
echo '<td>'. $row['category_name'] . '</td>';
echo '<td width=250>';
echo '<a class="btn" href="readCategory.php?id='.$row['id'].'">Read</a>';
echo ' ';
echo '<a class="btn btn-success" href="updateCategory.php?id='.$row['id'].'">Update</a>';
echo ' ';
echo '<a class="btn btn-danger" href="deleteCategory.php?id='.$row['id'].'">Delete</a>';
echo '</td>';
echo '</tr>';
</div>
}
Database::disconnect();
?>
</tbody>
</table> -->
You need to initialize the variable in the code like this
require 'database.php';
$id = null;
if ( !empty($_GET['id'])) {
$id = $_REQUEST['id'];
}
if ( null==$id ) {
header("Location: index.php");
}
$category_category_id = "";
$category_name = "";
if ( !empty($_POST)) {
// keep track validation errors
$category_nameError = null;
$category_category_idError = null;
// keep track post values
$category_category_id = $_POST['id'];
$category_name = $_POST['category_name'];
// validate input
$valid = true;
if (empty($category_name)) {
$category_nameError = 'Please enter Category name';
$valid = false;
}
if (empty($category_category_id)) {
$category_idError = 'Please enter Category id';
$valid = false;
}
// update data
if ($valid) {
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "UPDATE category set id = ?, category_name = ? WHERE id = ?";
$q = $pdo->prepare($sql);
$q->execute(array($category_category_id,$category_name,$id));
Database::disconnect();
header("Location: index.php");
}
} else {
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT * FROM category where id = ?";
$q = $pdo->prepare($sql);
$q->execute(array($id));
$data = $q->fetch(PDO::FETCH_ASSOC);
$category_category_id = $data['id'];
$category_name = $data['category_name'];
Database::disconnect();
}
also change the input field name
<input name = "category_name" id="catogortId" type = "text" placeholder = "Category Name" value = "<?php echo !empty($category_name)?$category_name:'';?>">
You don't have put name attribute value in form so put it like :
<input name="category_name" type="text" placeholder="Category Name" name="category_name" value="<?php echo !empty($category_name)?$category_name:'';?>">
You do not have category_name field.
Change:
<input name="category_id" type="text" placeholder="Category Name" value="<?php echo !empty($category_name)?$category_name:'';?>">
To
<input name="category_name" type="text" placeholder="Category Name" value="<?php echo !empty($category_name)?$category_name:'';?>">
You need to change name = "category_id" to name = "category_name" in updateCategory.php file
Change
<input name = "category_id" type = "text" placeholder = "Category Name" value = "<?php echo !empty($category_name)?$category_name:'';?>">
TO
<input name = "category_name" type = "text" placeholder = "Category Name" value = "<?php echo !empty($category_name)?$category_name:'';?>">
I have attempted to set up pagination for a simple database table which selected everything from the database table and displays it in a table for the user however i have been having issues with this. I followed a tutorial which shows how to set up the pagination but i keep encountering a SQLSTATE[42000]: Syntax error or access violation: 1327 Undeclared variable: $startrow error and I'm not sure why.
this is the code:
<?php
include "db_conx.php";
//check if the starting row variable was passed in the URL or not
if (!isset($_GET['startrow']) or !is_numeric($_GET['startrow'])) {
//we give the value of the starting row to 0 because nothing was found in URL
$startrow = 0;
//otherwise we take the value from the URL
} else {
$startrow = (int)$_GET['startrow'];
}
try {
$db_conx = new PDO("mysql:host=$mysql_hostname;dbname=$mysql_dbname", $mysql_username, $mysql_password);
$db_conx->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $db_conx->prepare('SELECT * FROM role_type LIMIT $startrow, 3');
$stmt->execute();
$roles = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
catch(Exception $e)
{
die ("Could not connect to the database $mysql_dbname :" . $e->getMessage());
}
?>
<h4><center>Manage Role Types</center></h4>
<div class="container">
<div class = "container-fluid">
<div id = "table_container" style="width:auto; margin-top:50px;" class="mainbox col-md-6">
<div class="row clearfix">
<div class="col-md-12">
<table class="table table-bordered table-hover" id="tab_logic">
<thead>
<tr >
<th class="text-center">
Role Type Code
</th>
<th class="text-center">
Role Title
</th>
</tr>
</thead>
<tbody>
<!-- populating the table with information from mysql database -->
<?php foreach ($roles as $row) {
echo "<tr><td>";
echo $row['role_type_code'];
echo "</td><td>";
echo $row['role_title'];
echo "</td><td>";
echo '<p data-placement="top"
data-toggle="tooltip"
style="margin-left:5px"
title="Edit">';
echo '<button class="btn btn-primary btn-xs"
data-title="Edit"
data-toggle="modal"
data-id="';
echo $row['role_type_code'];
echo '" data-role="';
echo $row['role_title'];
echo '" data-target="#editModal">';
echo '<span class="glyphicon glyphicon-edit" />';
echo '</button></p>';
echo "</td>";
echo "</td><td>";
echo '<p data-placement="top"
data-toggle="tooltip"
style="margin-left:5px"
title="Delete">';
echo '<button class="btn btn-danger btn-xs"
data-title="Delete"
data-toggle="modal"
data-id="';
echo $row['role_type_code'];
echo '" data-role="';
echo $row['role_title'];
echo '" data-target="#deleteModal">';
echo '<span class="glyphicon glyphicon-trash" />';
echo '</button></p>';
echo "</tr>"; }
?>
</tbody>
</table>
<?PHP
//now this is the link..
echo 'Next';
$prev = $startrow - 10;
//only print a "Previous" link if a "Next" was clicked
if ($prev >= 0)
echo 'Previous';
?>
</div>
</div>
no idea why. I've tried using a value in place of the variable but it doesn't work. Any body know how i can overcome this please.
thank you
You can NOT embed php variable in SINGLE quoted strings http://php.net/language.types.string
So your query is wrong
$stmt = $db_conx->prepare('SELECT * FROM role_type LIMIT $startrow, 3');
It needs to be
$stmt = $db_conx->prepare("SELECT * FROM role_type LIMIT $startrow, 3");