PHP Script running without redirection - php

I have a database with two tables: accounts and recipes(each have their own ID column).
I have a page that displays all the recipes. I want to enable users to add recipes to their favourites in accounts table. Once user is logged in, $_SESSION['user_id'] is set.
I have script that will add the recipe id to the favourites in accounts table, but I don't know how to run it without redirecting from the page that displays all recipes.
Here is what i have so far:
_view.php
<?php
$result = $mysqli->query("SELECT * FROM recipes");
if ( $result->num_rows == 0 ){
$_SESSION['message'] = "Error!";
echo "<div class='error-mess'>" . $_SESSION['message'] . "</div>";
}
else {
while ($row = mysqli_fetch_array($result)) {
$slug = $row['slug'];
$ingr = json_decode($row['ingr']);
$ingr_count= count($ingr);
$id = $row['id'];
echo '<div class="container recipe mb-2">';
echo '<img class="" src="/images/recipes/';
echo $row['img'];
echo '"/>';
echo '<div class="title-cats"><a href = "/recipe_preview.php?slug=' . $slug . '">';
echo $row['title'];
echo '</a></div>';
echo '<h4>Ingredients:</h4><br>';
for($i = 0; $i<$ingr_count;$i++){
$num = $i + 1;
echo $num . '. ';
$ingrs = json_decode($ingr[$i],true);
print_r($ingrs[0]);
echo '<br>';
}
echo '<br><button type="submit" class="btn" name="add">Read More</button>';
//favourites link
echo '<span class="fa fa-heart ml-3"></span>';
echo '</div><hr>';
}
}
_favourite.php
<?php
//relationship
require 'db.php';
$user_id = $_SESSION['user_id'];
//$favourite_id = $_POST['fav'];
$favourite_id = $_GET["id"];
echo $favourite_id;
echo $user_id;
$result = $mysqli->query("SELECT favourites FROM accounts WHERE id ='$user_id'");
if ( $result === null) {//doesnt work
$favs = array();
array_push($favs,$favourite_id);
$new_favs = json_encode($favs);
echo 'null';
}
else{
$favs = array();
$result = json_decode($result,true);
array_push($favs, $result);
array_push($favs,$favourite_id);
$new_favs = json_encode($favs);
}
$sql = "UPDATE accounts SET favourites ='$new_favs' WHERE id = '$user_id'";
if ( $mysqli->query($sql)){
echo '<div class="error-mess">Recipe sucessfully saved!</div>';
}
else{
echo '<div class="error-mess">NOT</div>';
}
.js -jquery library is there
$(document).ready(function() {
$('#favourite').click(function(e) {
e.preventDefault(); // prevents the default behaviour of following the link
$.ajax({
type: 'GET',
url: $(this).attr('href'),
data: {
id: $(this).data('id'),
},
dataType: 'text',
success: function(data) {
// do whatever here
if(data === 'success') {
alert('Updated succeeded');
} else {
alert(data); // perhaps an error message?
}
}
});
});
});

Related

Item isn't deleted from database through ajax call

I'm running around the issue which I don't really know how to solve - I simply want to remove uploaded file from the database, but I'm failing to do so.
My personal guess now is that my delete_shop_item.php doesn't work or that upload.php loop messes up the deletion process from the database (but that's only my guess).
Ajax:
$(document).on('click', '#rmvBtn', function() { /*press the button to remove selected item*/
del_title = $("#"+ $("#selectOpt").val()); /* select dynamically generated option to remove*/
$.ajax({
type: 'POST',
url: 'delete_shop_item.php',
cache: false,
processData: false,
data: {title:del_title.val()},
success: function() {
$("#" + $("#selectOpt").val()).remove();
$("#selectOpt option:selected").remove();
}
});
delete_shop_item.php
$title = $_POST['title'];
$pdo = new PDO('mysql:host=localhost;dbname=project', 'root', '');
$query = 'DELETE FROM photos WHERE title = :title';
$stmt = $pdo->prepare($query);
$stmt->bindPARAM(':title', $title);
$stmt->execute();
upload.php
<?php $count = 1;
while($data = mysqli_fetch_array($result)) {
if($count === 1) {
echo "<div class='img_container'>";
}
echo "<div class='img_div' id='".$data['title']."'>";
echo "<img src='uploads/" . $data['filename']."'>";
echo "<p class='img_title' >" .$data['title']. "</p>";
echo "<p class='img_desc'>" .$data['photo_description']. "</p>";
echo "<p>" .$data['price']. "</p>";
echo "</div>";
if($count % 5 === 0) {
echo "</div>";
$count = 1;
continue;
}
$count++;
}
?>
try data: {title:del_title} in ajax request

How to delete receiver name and our messages in my messaging code in the display page?

Messages I want to delete a receiver name and our messages or the entire receiver row in the database in the display page.I have 2 codes to show, 1st is the displaying page, next is the delete page. When I press the x image, it will not delete any receiver name and our messages. I wonder if the request id in the index.php I made is effective or not. Consider my codes below:
main page / index.php
$q = 'SELECT DISTINCT `receiver_name`,`sender_name`,`id`
FROM `messages` WHERE
`sender_name`="' . $_SESSION['username'] . '" OR
`receiver_name`="' . $_SESSION['username'] . '"
ORDER BY `date_time` DESC';
$r = mysqli_query($con, $q);
if ($r) {
if (mysqli_num_rows($r) > 0) {
$counter = 0;
$added_user = array();
while ($row = mysqli_fetch_assoc($r)) {
$sender_name = $row['sender_name'];
$receiver_name = $row['receiver_name'];
$id = $row['id'];
if ($_SESSION['username'] == $sender_name) {
//add the receiver_name but only once
//so to do that check the user in array
if (in_array($receiver_name, $added_user)) {
//dont add receiver_name because
//he is already added
} else {
//add the receiver_name
?>
<div class="grey-back">
<img src="images/profile_user.jpg" class="image"/>
<?php echo '' . $receiver_name . '';
echo '<img src="x.png" style="width:12px; height:12px; float:right;">';
?>
</div>
<?php
//as receiver_name added so
///add it to the array as well
$added_user = array($counter => $receiver_name);
//increment the counter
$counter++;
}
} elseif ($_SESSION['username'] == $receiver_name) {
//add the sender_name but only once
//so to do that check the user in array
if (in_array($sender_name, $added_user)) {
//dont add sender_name because
//he is already added
} else {
//add the sender_name
?>
<div class="grey-back">
<img src="images/profile_user.jpg" class="image"/>
<?php echo '' . $sender_name . ''; ?>
</div>
<?php
//as sender_name added so
///add it to the array as well
$added_user = array($counter => $sender_name);
//increment the counter
$counter++;
}
}
}
} else {
//no message sent
echo '<div style="float:left; padding: 70px 0 0 150px;">';
echo 'no user';
echo '</div>';
}
} else {
//query problem
echo $q;
}
delete page
require_once "connection.php";
$id = $_REQUEST['id'];
mysqli_query($con, "DELETE FROM messages WHERE id=$id");
header("location: index.php");
I see one problem:
echo '<img src="x.png" style="width:12px; height:12px; float:right;">';
will output
<img src="x.png" style="width:12px; height:12px; float:right;">
but if $id=76, I'd guess you want it to be:
To do that try:
echo '';
And if $id is something more complex, with symbols & whatnot, then id='.$id.' becomes id='.urlencode($id).'.
That might be your problem. If it still doesn't work, let me know what output & error messages you are getting

Incrementing a mysql value by one on click with AJAX?

I'm very new to AJAX and PHP. I'm trying to implement a "like" feature on a website where users can post memes. The user should be able to click a heart-shaped image to "like" next to a meme and the "likes" value for that particular meme should increase by one in the MySQL database, however, it is not doing anything.
The MySQL table is called meme_information and it has 5 columns, "name", "email", "likes", "image_path", and "id" which is the primary key and auto increments.
Below is the code for the page where all the memes are displayed. There is some html above that I left out, but it is just the navbar and sourcing in files. I am pretty sure that the "data" value in the AJAX is wrong, but I'm not sure what I'm supposed to put in there.
browse.php
<?php
include("connecttodb.php");
$files = glob("uploads/*.*");
for ($i=0; $i<count($files); $i++) {
$image = $files[$i];
$supported_file = array(
'gif',
'jpg',
'jpeg',
'png'
);
$image = $files[$i];
$path = substr($image,8);
$q = "SELECT name, email, id FROM meme_information WHERE image_path= \"$path\"";
$id = 0;
$result = $link->query($q);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "Name: ". $row["name"] ."<br>";
echo "Email: ". $row["email"] ."<br>";
echo "Id: ". $row["id"] . "<br>";
$id = $row["id"];
}
}
echo '<img src="'.$image.'" style="width:400px;height:400px;"></img>';
echo '<img onclick="myFunction()" src="heart-unclicked.png" style="width:50px;height:50px;">like</img>';
echo
'<script>
function myFunction() {
$.ajax({
type: "POST",
url: "update_likes.php",
data: {"increment_by": 1},
success: function() {
alert("works");
},
error: function() {
alert("doesnt work");
},
});
}
</script>';
}
?>
I believe the part after WHERE in the SQL query is wrong. Not sure how I can get the id number from the meme that was "liked."
update_likes.php
<?php
require('connecttodb.php');
$q2 = "UPDATE meme_information SET likes = likes + 1 WHERE id='".$id."'";
echo "The id is $id" . "<br>";
$result = mysqli_query($link, $q2);
echo "<br> this is the id" . "$result";
?>
connecttodb.php
<?php
global $link;
include("dbconnect.php");
$link = new mysqli($server,$user,$password,$dbname);
if ($link->connect_errno) {
die("Connection failed: " . $link->connect_error);
} else {
print"Connection successful.";
}
?>
This might solve the issue.
<?php
include("connecttodb.php");
$files = glob("uploads/*.*");
for ($i=0; $i<count($files); $i++) {
$image = $files[$i];
$supported_file = array(
'gif',
'jpg',
'jpeg',
'png'
);
$image = $files[$i];
$path = substr($image,8);
echo '<img src="'.$image.'" style="width:400px;height:400px;"></img>';
$q = "SELECT name, email, id FROM meme_information WHERE image_path= \"$path\"";
$id = 0;
$result = $link->query($q);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "Name: ". $row["name"] ."<br>";
echo "Email: ". $row["email"] ."<br>";
echo "Id: ". $row["id"] . "<br>";
$id = $row["id"];
echo '<img onclick="myFunction('.$id.')" src="heart-unclicked.png" style="width:50px;height:50px;">like</img>';
}
}
echo
'<script>
function myFunction(id) {
$.ajax({
type: "POST",
url: "update_likes.php",
data: {"increment_by": 1,"id": id},
success: function() {
alert("works");
},
error: function() {
alert("doesnt work");
},
});
}
</script>';
}
?>
update_likes.php
<?php
require('connecttodb.php');
if(isset($_POST['id']))
{
$q2 = "UPDATE meme_information SET likes = likes + 1 WHERE id='".$_POST['id']."'";
echo "The id is $id" . "<br>";
$result = mysqli_query($link, $q2);
echo "<br> this is the id" . "$result";
}
?>

change cell value on button click

I have a table with the following.
Table parts_stock
*--------------------*
| id | sku | stock |
| 1 | 101 | 2 |
| 2 | 102 | 3 |
*--------------------*
This is my code so far, i'm sure there are many ways to achieve this but ideally I want the qty value to change based on which button is clicked on without the page being refreshed (AJAX probably).
<tbody>
<?php
$query = 'SELECT stock_id, sku, in_stock ';
$query .= 'FROM parts_stock';
confirmQuery($query);
$select_skus = mysqli_query($connection, $query);
$num = mysqli_num_rows($select_skus);
if($num>0) {
while($row = mysqli_fetch_assoc($select_skus)) {
$id = $row['stock_id'];
$sku = $row['sku'];
$qty = $row['in_stock'];
echo "<tr>";
echo "<td>".$sku."</td>";
echo "<td>".$qty."</td>";
echo "<td>
<a href='' onclick='rem_qty()' id='minus' name='minus' class='btn btn-warning'><span class='glyphicon glyphicon-minus'></span></a>
<a href='' onclick='add_qty()' id='plus' name='plus' class='btn btn-success'><span class='glyphicon glyphicon-plus'></span></a>
</td>";
</td>";
}
}?>
</tbody>
ajax_search.js
<script>
function rem_qty(){
$.ajax({
type: "POST",
url: "update_qty.php",
data: {id_m: stock_id}
});
}
function add_qty(){
$.ajax({
type: "POST",
url: "update_qty.php",
data: 'id_p: stock_id'
});
}
</script>
update_qty.php file
<?php
if (isset($_POST['id_m'])) {
$r = $_POST['id_m'];
echo $r;
$cur_inv = "SELECT in_stock FROM parts_stock WHERE stock_id = '".$r."'";
$cur_query = mysqli_query($connection, $cur_inv);
while ($row = mysqli_fetch_assoc($cur_query)) {
$rem_stock = $row['in_stock'];
$rem_stock -= 1;
}
$inv_update = "UPDATE parts_stock SET in_stock = '".$rem_stock."' WHERE stock_id = '".$value."'";
$inv_query = mysqli_query($connection, $inv_update);
}
if (isset($_POST['id_p'])) {
$a = $_POST['id_p'];
echo $a;
$cur_inv = "SELECT in_stock FROM parts_stock WHERE stock_id = '".$a."'";
$cur_query = mysqli_query($connection, $cur_inv);
while ($row = mysqli_fetch_assoc($cur_query)) {
$add_stock = $row['in_stock'];
$add_stock -= 1;
}
$inv_update = "UPDATE parts_stock SET in_stock = '".$add_stock."' WHERE stock_id = '".$value."'";
}
?>
A simple and complete solution: just change mysqli_connect config in both page
index.php
<?php
$connection = mysqli_connect("localhost", "root", "", "dbname"); //change dbname
$query = 'SELECT id, sku, stock FROM parts_stock';
//confirmQuery($query);
$select_skus = mysqli_query($connection, $query);
$num = mysqli_num_rows($select_skus);
?>
<table>
<tr>
<th>Sku</th>
<th>Stock</th>
<th>Action</th>
</tr>
<?php if($num>0){
while($row = mysqli_fetch_assoc($select_skus)) {
$id = $row['id'];
$sku = $row['sku'];
$qty = $row['stock'];
echo "<tr>";
echo "<td>".$sku."</td>";
echo "<td class='stock-{$id}'>".$qty."</td>";
echo "<td>
<a class='btn btn-warning' onclick='add_qty({$id})' href='#'><span class='glyphicon glyphicon-minus'>Value Add</span></a>
<a class='btn btn-success' onclick='rem_qty({$id})' href='#'><span class='glyphicon glyphicon-plus'>Value Deduct</span></a>
</td>";
echo "</tr>" ;
}
}?>
</table>
<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
<script type="text/javascript">
function add_qty(id){
$.ajax({
type: "POST",
url: 'update_qty.php', //Relative or absolute path to response.php file
data: {id:id, type:'add'},
dataType: "json",
success: function (data) {
console.log(data);
if(data.success){
//successfully added
$(".stock-"+id).html(data.data.stock);
alert(data.msg);
}
}
});
}
function rem_qty(id){
$.ajax({
type: "POST",
url: 'update_qty.php', //Relative or absolute path to response.php file
data: {id:id, type:'rem'},
dataType: "json",
success: function (data) {
console.log(data);
if(data.success){
//successfully added
$(".stock-"+id).html(data.data.stock);
alert(data.msg);
}
}
});
}
</script>
update_qty.php
<?php
$connection = mysqli_connect("localhost", "root", "", "dbname"); ////change dbname
header('Content-Type: application/json');
$success = false; $msg ="";
if (isset($_POST['id'])) {
$id = $_POST['id'];
$cur_inv = "SELECT * FROM parts_stock WHERE id ={$id}";
$cur_query = mysqli_query($connection, $cur_inv);
if(mysqli_num_rows($cur_query)>0){ //if id is exist in database
if($_POST['type']=="add"){
$inv_update = "UPDATE parts_stock SET stock = (stock+1) WHERE id = {$id}"; //increase your stock dynamically
}elseif($_POST['type']=="rem"){
$inv_update = "UPDATE parts_stock SET stock = (stock-1) WHERE id = {$id}"; //increase your stock dynamically
}
$inv_query = mysqli_query($connection, $inv_update);
if($inv_query){ //If sucess
$msg = "Successfully Updated";
$success = true;
}else{ //if failed
$msg = "Failed to Update";
}
}else{
$msg="Id is not found.";
}
$last_inv = "SELECT * FROM parts_stock WHERE id ={$id}";
$last_query = mysqli_query($connection, $last_inv);
$row = mysqli_fetch_assoc($last_query);
echo json_encode(array('success'=>$success, 'msg'=>$msg, 'data'=>$row));
}
?>
No need extra js file just index.php and update_qty.php
Working example
demo.php
<?php
$query = 'SELECT id, sku, stock ';
$query .= 'FROM parts_stock';
confirmQuery($query);
$select_skus = mysqli_query($connection, $query);
$num = mysqli_num_rows($select_skus);
if($num>0) {
while($row = mysqli_fetch_assoc($select_skus)) {
$id = $row['id'];
$sku = $row['sku'];
$qty = $row['stock'];
$data = "";
$data .= "<tr>";
$data .= "<td>{$sku}</td>";
$data .= "<td>{$qty}</td>";
$data .= "<td>
<a class='btn btn-warning' href='inventory.php?source=edit_inventory&id={$id}'><span class='glyphicon glyphicon-minus'></span></a>
<a class='btn btn-success' href='inventory.php?source=edit_inventory&id={$id}'><span class='glyphicon glyphicon-plus'></span></a>
</td>";
echo $a;
exit;
}
}?>
AJAX:
<!DOCTYPE html>
<html>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"> </script>
<table >
<tr>
<th>Id</th>
<th>Sku</th>
<th>Qty</th>
</tr>
<tbody id="mytable">
</tbody>
</table>
<button id="clickme">Click</button>
<script>
$(document).ready(function(){
$("#clickme").click(function() {
$.ajax({
url:"demo.php",
type:"GET",
beforeSend:function() {
$("#mytable").empty();
},
success:function(response){
$("#mytable").append(response);
}, error:function(err) {
console.log(err);
}
})
});
});
In your HTML Button to have a onClick event like this onclick="buttonSubtract1('<?php if(isset($val['itm_code'])){echo $val['itm_code'];}?>')"(You can fetch the itm_code from your db).Then Write your AJAX for Request and Response. And You need to Pass the itm_code through var x. e.g for like this xmlhttp.open("POST", "ajax/get_items.php?val=" +x, true);
In AJAX file
$item_cat = $_SESSION['item_cat']; // get a category from session
$iname=$_GET['val']; //get the value from main php file
if(!key_exists($item_cat)
{
$_SESSION['main'][$iname] = "1";
}
else
{
$_SESSION['main'][$item_cat][$iname]++;
}
echo "<pre>";
print_r($_SESSION['main']);
echo "</pre>";
EDIT 1
function buttonSubtract1(x)
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.location.assign('items.php');
}
}
xmlhttp.open("POST", "ajax/get_items.php?val=" +x, true);
xmlhttp.send();
}

How to add update, delete and view button in my php rows

I want to add "update", "delete" and "view" in the other page button in the right side of the table rows of my php table. Please help me to add it. Here is my code:
<?php
$conn = mysqli_connect('localhost','root','','dbname');
if(mysqli_connect_errno()){
echo 'Failed to connect: '.mysqli_connect_error();
}
$query = "SELECT * FROM table";
$results = mysqli_query($conn,$results);
echo '<table border="1">';
echo '<tr>';
echo "<th>Firstname</th>";
echo "<th>Lastname</th>";
echo '</tr>';
while($row=mysqli_fetch_array($results)){
echo '<tr>';
echo '<td>'.$row['Firstname'].'</td>';
echo '<td>'.$row['Lastname'].'</td>';
echo '</tr>';
}
echo '</table>';
mysqli_close($conn);
?>
echo '<tr>';
echo "<th>Firstname</th>";
echo "<th>Lastname</th>";
echo "<th>Actions</th>";
echo '</tr>';
while($row=mysqli_fetch_array($results)){
echo '<tr>';
echo '<td>'.$row['Firstname'].'</td>';
echo '<td>'.$row['Lastname'].'</td>';
echo "<td>
Update
Delete
View
</td>";
echo '</tr>';
}
echo '</table>';
You should use jquery/Ajax for delete. It is better option.
For delete write this function: Need to add min jquery file
<script src="js/jquery-1.7.1.min.js"></script>
<script>
function deleteRow(id)
{
$.ajax({
url: 'delete.php',
type: "POST",
data: {
'id' : id,
},
success : function(response) {
alert('Record deleted');
},
error : function() {
},
complete : function() {
}
});
}
</script>
write your delete record code in 'delete.php'.
This is one option. You can do this in more good and specific way. Everything to say here is not possible for me.
for view you can do this in two ways.
1) If you want to display in same format, redirect it on self page and put condition like.
if(isset($_POST['id'])
{
$id = $_POST['id'];
$query = "SELECT * FROM table where id=$id";
}
else
{
$query = "SELECT * FROM table";
}
2) If you want in different format, Do same thing in view.php select only that record.
One simple thing i want to ask what is the need for view? when it is already in table above.
For Update write in your update.php :
if(isset($_POST['id'])
{
$id = $_POST['id'];
$query = "SELECT * FROM table where id=$id";
}
and set form action
<form method="post" action="<?php echo esc_url($_SERVER['PHP_SELF']); ?>">
fetch value of above result in input box like and also fetch id as hiiden field:
<input type='text' name='firstname' value='<?php echo $row['firstname']; ?>
<input type='hidden' name='id' value='<?php echo $row['id']; ?>
and for update you can go like:
if(isset($_POST['firstname'] && isset($_POST['lastname'] ) // Here you can use your any required field
{
//Your update logic go here like:
$id = $_POST['id'];
$query = "UPDATE table SET firstname=$_POST['firstname'] where id=$id"; // Your whole update query.
}
i see some mistake in your code:
$query = "SELECT * FROM table";
$results = mysqli_query($conn,$results);
should be:
$query = "SELECT * FROM table";
$results = mysqli_query($conn,$query);
try this
echo '<table border="1">';
echo '<tr>';
echo "<th>Firstname</th>";
echo "<th>Lastname</th>";
echo "<th></th>";
echo '</tr>';
while($row=mysqli_fetch_array($results)){
echo '<tr>';
echo '<td>'.$row['Firstname'].'</td>';
echo '<td>'.$row['Lastname'].'</td>';
echo "<td>
<input type='submit' value='update'>
<input type='submit' value='delete'>
<input type='submit' value='view'>
</td>";
echo '</tr>';
}
echo '</table>';
Try this functions:
<?php
Class Db {
protected $connection;
public function __construct() {
$this->connection = $connection;
}
function insert($table,array $data) {
$fields = '';$values = '';
foreach($data as $col => $value) {
$fields.= $col.",";
}
foreach($data as $col => $value) {
$values.= "'".replace_str($value)."',";
}
$fields = substr($fields,0,-1);
$values = substr($values,0,-1);
if(!$query = mysqli_query($this->connection,"insert into ".$table."(".$fields.") values(".$values.")")) {
HandleDBError("Error inserting data to the table\query:$query");
}
return $query;
}
function update($table, array $data, $where) {
$fields = '';$values = '';
foreach($data as $col => $value) {
$values.= $col."='".replace_str($value)."',";
}
$values = substr($values,0,-1);
if(!$query = mysqli_query($this->connection,"update ".$table." set ".$values." where ".$where)) {
HandleDBError("Error updating data to the table\query:$query");
}
return $query;
}
function delete($table, $where = '') {
if ($where)
return mysqli_query($this->connection,"delete from ".$table." where ".$where);
return mysqli_query($this->connection,"delete from ".$table);
}
function get($strQuery) {
if(!$query = mysqli_query($this->connection,$strQuery)) {
HandleDBError("Error inserting data to the table\query:$query");
}
$data = [];
while($row = mysqli_fetch_assoc($query)) {
$data[] = $row;
}
return $data;
}
}
?>

Categories