I have a search bar on the first page and the results are shown on the second page with pagination. The problem is the pagination isn't working with $_GET or $_POST variable.
what I meant is like when the form is submitted the url on second page changes to something like
products.php?search=something and I am able to see the results that show up.
However when I hit the next button of the pagination I get undefined index search error and the url changes to products.php?page=2
so is there any way that I can store the $_GET['search']; value so that I can use it when the page number changes?
<form action="products.php" method="post">
<input type="text" name="search">
<input type="Submit">
</form>
products.php
<?php
/*
* Connect to the database (Replacing the XXXXXX's with the correct details)
*/
try
{
$dbh = new PDO('mysql:host=localhost;dbname=db', 'root', '');
}
catch(PDOException $e)
{
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
/*
* Get and/or set the page number we are on
*/
if(isset($_GET['page']))
{
$page = $_GET['page'];
}
else
{
$page = 1;
}
/*
* Set a few of the basic options for the class, replacing the URL with your own of course
*/
$options = array(
'results_per_page' => 100,
'url' => 'products.php?page=*VAR*',
'db_handle' => $dbh
);
$q = $_GET['search'];
/*
* Create the pagination object
*/
try
{
$paginate = new pagination($page, "SELECT * FROM products where title LIKE '%$q%' order by id desc", $options);}
catch(paginationException $e)
{
echo $e;
exit();
}
if($paginate->success == true)
{
$paginate_result = $paginate->resultset->fetchAll();
foreach($paginate_result as $row)
{
echo $row['title'];
}
?>
<?php echo "<li>"; //this is next and prev button for the pagination class if results exceed the limit.
echo $ball->links_html;
echo "</li>"; ?>
Change your code to something like this ...
<form action="products.php" method="get">
<input type="text" name="search">
<input type="Submit">
</form>
... and ...
$options = array(
'results_per_page' => 100,
'url' => 'products.php?search=' . urlencode($_GET['search']) . '&page=*VAR*',
'db_handle' => $dbh
);
The easiest solution would probably be to use a hidden field in your form:
<form action="products.php" method="post">
<input type="text" name="search">
<input type="hidden" name="page" value="<?php echo $_GET['page']; ?>">
<input type="Submit">
</form>
Try Session variables, they let you store it until the browser is closed(or you switch to another website maybe?) and store it across pages.
http://www.tizag.com/phpT/phpsessions.php
The other alternative is cookies, which will let you store for just about as long as you want unless the user deletes their cookies.
http://www.tizag.com/phpT/phpcookies.php
Related
I have a user list on my home page with a delete button besides every user, I need to link each button with the right user to delete.
<form action="http://localhost:8000/?f=delete_Users" method="POST">
<?php
include_once INCLUDE_PATH . '/Services/user_service.php';
$currentUserList = json_decode(file_get_contents('./Data/users.json'), true);
foreach ($currentUserList as $key => $value) :
?> <li><?php echo ($value['username']) ?>
<input type="submit" name="deleteBtn" value="Deletar">
<input type="hidden" name="id[]" value= "<?php echo ($key) ?>">
<?php
After this, i need to link the right user to the delete function but what i've tried so far hasn't worked.
function delete_Users($_POST) {
print_r($_POST);
$id = $_POST['id'];
include_once INCLUDE_PATH . '/Services/user_service.php';
$currentUserList = list_Users();
if (isset($_POST['deleteBtn'])) {
array_splice($currentUserList, $id, 1);
};
}
I want to make button that only appears when you make a post but after you reload page or click the button that button disappear. The button should redirect you to page with your posts. I tried to make it with SESSION but it doesn't seem to work. Can you guys post how would you do that.
EDIT: I fixed typing mistake, still nothing shows up.
<?php
session_start();
include ('init.php');
if(isset($_POST['error'])){
echo($_SESSION['error']);
unset($_SESSION['error']);
}
if(isset($_POST['success'])){
header('location: index.php');
}
if(isset($_POST['submit'])){
$title = $Users->checkInput($_POST['title']);
$text = $Users->checkInput($_POST['text']);
if($Post->postMessage($title,$text)){
$_SESSION['error'] = '<input type="submit" name="success">'; /* Session with input i want to show only once */
header('location: POST.php');
return;
}
}
?>
<html>
<head><title></title></head>
<body>
<form method='POST'>
Title: <input type="text" name="title">
Text: <input type="text" name="text">
<input type="submit" name="submit">
</form>
Go back
</body>
</html>
This is my class file:
class Post extends Users{
public function postMessage($title,$text){
$sql = "INSERT INTO forum(title,text,date,forum_id) values(:title,:text,:date,:forum_id)";
$stmt = $this->pdo->prepare($sql);
$stmt->execute(array(
':title' => $title,
':text' => $text,
':date' => date('Y-m-d H:i:s'),
':forum_id' => $_SESSION['id']
));
return true;
}
}
I believe that instead of if(isset($_POST['error'])), you should do an isset of $_SESSION, i.e:
if(isset($_SESSION['error'])){
echo($_SESSION['error']);
unset($_SESSION['error']);
}
I'm trying to write from my database into my page, using one effect. The objective is, when it writes my comment on the page, show it with an effect.
<?php
if(count($_POST) > 0){
echo '<script language="javascript">';
echo '$( "#toggle" ).toggle( "drop" );';
echo '</script>';
$db = new mysqli("localhost", "root", "usbw", "trab_projeto");
$qr = $db->query("INSERT INTO comments(comment) VALUES ('{$_POST['mensagem']}')");
echo "<fieldset id='toogle'>";
echo "<p>";
$row = $db->query("SELECT * FROM comments ORDER BY comment_id DESC LIMIT 1")->fetch_assoc();
echo $row["comment"];
echo "</p>";
echo "</fieldset>";
}
?>
The part of the script doesn't work.
These code is executed when I click on a submit form.
<div class="cadastro">
<form action="" id="form-msg" method="post" enctype="multipart/form-data">
<fieldset>
<p>
<span><b>Escreva aqui o seu comentário:</b></span><br>
<textarea name="mensagem" style="margin: 0px; width: 511px; height: 119px;"></textarea>
</p>
<input type="submit" value="Enviar">
</fieldset>
</form>
</div>
To return a JSON response, you must first place this in your header(). At the top of your script append:
header('Content-type: javascript/json');
Moving on, to prevent your SQL injection I have changed the driver to PDO which you can find documentation on.
header('Content-type: javascript/json');
$driver = new PDO('mysql:host=localhost;dbname=trab_projeto', 'root', 'password');
$state = false;
if(
!isset($_POST['mensagem']) &&
!empty($_POST['mensagem'])
) {
$driver->Prepare('INSERT INTO comments (comment) VALUES (?)');
$state = $driver->execute(array($_POST['mensagem']));
}
if($state)
{
echo json_encode(array('status' => true));
exit;
}
echo json_encode(array('status' => false));
exit;
For future notice, this 'comment' it not attached to any 'thread' scope. If you have multiple posts, you should give each post a unique ID and cross-reference the post ID with the comment so you can load the comments for that specific post.
You can then use jQuery to send requests like so:
$(document).ready(function() {
var form = $('#form-msg');
comment = form.closest('textarea').val();
$.post('the_file_path.php', { mensagem: comment })
.done(function(response) {
if(response.status) {
// todo: success using the effect below
}
});
});
Note the following code above needs a click() attached to your submit button. Consider removing this line of code:
<input type="submit" value="Enviar">
And using:
<button type='button'>Enviar</button>
So you can target it through the form like so:
form.closest('button').click(function() {
// ...
}
You could use an effect when showing the comment to the user-end like so:
var commentToAdd = document.createElement('p');
commentToAdd.innerHTML = comment;
$('#comments').append(commentToAdd);
commentToAdd.show('slow');
I have database generated content in a table with edit and delete buttons in a form at the end of the row.
<td>
<form action="?" method="post">
<div class="">
<input type="hidden" name="id" value="<?php htmlspecialchars($item['id']); ?>">
<input type="hidden" name="action" value="edit_daily_shift_report">
<input type="submit" value="Edit" onclick="return confirm('Edit this report?');">
<input type="hidden" name="action" value="delete_daily_shift_report">
<input type="submit" value="Delete" onclick="return confirm('Delete this report?');">
</div>
</form>
</td>
If I remove the delete button, the edit code works fine. But with both buttons present, the edit button fails and the item in the row is deleted. I am stumped. Not only is the action value of the edit button ignored, the action value of the delete button is executed. Any help is appreciated!
Here is the controller edit and delete code:
/*********************** Edit Daily Shift Report ************************/
if (isset($_POST['action']) && $_POST['action'] === 'edit_daily_shift_report')
{
include '../includes/dbconnect-local.php';
try
{
$sql = 'SELECT * FROM daily_shift_report WHERE id = :id';
$s = $db->prepare($sql);
$s->bindValue(':id', $_POST['id']);
$s->execute();
}
catch (PDOException $e)
{
$error = 'Error deleting data.' . $e->getMessage();
include 'error.html.php';
exit();
}
// Assign page title value
$pageTitle = 'Edit Daily Shift Report';
// Store single row resut in $item associative array
$item = $s->fetch(PDO::FETCH_ASSOC);
// Display report content in form
include 'edit_daily_shift_report.html.php';
exit();
}
/********************* Delete from Daily Shift Report *******************/
if (isset($_POST['action']) && $_POST['action'] === 'delete_daily_shift_report')
{
include '../includes/dbconnect-local.php';
try
{
$sql = 'DELETE FROM daily_shift_report WHERE id = :id';
$s = $db->prepare($sql);
$s->bindValue(':id', $_POST['id']);
$s->execute();
}
catch (PDOException $e)
{
$error = 'Error deleting data.' . $e->getMessage();
include 'error.html.php';
exit();
}
echo '<span style="color:#ff0000;">Daily Shift Report DELETED successfully!</span>';
}
Thank you.
You need to understand how the post request works. As you know, you have two action fields, one for delete and one for edit.
Your problem is in short that there is no way to Connecticut specific input fields to different buttons.
What i would rather suggest is that you set the name of the buttons to action and the value as the value you already use for the hidden fields.
With this you also have to make a minor change in your html. Instead of:
<input type="submit" value="something" onclick="something">
Use this:
<button name="action" value="edit" onclick="something">Edit</button>
And the same goes for delete button
When you use button tag instead of input, you can set a value to the button which is different from the display, which makes it a cleaner PHP code when checking the value of $_POST['action'] afterwards
I want $id to increase by 1 every time the form is submitted. Then it should be appended to the array $users.
Why is this not working?
<?php
$users = array();
$id = 0;
if(isset($_POST["submit"])){
$id = $id + 1;
$users[] = $id;
}
echo "<pre>";
print_r($users);
echo "</pre>";
?>
<form action="random.php">
buy a ticket
<input type="submit" name="submit">
</form>
This is because once the PHP code stops executing the value of $id and $users is gone forever. HTTP and PHP is stateless. Once that page is processed it is gone and it is like it never existed. If you want to persist state you need to use a persistent data store like sessions or database.
<?php
session_start();
if(isset($_POST["submit"])){
if (!isset($_SESSION['users'])) { $_SESSION['users'] = 0 }
$_SESSION['users']++;
}
echo "<pre>";
print_r($_SESSION['users']);
echo "</pre>";
?>
<form action="random.php" method="post">
buy a ticket
<input type="submit" name="submit">
</form>
N.B.: Forms defaults to GET when a method isn't defined, therefore it needs the method="post" since you are working with POST variables.