Show error message when clicked on the like button - php

Hello I want to make a like system using PHP and MySQL when clicked on the like Button i also insert Data in the database but there is an error database value inserted but like value as 0 no increment and undefined error occurs . Can anybody help me solving this problem
There is my Like button code :
<?php
//// work with like box
$get_likes = mysqli_query($con,"SELECT * FROM `likes`");
if (mysqli_num_rows($get_likes)===1) {
$get = mysqli_fetch_assoc($get_likes);
// $uid = $get['uid'];
$total_likes = $get['total_likes'];
//echo $uid;
$total_likes = $total_likes + 1;
//echo $total_likes++;
}
if (isset($_POST['likebutton_'])) {
$like = mysqli_query($con,"UPDATE `likes` SET `total_likes` = '$total_likes'") or die(mysqli_error($con));
//$insert_Data = mysqli_query($con,"INSERT INTO `likes` (`uid`) VALUES('$username')") or die(mysqli_error($ocn));
header("Location:home.php");
}
else
{
echo "Error";
}
?>
this code work fine without insert Data
There is My liked with Data Insertd Code
<?php
////work with like box
$get_likes = mysqli_query($con,"SELECT * FROM `likes`");
if (mysqli_num_rows($get_likes)===1) {
$get = mysqli_fetch_assoc($get_likes);
// $uid = $get['uid'];
$total_likes = $get['total_likes'];
//echo $uid;
$total_likes = $total_likes + 1;
//echo $total_likes++;
}
if (isset($_POST['likebutton_'])) {
$like = mysqli_query($con,"UPDATE `likes` SET `total_likes` = '$total_likes'") or die(mysqli_error($con));
$insert_Data = mysqli_query($con,"INSERT INTO `likes` (`uid`) VALUES('$username')") or die(mysqli_error($ocn));
header("Location:home.php");
}
else
{
echo "Error";
}
?>
this is output i want to display my font-end page <?php echo $total_likes ;?> but it occur error
The error is Undefined Variable
I also try $total_likes="";
as global but still not work

Your code suffers from a race condition. What you should be doing is this pattern:
INSERT INTO likes (uid, total_likes) VALUES (?, 1)
ON DUPLICATE KEY SET total_likes=total_likes+1
Where you use bind_param to set the placeholder value to your UID.
Note that in your one query you set the total count of all likes to be +1. This is a huge mistake.

Related

PHP incrementing a var

I am building a car parking application in which different users have different numbers of parking spots. This number is set by an administrator in a database. The user can input a numberplate which then will be added to a database as well. What I want is that when a user has occupied all the spots, that he will not be able to insert any more number plates.
However, now I have the following code at the moment:
if(isset($_POST['number_plate'])){
$numberPlate = $_POST['number_plate'];
$user_id = $_SESSION['id'];
$query = mysql_query("SELECT `parking_spots` FROM `login` WHERE `id` = ".$user_id." ");
$row = mysql_fetch_assoc($query);
$totalNumberOfSpots = $row['parking_spots'];
$occupiedNumberOfSpots = 0;
$sql = "INSERT INTO amsterdam (numberplate, user_id) VALUES ('$numberPlate','$user_id')";
if(mysql_query($sql))
{
echo 'numberplate added';
$occupiedNumberOfSpots++;
if($occupiedNumberOfSpots == $totalNumberOfSpots)
{
echo "There are no more spots avialable";
}
}
else
{
echo 'Something went wrong!';
}
}
But when I echo the $occupiedNumberOfSpots variable it keeps returning 1 and does not increment every time I add numberplate.
How can I solve this issue?
It is because You are running the same code each time You add a plate to your db.
this:
$occupiedNumberOfSpots = 0;
should be taken from db as well. I guess it should be like that:
$totalNumberOfSpots = 100; // for example
$occupiedNumberOfSpots = $row['parking_spots']; // taken from db
instead of:
$totalNumberOfSpots = $row['parking_spots'];
$occupiedNumberOfSpots = 0;

Getting data from POST [id] form in PHP

On a table that displays data from a database, I have a form that has a text area on which a user can type a receipt number and submit to save in a database for a specif row. The PHP code below is what updates the database after the form is submitted.
I want to pick the rest of the details for the specific row so I used the $_POST['id'] on which the receipt has been submitted. The id is the primary key. I'm however having a challenge since I can't fetch data from the database using $id = $_POST['id'];I created before outside the function The update statement works perfectly but the SELECT STATEMENTdoesn't . How do I go about it? Any one?
if(isset($_POST['submit'])) {
$rec = $_POST['receipt'];
$id = $_POST['id'];
//reate connection
$sql = "UPDATE customer SET `receipt` = '".$_POST['receipt']."', `date_entered` = NOW(), `receipt_lock` = 1 WHERE `id` = '".$_POST['tid']."' AND receipt_lock = 0";
if ($conn->query($sql) === TRUE) {
// echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
exit();
$conn->close();
}
function wall(){
global $recp;
global $id;
// Create con
$sql = "SELECT * FROM customer WHERE id ='$id'";
$result1 = mysqli_query($conn, $sql);
$resultarr = mysqli_fetch_assoc($result1); // fetch data
$name = $resultarr['name'];
echo "$name"; //Does not display
$amount = $resultarr['amount'];
$transaction_id = $resultarr['trans_id'];
$date = $resultarr['time_paid'];
}
else {
echo "this is not right!;
}
wall();
Ignoring all the (valid) questions about SQL security and just addressing your problem - how about passing the $id variable as a parameter to your wall function.?
wall($id);
function wall($id){
$sql = "SELECT * FROM customer WHERE id ='$id'";
// ... use prepared statements for security...
...
}
Looks like you are using $_POST['tid'] instead of $_POST['id'] or $id in your SQL-query.
What you are doing there is a big nono, in terms of security. Make sure you escape your POST parameters before adding them inside your query.
$id = $_POST['id'];
$id = mysqli_real_escape_string($conn, $id);
http://php.net/manual/ro/mysqli.real-escape-string.php
Think about sending data as parameters of a function function wall($id) instead of a global parameter.

deleting records from mysql table

Continuing with my simple CRUD, I'm stuck again...
So I have a table created called "usuaris" and a column called "id" which is my auto-increment and then another column called "usuari_nom". Now, I want to add "delete function", so when I am displaying the records of my table I've added a to delete it:
<div id="main">
<?php
global $conn;
$query = "SELECT * FROM usuaris";
if($grup_usuaris = mysqli_query($conn, $query)) {
echo "<table>";
echo "<tr><th>Usuaris</th><th>Accions</th></tr>";
while($row = mysqli_fetch_assoc($grup_usuaris)) {
echo "<tr><td>" . $row['usuari_nom'] . "</td><td>Eliminar usuari</td></tr>";
}
echo "</table>";
echo "+ Afegeix Usuari";
mysqli_free_result($grup_usuaris);
} else {
echo "query failed";
echo("Error description: " . mysqli_error($conn));
}
?>
</div>
So now, If I click on "eliminar usuari" it goes to the file where I am adding the query to delete, plus the id of that user; for example: "http://localhost/calendario/elimina_usuari.php?subject=6". But then, in the file elimina_usuari.php, how do I select the id to know what record to delete?
I've thought with $_GET but it doesn't seems to work, either with $_POST:
elimina_usuari.php
<?php
global $conn;
$usuari_id = $_GET['id'];
$query = "DELETE FROM subjects WHERE id = {$usuari_id} LIMIT 1";
$result = mysqli_query($conn, $query);
if ($result && mysqli_affected_rows($conn) == 1) {
redirect_to("calendari.php");
} else {
echo "no eliminat";
}
?>
Any clue how can I get its id? Should I take it from the url somehow?
Thanks
you're doing fine.
just need to change this
$usuari_id = $_GET['id'];
to
$usuari_id = $_GET['subject'];
as you're setting subject instead of id in your url
http://localhost/calendario/elimina_usuari.php?subject=6
^
and if you want to process id, like $_GET['id'], you need to change URL.
"http://localhost/calendario/elimina_usuari.php?id=6"
^ change here
EDIT
as per your comment,
you can use any $variable to $_POST or $_GET, it has nothing to do with the database column name.
Like you can use following.
"http://localhost/calendario/elimina_usuari.php?eve_mf=6"
and on elimina_usuari.php page,
$id = $_GET['eve_mf'];
and second part, why can I do that and I don't need to call it id as it is called in my db table?
Again, it's not the issue what you call variables in you local environment, all you to do(and should take care of) is to put right parameters in your sql query.
$query = "DELETE FROM subjects WHERE id = {$usuari_id} LIMIT 1";
Here id is the name of your column name in your database. You can't change it here if you even want it to.
however, $usuari_id is your local variable, and you can change it whatever you want.
Hope I've explained what you're looking for :)
You can get the id with $_GET['subject'].
Please be aware about SQL injection as you are wrongly get the id of the user to be deleted:
$usuari_id = mysqli_real_escape_string($conn, $_GET['subject']);
<?php
global $conn;
$usuari_id = $_GET['subject'];
$query = "DELETE FROM subjects WHERE id = {$usuari_id} LIMIT 1";
$result = mysqli_query($conn, $query);
if ($result && mysqli_affected_rows($conn) == 1) {
redirect_to("calendari.php");
} else {
echo "no eliminat";
}
?>
You just need to Get the exact variable name or parameter name which you have sent with your url
I mean see your url contains subject=6
that means you have to get subject instead of id;
please replace this code
$usuari_id = $_GET['id'];
to
$usuari_id = $_GET['subject'];
try this in elimina_usurai.php
<?php
global $conn;
$usuari_id = $_GET['subject'];
$query = "DELETE FROM subjects WHERE id = {$usuari_id} LIMIT 1";
$result = mysqli_query($conn, $query);
if ($result && mysqli_affected_rows($conn) == 1) {
redirect_to("calendari.php");
} else {
echo "no eliminat";
}
?>

Updating Database if variable is less than variable

Basically I am trying to make it check if the user has their ID in the database and if they do have it in there it updates it putting $page as 'lastpage' in the database. It also checks to make sure that the value it has set inside there now is less than $page, if it isn't than it does nothing.
If the user doesn't have there ID in there than it should add it with whatever $page is set to.
The problem is that it isn't updating in the database at all.
This is the code I got so far, anyone got ideas?
session_start();
if(!isset($_SESSION['id'])) {
header("Location: ../../index.php");
} else {
}
include '../../connect.php';
include '../../users_func.php';
$id = $_SESSION['id'];
$page = 3;
$sql_chk = " select * from html where id = '$id' and lastpage = '$page' ";
$rs_chk = mysql_query($sql_chk);
$num_chk = mysql_num_rows($rs_chk);
if ($num_chk == 0) {
mysql_query("INSERT INTO `html` (`id`, `lastpage`) VALUES ('$id', '$page') ");
} else {
$sql = "UPDATE html SET lastpage='$page' WHERE id='$id' and lastpage < $page";
mysql_query($sql) or die("MYSQL Query Failed : " . mysql_error());
}
Your code is overly verbose, and those 3 queries would be replaced with a single
INSERT INTO html (id, lastpage) VALUES ($id, $page)
ON DUPLICATE KEY UPDATE lastpage = IF(lastpage < VALUES(lastpage), VALUES(lastpage), lastpage)
I know you are going to change the code to mysqli or PDO and all, but your existing code should check for errors
$result = mysql_query($sql);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
In your code, it's quite possible mysql_num_rows($rs_chk) is checking on an invalid resource $rs_chk.

Is this coding wrong it's not working properly

The below script inputs data to a database this takes some information from a form then stores them in to the database. And I'm also using uplodify to upload a image file and store the file name in the database but my issue is this data processing script keeps updating the row ID one never jumps to the second line I tried every thing can some one help me with this or show me what I'm doing wrong.
Also this checks the ID and if it's not equal to 1 then does an insertion if it's equal then update it but this not happening.
The ID is auto incrementing.
My script
<?php
/**
* #author SiNUX
* #copyright 2013
*/
include ('connect.php');
$getId = mysql_query("SELECT ID FROM poiinfo ORDER BY ID DESC LIMIT 1");
$row = mysql_fetch_array($getId);
$poiName = $_REQUEST['Name'];
$poiDes = $_REQUEST['Descrip'];
$poiCon = $_REQUEST['ConInfo'];
//$poiId = $_REQUEST['pID'];
if($row['ID'] != "1"){
$dbData = "INSERT INTO poiinfo(`Name`, `Des.`, `Contact`) VALUES ('$poiName','$poiDes','$poiCon')";
$putData = mysql_query($dbData);
if ($putData){
echo "Data inserted";
}else {
echo "Not Done";
}
}else {
$updLn = "UPDATE `poiinfo` SET `Name`='$poiName',`Des.`='$poiDes',`Contact`='$poiCon'";
$updDone = mysql_query($updLn);
if ($updDone){
echo "Data inserted";
}else {
echo "Not Done";
}
}
?>
I tried u r suggestions but it's still the same now my code for the update is looks like this.
$updLn = "UPDATE `poiinfo` SET `Name`='$poiName',`Des.`='$poiDes',`Contact`='$poiCon' WHERE `ID`='".$row['ID']."'";
But still it keeps up dating the ID 1 not moving on to the next one.
Your update query is missing a WHERE clause. Try this:
$updLn = "UPDATE `poiinfo` SET `Name`='$poiName',`Des.`='$poiDes',`Contact`='$poiCon' WHERE ID = '".$row['ID']."'";
Also be beware of MySQL Injections: http://en.wikipedia.org/wiki/SQL_injection
To check why your update failed, you should call mysql_error in your last else clause :
} else {
echo mysql_error();
}
As for the first problem : if you never insert a new record (I don't see how that could happen, provided your code), you will never have a record whose ID is 2.
$updLn = "UPDATE `poiinfo` SET `Name`='$poiName',`Des.`='$poiDes',`Contact`='$poiCon'";
You need a where clause in this sql to specify a record to update. Currently it is updating all records.
$updLn = "UPDATE `poiinfo` SET `Name`='$poiName',`Des.`='$poiDes',`Contact`='$poiCon' WHERE `ID` = ".$row['id']";";
You will need to set an $id variable for this to work.

Categories