Can't update DataBase with checkbox data - php

I have a list of 4 images of an item.
One of them should show up in another page as a link from that page to the item page.
I want to be able to check a box so that this one will be the main pic and will show up in the category page.
this is the code of the form:
$all_pics_of_item = fetch_all_pics_of_item($item_id);
//print_r($all_pics_of_item);
if(is_array($all_pics_of_item))
{
echo '<ul>';
foreach($all_pics_of_item as $key=>$val)
{
if ($val['pics_main']=='yes')
{
$set_checked = "checked";
$action = true;
}
else
{
$set_checked = "";
$action = false;
}
echo '<li style="float: left;margin:10px;border: 1px solid #000;padding:10px;">';
echo '<img style="width:120px;height:120px;" src="../../gallery_images/thumbs/'.$val['pics_source'].'">';
echo '<br>'.$val['pics_name'];
echo '<br><div class="delet"><b>x</b></div>';
echo '<br><form method="post" action="update_main_pic.php" enctype="text/plain" >
Show in cat. page<input type="checkbox" class="myCheckbox" name="main" value="no"'.$set_checked.'&action='.$action.' data-picid="'.$val['pics_id'].'" data-itemid="'.$item_id.'" />
</form>';
echo '</li>';
}
echo '<ul>';
}
Here is the AJAX and script:
$(document).ready(function(){
$(':checkbox').click(function() {
$(':checkbox').not(this).removeAttr('checked');
var picid = $(this).attr('data-picid');
var itemid = $(this).attr('data-itemid');
var action = $(this).is(':checked');
//if((this).attr('checked',true))
//{
// var action = true;
//}
//else
// {
// var action = false;
// }
$.ajax({
url: "ajax_update_main_pic.php",
type: "POST",
data: "itemid=" + itemid + "&picid=" + picid + "&action=" + action,
timeout:5000,
dataType: "html",
beforeSend:function(){
},
error: function(){
alert('Problem !');
},
success: function(msg){
if(msg == 'no')
{
}
else
{
}
},
complete: function(){
}
})
});
}); //END READY
Here is the update function:
<?php
require_once "../../db.php";
require_once "../../functions.php";
if(isset($_POST['itemid']) && isset($_POST['picid']) && isset($_POST['action']))
{
$item_id = $_POST['itemid'];
$pic_id = $_POST['picid'];
$action = $_POST['action'];
}
else
{
header('location: upload_image.php');
die();
}
if($action == 'true')
{
$pic_show = 'yes';
}
else
{
$pic_show = 'no';
}
//print_r($pic_show);
function update_main_pic($item_id, $pic_id, $pic_show )
{
global $db;
try
{
$sql = "
UPDATE pics SET
pics_main = :pic_show
WHERE pics_id = :pic_id AND pics_items_id = :item_id
";
$stmt = $db->prepare($sql);
$stmt->bindParam(':pics_id', $pic_id, PDO::PARAM_INT);
$stmt->bindParam(':pics_items_id', $item_id, PDO::PARAM_INT);
$stmt->bindParam(':pics_main', $pic_show, PDO::PARAM_STR);
$stmt->execute();
return true;
}
catch(Exception $e)
{
return false;
}
}
$result = update_main_pic($item_id, $pic_id, $pic_show );
if($result == false)
{
die('Problem updating pics');
}
else
{
header('location: upload_image.php?iid='.$item_id);
die();
}
?>
I always get 'Problem updating pics'
It looks like only the checked checkbox is transmitted, while I want that the column PIC_MAIN will show "yes" if this is the one chosen and "no" foe all other pics

The issue lies with your binding.
You sql has the following name variables :pic_show , :pic_id and :item_id but you are binding :pics_main', :pics_items_id and :pics_id.
Change your binding to:
$sql = "
UPDATE pics SET
pics_main = :pic_show
WHERE pics_id = :pic_id AND pics_items_id = :item_id
";
$stmt = $db->prepare($sql);
$stmt->bindParam(':pic_id', $pic_id, PDO::PARAM_INT);
$stmt->bindParam(':item_id', $item_id, PDO::PARAM_INT);
$stmt->bindParam(':pic_show', $pic_show, PDO::PARAM_STR);

Related

error in updating mysql with $.post using jquery

i wanna have like for my blog posts, it should work like this: user will click on something and it increase that number by +1 and store it in data base, i have a column named post_like in my db. but after increase 0 to 1 (when i try to increase from 1 to 2 or more) i get error.
jquery:
$("#insert_like").click(function(e){
alert('s')
var like = $("#insert_like").val();
like += 1;
var post_id = $("#post_id").val();
$.post("./inc/like.php", {
like: like,
post_id: post_id
}, function(data, status){
$("#insert_like").text(data);
like = 0;
});
});
php:
<?php
if (isset($_POST['like'])) {
require_once 'db.inc.php';
$like = $_POST['like'];
$post_id = $_POST['post_id'];
$q = "UPDATE posts set post_like = ? WHERE post_id=? LIMIT 1";
$stmt = $conn->prepare($q);
$stmt->bind_param('ii', $like, $post_id);
$stmt->execute();
if ($stmt->affected_rows == 1) {
echo "$like";
} else {
echo "error: $stmt->error";
}
$stmt->close();
$conn->close();
} else {
header('Location: ../home.php');
}
html:
<p>Post like: <span id="insert_like" style="cursor: pointer"><?php echo $post_like ?></span> </p>
You can pass the Post Id from javascript and update the likes in the backend. Consider below example:
$("#insert_like").click(function(e){
$.post("./inc/like.php", {
post_id: $("#post_id").val()
}, function(data, status){
$("#insert_like").text(data);
like = 0;
});
});
and in the backend
<?php
if (isset($_POST['like'])) {
require_once 'db.inc.php';
$post_id = $_POST['post_id'];
$q = "UPDATE posts SET post_like = (post_like + 1) WHERE post_id = ?";
$stmt = $conn->prepare($q);
$stmt->bind_param('i', $post_id);
$stmt->execute();
if ($stmt->affected_rows == 1) {
// get the updated likes and return as response.
} else {
echo "error: $stmt->error";
}
$stmt->close();
$conn->close();
} else {
header('Location: ../home.php');
}
Hope this helps.

Unexpected < token in JSON at position 0

I keep receiving this JSON error,i think it has something to do with html tags or any other tags that conflicts with it.
Here is my PHP Code:
<?php
require_once("connection.php");
class AddAdminUPController extends Connection{
public function addAdminUP(){
include "function.php";
$username = cleanData($_POST['username']);
$password = cleanData($_POST['password']);
if (!empty($username)){
if(!empty($password)){
if(strlen($password) > 8){
$select_query = "select * from sample_user where user_name = ?";
$stmt = $this->db->prepare($select_query);
$stmt->bindParam(1,$username);
if($stmt->execute()){
if($stmt->rowCount() <= 0){
$password = password_hash($password,PASSWORD_BCRYPT,array('cost' => 12));
$create_query = "insert into sample_user(user_name,password)values(?,?)";
$stmt = $this->db->prepare($create_query);
$stmt->bindParam(1,$username);
$stmt->bindParam(2,$password);
if($stmt->execute()){
echo "<script>".
"Materialize.toast('Created SuccessFully!', 5000, 'green')"
."</script>";
echo "<script>".
"$('#add_admin_up_form').hide();".
"$('#add_admin_up').hide();";
?>
$(".enrollment_title").html("<i class='material-icons'>fingerprint</i> Enroll Fingerprint");
<?php
echo "</script>";
include 'flexcode_sdk/include/global.php';
include 'flexcode_sdk/include/function.php';
if(isset($_GET['action']) && $_GET['action'] == 'add'){
$lastID = $this->db->lastInsertId();
?>
<script type="text/javascript">
$('title').html('User');
function user_register(user_id, user_name) {
$('body').ajaxMask();
regStats = 0;
regCt = -1;
try
{
timer_register.stop();
}
catch(err)
{
console.log('Registration timer has been init');
}
var limit = 4;
var ct = 1;
var timeout = 5000;
timer_register = $.timer(timeout, function() {
console.log("'"+user_name+"' registration checking...");
user_checkregister(user_id,$("#user_finger_"+user_id).html());
if (ct>=limit || regStats==1)
{
timer_register.stop();
console.log("'"+user_name+"' registration checking end");
if (ct>=limit && regStats==0)
{
alert("'"+user_name+"' registration fail!");
$('body').ajaxMask({ stop: true });
}
if (regStats==1)
{
$("#user_finger_"+user_id).html(regCt);
alert("'"+user_name+"' registration success!");
$('body').ajaxMask({ stop: true });
load('view_admin.php?action=add');
}
}
ct++;
});
}
function user_checkregister(user_id, current) {
$.ajax({
url : "view_admin.php?action=checkreg&user_id="+user_id+"&current="+current,
type : "GET",
success : function(data)
{
try
{
var res = jQuery.parseJSON(data);
if (res.result)
{
regStats = 1;
$.each(res, function(key, value){
if (key=='current')
{
regCt = value;
}
});
}
}
catch(err)
{
alert(err.message);
}
}
});
}
</script>
<?php
$last_id_query = "select * from sample_user where user_id = ?";
$stmt = $this->db->prepare($last_id_query);
$stmt->bindParam(1,$lastID);
if ($stmt->execute()){
while($row = $stmt->fetch(PDO::FETCH_OBJ)){
$url_register =
base64_encode($base_path."register.php?user_id=".$row->user_id);
echo "<br><a href='finspot:FingerspotReg;$url_register' onclick=\"user_register('".$row->user_id."','".$row->user_name."')\" class='fw_button general_button btn waves-effect waves-light'>Register Fingerprint</a>";
}
}
}
elseif (isset ($_GET['action']) && $_GET['action'] == 'checkreg') {
$sql1 = "SELECT count(finger_id) as ct FROM sample_finger WHERE user_id=".$_GET['user_id'];
$result1 = mysql_query($sql1);
$data1 = mysql_fetch_array($result1);
if (intval($data1['ct']) > intval($_GET['current'])) {
$res['result'] = true;
$res['current'] = intval($data1['ct']);
}
else
{
$res['result'] = false;
}
echo json_encode($res);
}
else { echo "Parameter invalid..";}
}
else{
echo "<script>".
"Materialize.toast('Query Failed!', 5000, 'red')"
."</script>";
}
}
else{
echo "<script>".
"Materialize.toast('Username already exists!', 5000, 'red')"
."</script>";
}
}
else{
echo "<script>".
"Materialize.toast('Query Failed!', 5000, 'red')"
."</script>";
}
}
else{
echo "<script>".
"Materialize.toast('Password is too short!', 5000, 'red')"
."</script>";
}
}
else{
echo "<script>".
"Materialize.toast('Password is empty!', 5000, 'red')"
."</script>";
}
}
else{
echo "<script>".
"Materialize.toast('Username is empty!', 5000, 'red')"
."</script>";
}
}
}
$add_admin_up_controller = new AddAdminUPController;
echo $add_admin_up_controller->addAdminUP();
?>
I need help in fixing this kind of error. It keeps displaying:
SyntaxError: Unexpected token < in JSON at position 0 at JSON.parse () at Function.jQuery.parseJSON (jquery.js:8520) at Object.success (eval at (jquery.js:339), :55:90) at fire (jquery.js:3148) at Object.fireWith [as resolveWith] (jquery.js:3260) at done (jquery.js:9314) at XMLHttpRequest.callback (jquery.js:9718)
You are returning plain text instead of JSON. In your ajax call put the response dataType: 'json' and the part of PHP:
header("Content-Type: application/json");
echo json_encode($res);
exit;
This error due to your responce is not in json format and your ajax request is expecting json responce .
You can change responce header by use dataType : 'text/html' in your ajax request.
Here in action .
function user_checkregister(user_id, current) {
$.ajax({
url : "view_admin.php?action=checkreg&user_id="+user_id+"&current="+current,
type : "GET",
dataType: 'text/html',
success : function(data)
{
try
{
var res = jQuery.parseJSON(data);
if (res.result)
{
regStats = 1;
$.each(res, function(key, value){
if (key=='current')
{
regCt = value;
}
});
}
}
catch(err)
{
alert(err.message);
}
}
});
}

Notification appears to be successful even if no data has been added to database

So I have these codes wherein I want a notification to appear in every event. I want to check if the record exists, then a notification will appear, saying the college already exists. But that doesn't happen tho. I keep on inputting duplicate input, but the notification still says it's successful. Is there a mistake in my code?
add-college.php
<?php
function findDuplicate($code) {
try {
include($_SERVER['DOCUMENT_ROOT']."/config/db-config.php");
$sql = "SELECT * FROM colleges WHERE collegecode = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $code);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows > 0) {
return true;
}
else {
return false;
}
}
catch (Exception $e) {
return false;
}
}
try {
include($_SERVER['DOCUMENT_ROOT']."/config/db-config.php");
$code = $_POST['code'];
$name = $_POST['name'];
$result = array();
if (findDuplicate($code)) {
$result['message'] = 'duplicate';
}
else {
$sql = "INSERT INTO colleges(collegecode, collegename) VALUES(?, ?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ss", $code, $name);
if ($stmt->execute()) {
$result['message'] = 'success';
}
else {
$result['message'] = 'error';
}
}
echo json_encode($result);
}
catch (Exception $e) {
echo json_encode($result);
}
?>
script.js
$("#save-new").click(function() {
var form = $("#add-college");
var code = $("#code").val();
var name = $("#name").val();
$.ajax({
type: "POST",
data: {
code: code,
name: name
},
url: "../ajax/add-college.php",
dataType: "html",
success: function(data) {
if (data.message = "success") {
$.notify({
// options
message: 'College has been added.'
},{
// settings
type: 'success'
});
}
else if (data.message = "duplicate") {
$.notify({
// options
message: 'College already exists.'
},{
// settings
type: 'warning'
});
}
else {
$.notify({
// options
message: 'College cannot be added.'
},{
// settings
type: 'error'
});
}
$("#code").val("");
$("#name").val("");
$("#add-new").modal('hide');
showColleges();
}
});
});
data.message = "success" this is assignment operation, if you want to compare two string use == operator.
So, the correct statement would be for the if condition would be if(data.message == "success")
Similarly, if(data.message == "duplicate"). I am sure you are aware of all this!

How to get a single mysql value and output it to an ajax call?

I'm trying to get a number from a mysql line then outputting it to ajax. the number can't be a string because I will multiply it in ajax. This is what i have so far. I'm not sure what to do from here.
ajax:
$(document).ready(function()
{
$("#btnCalc").click(function()
{
var user = $("#txtUser").val();
var amount = $("#txtAmount").val();
var category = $("txtCat").val();
var number = $("txtNum").val();
var result = '';
$.get("code/value.php",
{
ID:user,
amount:amount,
result:result
},function(query)
{
if ( user > 0 and user < 30 ){
alert(result);
}
else{
alert( 'invalid user ID');
}
});
});
});
php:
<?php
$userID = $_GET["ID"];
$amount = $_GET["amount"];
$category = $_GET["category"];
$num = $_GET["number"];
require "../code/connection.php";
$SQL = "select userAmount from user where userID= '$userID'";
$reply = $mysqli->query($SQL);
while($row = $reply->fetch_array() )
{
}
if($mysqli->affected_rows > 0){
$msg= "query successful";
}
else{
$msg= "error " . $mysqli->error;
}
$mysqli->close();
echo $msg;
?>
Pretty straightforward - you just grab the value from the row and cast it as a float.
while($row = $result->fetch_array() )
{
$msg = floatval($row['userAmount']);
}
if($msg > 0) {
echo $msg;
} else {
echo "error" . $mysqli->error;
}
$mysqli->close();
And one small change in your ajax call:
$.get("code/value.php",
{
ID:user,
amount:amount,
result:result
},function(query)
{
alert(query);
});
});
You need to add echo $row['userAmount']; inside or after your while loop, and drop the second echo. You should be able to take result within your AJAX code and use it as a number directly.
Here function(query), query is the response from the AJAX call. So your alert should be:
alert(query);
result is empty.
You also should be using prepared statements and outputting the value you want.
Something like:
<?php
$userID = $_GET["ID"];
$amount= $_GET["amount"];
require "../code/connect.php";
$SQL = "SELECT userAmount FROM user WHERE userID= ?";
$reply = $mysqli->prepare($SQL);
if($mysqli->execute(array($userID))) {
$row = $reply->fetch_array();
echo $row['amount'];
}
else
{
$msg = "error" . $mysqli->error;
}
$mysqli->close();
?>
Then JS:
$(document).ready(function()
{
$("#btnCalc").click(function()
{
var user = $("#txtUser").val();
var amount = $("#txtAmount").val();
var result = '';
$.get("code/value.php",
{
ID:user,
amount:amount,
result:result
},function(query)
{
alert(query);
});
});
});
You can use https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/parseFloat or https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt to convert the value to an integer/float in JS.

Error trying to search a video AJAX

I have created a code that allows you to search videos from the database. But everytime I write the video I want to search, in console, error appears... I really dont know why it doesnt print the result...
Could you help me?
I need help real fast
AJAX
$(document).ready(function($) {
var Search = function(title){ return $.post( "./include/php/busqueda_videos.php", { "title" : title }); }
$("#input_search").on('keyup', function(event) {
var output = "";
$(".videos_container").html("");
event.preventDefault();
var input = $("#input_search").val();
Search(input).done(function(response) {
if(response.success) {
$.each(response.videos, function(key, value) { var output = "<div class='video_main_container'><div class='video_container'><div class='video_thumb'><a data-id='"+value['id']+"'><img src='"+value['image']+"' alt='' /></a></div><div class='video_info'><p class='title'>"+value['title']+"</p><p class='usuario'>"+value['user']+"</p></div></div></div>"; });
$(".videos_container").html(output);
} else {
console.log("Error");
}
}).fail(function(jqXHR, textStatus, errorThrown) { console.log("Hubo un error"); });
});
});
PHP
<?php
if(isset($_POST['title'])) {
get_infvideo($_POST['title']);
} else {
$message = sprintf("No valid");
header($_SERVER['SERVER_PROTOCOL'] . ' ' . $message, true, 403);
}
function get_infvideo($title) {
$dsn = "mysql:host=localhost;dbname=tapehd;charset=utf8";
$usuario = "root";
$contraseƱa = "";
$conexion = new PDO($dsn, $usuario, $contraseƱa);
$resultado = null;
$jsondata = array();
$videos = array();
$text ="";
if($title!="") {
$title= explode(" ", $title);
for($i=0; $i<count($title);$i++) {
if($text!="") {
$text .= " AND (title LIKE '%".$title[$i]."%' or user LIKE '%".$title[$i]."%')";
} else {
$text .= " (titulo LIKE '%".$titulo[$i]."%' or user LIKE '%".$title[$i]."%')";
}
}
}
if($conexion){
$sql = "SELECT * FROM video WHERE ".$text;
if($resultado = $conexion->query($sql)) {
while($fila = $resultado->fetch()) {
$fila['id'] = $fila['id'];
$fila['user'] = $fila['user'];
$fila['image'] = $fila['image'];
$jsondata['success'] = true;
array_push($videos, $fila);
$jsondata['videos'] = $videos;
}
} else {
$jsondata['success'] = false;
$jsondata['message'] = $sql;
}
}
header('Content-type: application/json; charset=utf-8');
echo json_encode($jsondata, JSON_FORCE_OBJECT);
}
exit();
?>
The idea is to print the video (with his id, image, user, title) that you have searched...

Categories