This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 7 years ago.
I am trying to build a click button that increments value of the item in the database. I am using UPDATE method for this.
The problem is that whenever the update query is run, the value it takes from the databse to increment (or decrement) is zero. (0+1 = 1, 0-1 = -1)
require_once("C:/xampp/htdocs/Selfie/database/dbcontroller.php");
$db_handle = new DBController();
$image_id = $_POST["image_id"];
$active_user_id = $_POST["active_user_id"];
$query = "SELECT user_image_id from users where user_id='" . $active_user_id . "'";
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
if ($row['user_image_id'] == $image_id) {
echo "own image";
}
else
{
$query = "SELECT image_id from hearts where user_id='" . $active_user_id . "'";
$result = mysql_query($query);
if ($row = mysql_fetch_assoc($result)) {
if ($row['image_id'] == $image_id) {
$query = "UPDATE images SET image_hearts='image_hearts'-1 where image_id=" . $image_id;
$result = mysql_query($query);
$query = "DELETE FROM hearts WHERE user_id=" . $active_user_id;
$result = mysql_query($query);
$query = "UPDATE users SET user_like ='' where user_id=" . $active_user_id;
$result = mysql_query($query);
echo "just unlike";
}
else
{
$query = "DELETE FROM hearts WHERE user_id=" . $active_user_id;
$result = mysql_query($query);
$query = "UPDATE images SET image_hearts='image_hearts'-1 where image_id=" . $row['user_image_id'];
$result = mysql_query($query);
$query = "Select image_path from images where image_id=" . $image_id;
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
$query = "UPDATE users SET user_like ='" . $row["image_path"] . " where user_id=" . $active_user_id;
$result = mysql_query($query);
$query = "UPDATE images SET image_hearts='image_hearts'+1 where image_id=" . $image_id;
$result = mysql_query($query);
$query = "INSERT INTO hearts (image_id , user_id) VALUES ('$image_id','$active_user_id')";
$result = mysql_query($query);
echo "unlike then like";
}
}
else
{
$query = "INSERT INTO hearts (image_id , user_id) VALUES ('$image_id','$active_user_id')";
$result = mysql_query($query);
$query = "UPDATE images SET image_hearts='image_hearts'+1 where image_id=" . $image_id;
$result = mysql_query($query);
$query = "Select image_path from images where image_id=" . $image_id;
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
$query = "UPDATE users SET user_like ='" . $row["image_path"] . "' where user_id=" . $active_user_id;
$result = mysql_query($query);
echo "image liked successfully.";
}
}
This is my jQuery code:
function test_click(i_image_id, i_heart_id, i_active_user_id) {
var active_user_id = i_active_user_id;
var image_id = i_image_id;
var heart_id = i_heart_id;
jQuery.ajax({
url: "../Selfie/validations/add_like.php",
data: {
active_user_id: active_user_id,
image_id: image_id
},
type: "POST",
success: function(data) {
if (data == "own image")
{
alert('You are trying to like your own image You NARCISSIST');
}
else if (data == "just unlike")
{
$("*").removeClass("btn-heart-red animated bounce fa-heart-red");
alert('just unlike');
}
else
{
$("*").removeClass("btn-heart-red animated bounce fa-heart-red");
$("#" + heart_id).removeClass("animated rubberBand");
$("#" + heart_id).toggleClass("btn-heart-red animated bounce fa-heart-red");
}
alert(data);
}
});
}
This image_hearts='image_hearts'+1 remove the quotes; that's a column you're wanting to update and not the string literal. The same thing goes for 'image_hearts'-1
Check for errors on your queries, which would have helped you here.
http://php.net/manual/en/function.mysql-error.php
Plus, your present code is open to SQL injection. Use mysqli with prepared statements, or PDO with prepared statements.
mysql_* functions deprecation notice:
http://www.php.net/manual/en/intro.mysql.php
This extension is deprecated as of PHP 5.5.0 and removed as of PHP 7.0, and is not recommended for writing new code as it will be removed in the future. Instead, either the mysqli or PDO_MySQL extension should be used. See also the MySQL API Overview for further help while choosing a MySQL API.
These functions allow you to access MySQL database servers. More information about MySQL can be found at » http://www.mysql.com/.
Documentation for MySQL can be found at » http://dev.mysql.com/doc/.
Footnotes:
If I may quote Marc's comment:
"in other words. 'image_hearts' + 1 is string literal plus integer, and unless that string literal contains digits at the start of it, will simply become 0 + 1 – Marc B"
Related
So I am trying to do an history for my site but when i do the query select with the jquery variable it doesn't work. HERE is the table that shows the values from db and here is the pop up box that opens to show details but I want to show the values from each row that I click
Here is the jquery code:
var idocorrencia;
$(document).on("click","#listagem tr td a", function(e){
e.preventDefault();
idocorrencia = $(this).parent().attr("idlista");
$("#listagem caption").text($(this).text());
console.log(idocorrencia);
alert(idocorrencia);
$.post( "historico.php", { idoc: idocorrencia })
$.ajax({
method:"POST",
url:"historico.php",
data:{idoc : "idlista"},
dataType: 'json',
});
});
Here is the php:
$id = $_POST['idoc'];
$result = mysqli_query($conn, "SELECT id FROM ocorrencia where id=$id");
$row = mysqli_fetch_assoc($result);
$idoc = isset($_POST['idoc']) ? $_POST['idoc'] : $row['id'];
Try to do it like this:
if (isset($_POST['idoc'])) {
$id = $_POST['idoc'];
$result = mysqli_query($conn, "SELECT id FROM ocorrencia where id='" . mysqli_real_escape_string($conn, $id) . "'");
if($result!==false && mysqli_num_rows($result)>0){
$row = mysqli_fetch_assoc($result);
$idoc = $row['id'];
}
}
UPDATE
and here is the same script with prepared statements:
if (isset($_POST['idoc'])) {
$statement = mysqli_prepare($conn, "SELECT id FROM ocorrencia where id=?");
mysqli_stmt_bind_param($statement, 's', $id);
$id = $_POST['idoc'];
mysqli_stmt_execute($statement);
$result = mysqli_stmt_get_result($statement);
if ($result !== false && mysqli_num_rows($result) > 0) {
$row = mysqli_fetch_assoc($result);
$idoc = $row['id'];
}
}
Here I have used procedural style, as the original script was like that. But it can be easily rewritten in object oriented style.
Every time I get a visit to my index page I need to check if a record exists already in my database, if it does, it will need to update the field 'count' if not it will add a row.
I've managed to get it to create a row on visit, but cant seem to get it to update the count if the row already exists.
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// Check to see if record exists
$sql = "SELECT * FROM page_tracking where name ="index.php"";
if (mysqli_query ($conn, $sql)) {
$sql= "UPDATE page_tracking SET count=count+1 where name= "index.php")";
}
else if {
//Insert Query
$sql = "INSERT INTO page_tracking (name, count)
VALUES ('index.php', '1')";
}
if (mysqli_query($conn, $sql)) {
echo "Thanks for visiting! Your visit has been recorded";
} else {
echo "Unfortunately we were unable to record your visit: " . $sql . "<br>" . mysqli_error($conn);
}
There's probably a really simple explanation! Issue is definitely with the code for 'check to see if record exists'
1) Dont use double quotes around index.php use single quotes.
Just run update query
$sql = "SELECT * FROM page_tracking where name ="index.php"";
$result = mysqli_query ($conn, $sql);
$num_rows = mysqli_num_rows($result);
if ($num_rows) {
$sql= "UPDATE page_tracking SET count=count+1 where name= 'index.php'";
}else{
$sql = "INSERT INTO page_tracking (name, count) VALUES ('index.php', '1')";
}
if (mysqli_query($conn, $sql)) {
echo "Thanks for visiting! Your visit has been recorded";
} else {
echo "Unfortunately we were unable to record your visit: " . $sql . "<br>" . mysqli_error($conn);
}
Get the results and check whether it has records.
// Check to see if record exists
$sql = "SELECT * FROM page_tracking where name ="index.php"";
$query = mysqli_query ($conn, $sql);
$result=mysqli_fetch_all($query,MYSQLI_ASSOC);
if (count($result) > 0) {
$sql= "UPDATE page_tracking SET count=count+1 where name="index.php")";
}
else {
//Insert Query
$sql = "INSERT INTO page_tracking (name, count)
VALUES ('index.php', '1')";
}
In your code, you never executed the query. Only created it in a string.
if (mysqli_query ($conn, $sql)) {
$sql= "UPDATE page_tracking SET count=count+1 where name= "index.php")";
# execute the query
}
Also, not sure why this loose else if without a condition:
else if {
//Insert Query
An you may want to checkout the INSERT ... ON DUPLICATE KEY UPDATE statement, which can reduce your whole code to a single query if the file name is your unique key:
mysqli_query ($conn, "
INSERT INTO page_tracking (name, count)
VALUES ('index.php', 1)
ON DUPLICATE KEY UPDATE count=count+1
");
Please try this. Use single quote instead of double quote.
$link = mysql_connect("localhost", $mysql_user, $mysql_password);
mysql_select_db($database, $link);
$result = mysql_query("SELECT * FROM page_tracking where name ='index.php'", $link);
$num_rows = mysql_num_rows($result);
if($num_rows==1){
//Update Query
}else{
//Insert Query
}
$from = $_POST['from'];
$to = $_POST['to'];
$message = $_POST['message'];
$query = "SELECT * FROM Users WHERE `user_name` = '$from' LIMIT 1";
$result = mysql_query($query);
while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$fromID = $row['user_id'];
}
I'm trying to have $formID be the user_id for a user in my database. Each row in the Users table is like:
user_id | user_name | user_type
1 | Hristo | Agent
So I want $from = 1 but the above code isn't working. Any ideas why?
Try this:
$from = mysql_real_escape_string($_POST['from']);
$to = mysql_real_escape_string($_POST['to']);
$message = mysql_real_escape_string($_POST['message']);
$query = "SELECT * FROM Users WHERE user_name = '$from' LIMIT 1";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_assoc($result)) {
$fromID = $row['user_id'];
}
Also, make sure that:
You have connected to the database
You do get data from the post, try var_dump with your vars eg var_dump($from)
Use mysql_fetch_assoc instead
while($row =mysql_fetch_assoc($result)){ $fromID = $row['user_id'];
}
though it should.
try this code
$from = mysql_real_escape_string($_POST['from']);
$to = mysql_real_escape_string($_POST['to']);
$message = mysql_real_escape_string($_POST['message']);
$query = "SELECT * FROM Users WHERE `user_name` = '$from' LIMIT 1";
$result = mysql_query($query) or trigger_error(mysql_error().$query);
$row = mysql_fetch_array($result, MYSQL_ASSOC);
$fromID = $row['user_id'];
echo $fromID;
if it will throw no errors but still print no id, add this line
var_dump($row);
and post here it's output
not that you shouldn't use a user name but user id to address particular user.
I am having trouble executing SQL via AJAX when a dropdown box is changed and would like some help if possible.
Background Info
I have been tasked with creating a daily calendar that shows all the classes ran at a gym, which at its maximum is 5 x classes of 6 (30) people per hour for 14 hours.I'm no pro and I may have created a convoluted way around this issue, please let me know if i have.
I have managed to create the view which consists of 14 columns of 30 drop down boxes (5 x classes of 6 per hour for 14 hours). Each drop down box polls the db and if an entry resides it will populate the box with the name of the bookinguser. If no booking is found it will create a drop downbox that polls the members table and presents all the members of the gym, which when changed, will hopefully book that person in. - herein lies my current issue!
Each drop down box's name corresponds to the time, group and headcount which I intend on passing to javascript function and eventually to the SQL statement. Each option's value corresponds with the memberid which will also be passed giving all the information needed to construct the SQL.
The code I have so far
HTML - snipped generated from php loops
<div id="results">
<div id="07" class="column">07:00<br/>
<div id="group1">
<select name="07:00-1-0" onchange="getda(this.value,this)">
<option value="none">---------------</option>
<option value="2">John Doe</option>
<option value="1">Joe Bloggs</option>
</select>
<select name="07:00-1-1" onchange="getda(this.value,this)">
<option value="none">---------------</option>
<option value="2">John Doe</option>
<option value="1">Joe Bloggs</option>
</select>
PHP
<?php
$mysqli = new mysqli("localhost", "root", "", "gym");
/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
function hyphenate($str) {
return implode("-", str_split($str, 2));
}
function getmembers($time,$group,$iteration)
{
$date=$_GET["date"];
$date=hyphenate($date);
$date = explode('-', $date);
$new_date = $date[2].'-'.$date[1].'-'.$date[0];
$mysqli = new mysqli("localhost", "root", "", "gym");
if ($iteration == 0){
$result = $mysqli->query("select members.memberid, members.firstname, members.lastname from bookings inner join members on bookings.memberid = members.memberid where bookings.date = '$new_date' and time = '$time' and bookings.groupnumber = '$group' order by bookings.bookingid ASC limit 1");
}
else {$result = $mysqli->query("select members.memberid, members.firstname, members.lastname from bookings inner join members on bookings.memberid = members.memberid where bookings.date = '$new_date' and time = '$time' and bookings.groupnumber = '$group' order by bookings.bookingid ASC limit 1,$iteration");
}
$rowcount=mysqli_num_rows($result);
if ($rowcount==$iteration && $iteration == 0)
{
$result = $mysqli->query("select firstname, lastname,memberid from members order by firstname ASC");
echo '<select name="'.$time.'-'.$group.'-'.$iteration.'" onchange="getda(this.value,this)"><option value="---------------">---------------</option>';
while ($row = $result->fetch_assoc()) {
unset($firstname, $lastname);
$firstname = $row['firstname'];
$lastname = $row['lastname'];
$memberid = $row['memberid'];
echo '<option value="'.$memberid.'">'.$firstname . ' ' . $lastname .'</option>';
}
echo "</select>";
}
else if ($rowcount>=$iteration){
echo '<select name="'.$time.'-'.$group.'-'.$iteration.'" onchange="getda(this.value,this)">';
while ($row = $result->fetch_assoc()) {
unset($firstname, $lastname);
$firstname = $row['firstname'];
$lastname = $row['lastname'];
$memberid = $row['memberid'];
echo '<option value="'.$memberid.'">'.$firstname . ' ' . $lastname .'</option><option value="cancel">Cancel</option>';
}
echo "</select>";
}
else{
$result = $mysqli->query("select firstname, lastname, memberid from members order by firstname ASC");
echo '<select name="'.$time.'-'.$group.'-'.$iteration.'" onchange="getda(this.value,this)"><option value="---------------">---------------</option>';
while ($row = $result->fetch_assoc()) {
unset($firstname, $lastname);
$firstname = $row['firstname'];
$lastname = $row['lastname'];
$memberid = $row['memberid'];
echo '<option value="'.$memberid.'">'.$firstname . ' ' . $lastname .'</option>';
}
echo "</select>";
}
}
?>
JS
function getda(id,booking){
$.ajax({
type: 'post',
url: 'samefile.php',
data: {
get_option:id
},
success: function (response) {
document.getElementById("result").innerHTML=response;
}
});
}
samefile.php
<?php
if(isset($_POST['get_option']))
{
inlude 'config/config.php';
$name=$_POST["get_option"];
echo "<SCRIPT>
alert('$name');
</SCRIPT>";
$sql = "insert into bookings (memberid,date,time,groupnumber) values (1,'2016-04-14','09:00',3)";
$query = mysqli_query($sql);
$mysqli->close();
?>
The console in chrome looks fine (below) but no records are inserted and the php alert doesn't show. I havent passed any of the variable to the SQL as I was first testing that a query executed properly
jquery.min.js:4 XHR finished loading: POST "http://localhost/gym/samefile.php".send # jquery.min.js:4n.extend.ajax # jquery.min.js:4getda # cal.php?date=140416:42onchange # cal.php?date=140416:36ListPicker._handleMouseUp # about:blank:535
Might want to look into jQuery's .change(). I think that it would work with something like below for your code. You could also have it call your function that has ajax in it as well
$( ".class" ).change(function() { //can use #id here too
$.ajax({
type: 'post',
url: 'samefile.php',
data: {
get_option:this.value
},
success: function (response) {
document.getElementById("result").innerHTML=response;
}
});
});
I see three problems in samefile.php - include spelled incorrectly, an extra semicolon, and a missing closing bracket:
<?php
if(isset($_POST['get_option']))
{
include 'config/config.php';
$name = $_POST["get_option"];
//this should be converted to parameterized queries
$sql = "insert into bookings (memberid,date,time,groupnumber) values (1,'2016-04-14','09:00',3)";
$query = mysqli_query($sql);
if(is_object($query)){
echo 'successfully inserted';
} else {
echo 'insert failed';
}
$mysqli->close();
} else {
echo 'no data to process!';
}
?>
Pulling my hair out with this. Suddenly receiving the following error which wasn't there before:
>>PHP Notice: Undefined index: rmvFileList in C:\wamp\www\somesubdirectory\members\delete.php on line 7
This is coming from an Ajax submission to delete.php. Although the "notice" is appearing, the script is executing properly as it should (database deletion completed correctly, file deleted correctly, and the success call being logged correctly in the console.log). Probably just some sort of sick obsession, but I want to get rid of the warning popping up in my error log every time the delete script is called.
Here is the ajax:
var rmvFile = "Some file name";
$.ajax({
type: "POST",
url: "delete.php",
dataType:"text",
data: {'rmvFileList' : rmvFile },
success: function(returnData) {
console.log(returnData);
}
});
And here is delete.php:
<?php
session_start();
include('../../phpincl/db.php');
$table = 'phoeteo_img_' . $_SESSION['memberID'] . '_' . $_SESSION['showID'];
$name = $_POST['rmvFileList']; <<--This is line 7
$sql = "SELECT * FROM $table WHERE imgNameTime = '$name'";
$result = mysqli_query($conn, $sql) or die(mysqli_error($conn));
while($row = mysqli_fetch_assoc($result))
{
$toBeDeletedIndex = $row['imgIndex'];
$toBeDeletedFilename = $row['imgNameTime'];
$sql = "DELETE FROM $table WHERE imgNameTime = '$name'";
mysqli_query($conn, $sql) or die('Failed: ' . mysqli_error($conn));
$path = 'repository/' . $_SESSION['memberID'] . '_' . $_SESSION['showID'] . '/' . $toBeDeletedFilename;
unlink($path);
}
echo $name;
?>
Any and all help would be greatly appreciated. Thanks!
set isset in php:check code below :
if(isset($_POST['rmvFileList'])){
$name = $_POST['rmvFileList'];
$sql = "SELECT * FROM $table WHERE imgNameTime = '$name'";
$result = mysqli_query($conn, $sql) or die(mysqli_error($conn));
while($row = mysqli_fetch_assoc($result))
{
$toBeDeletedIndex = $row['imgIndex'];
$toBeDeletedFilename = $row['imgNameTime'];
$sql = "DELETE FROM $table WHERE imgNameTime = '$name'";
mysqli_query($conn, $sql) or die('Failed: ' . mysqli_error($conn));
$path = 'repository/' . $_SESSION['memberID'] . '_' . $_SESSION['showID'] . '/' . $toBeDeletedFilename;
unlink($path);
}
echo $name;
}