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.
Related
<?php
$sql = "SELECT MAX(REQUEST_ID) AS REQUEST_ID FROM TBL_REQUEST;";
$stmt = sqlsrv_query( $conn, $sql );
if( $stmt === false) {
echo "alert('DataBase Error');";
}
else{
$row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC);
$newReqId=$row['REQUEST_ID']+1;
}
$sql = "INSERT INTO TBL_REQUEST VALUES(".$newReqId.",\'ISSUE\',\'Test\',\'Test\',\'NSNS05\',1);";
$newsql = $sql;
$stmt = sqlsrv_query( $conn, $newsql );
if( $stmt === false) {
echo "alert('Not Inserted '+assoc_id+' ".$stmt." '+' ".$newsql." ');";
}
else{
echo "alert('Inserted '+assoc_id+' ".$stmt."');";
}
?>
in this above code i have used 2 SQL statements the first one is a select statement which works fine and fetches data from the table, but when i execute the Insert on the same table its not working...
INSERT INTO TBL_REQUEST VALUES(4016,'ISSUE','Test','Test','NSNS05',1);
thats the string which is
why are using "" between "" you should ' ' for $newReqId
$sql = "INSERT INTO TBL_REQUEST VALUES(".$newReqId.",\'ISSUE\',\'Test\',\'Test\',\'NSNS05\',1);";
I'm having trouble using an array to make an sql query delete multiple rows of data at once. Please ignore that I'm using sql injection for now.
EDIT: A somewhat better explanation - my php does not work at all. I have edited it somewhat, after checking the link Sebastian provided in the comments
NOTE: I'm using AngularJS to post
This is my $data structure, from my controller.js function. devicesToDelete is just a simple array, e.g. ["1", "2", "3"]:
$http.post('./js/removeMultiple.php', { 'devicesToDeleteArray': devicesToDelete })
.success(function(data) {
$scope.results = data;
devicesToDelete = [];
})
.error(function(err) {
$log.error(err);
})
This is the updated php code im having trouble with. On clicking my deleteMultiple button, only the confirm alert fires, the selected items aren't deleted and the console is clear of errors:
<?php
$data = json_decode(file_get_contents("php://input"));
include('config.php');
$sql = "DELETE FROM devices WHERE devID in ( implode(",", $data) )";
$qry = $conn->query($sql);
$sql = "SELECT * FROM devices";
$qry = $conn->query($sql);
$data = array();
if($qry->num_rows > 0){
while($row = $qry->fetch_object()){
$data[] = $row;
}
}else {
$data[] = null;
}
$conn->close();
echo json_encode($data);
EDIT 2: I managed to solve the issue on my own. Here is the solution:
I used .join() on my array on the javascript side to have all of the IDs for deletion be separated by commas (e.g. 1, 2, 3):
$http.post('./js/removeMultiple.php', { 'devicesToDeleteArray': devicesToDelete.join(", ") })
.success(function(data) {
$scope.results = data;
devicesToDelete = [];
})
.error(function(err) {
$log.error(err);
})
Then I just added what I completely glanced over in my php code which is the name of the array i was passing into it - devicesToDeleteArray
<?php
$data = json_decode(file_get_contents("php://input"));
include('config.php');
$sql = "DELETE FROM devices WHERE devID in ($data->devicesToDeleteArray)";
$qry = $conn->query($sql);
$sql = "SELECT * FROM devices";
$qry = $conn->query($sql);
$data = array();
if($qry->num_rows > 0){
while($row = $qry->fetch_object()){
$data[] = $row;
}
}else {
$data[] = null;
}
$conn->close();
echo json_encode($data);
here is php code:
<?php
$ids = $_POST['devicesToDeleteArray'];
if(!is_array($data)) {
$ids = json_decode($data, true);
}
if(!empty($ids)) {
include 'config.php';
$sql = "DELETE FROM devices WHERE devID in (implode(",", $ids))";
$qry = $conn->query($sql);
$sql = "SELECT * FROM devices";
$qry = $conn->query($sql);
$data = array();
if ($qry->num_rows > 0) {
while ($row = $qry->fetch_object()) {
$data[] = $row;
}
} else {
$data[] = null;
}
$conn->close();
echo json_encode($data);
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"
In php, i have used an sql query to fetch the data like :-
$sql="Select * from xyz";
$result = $conn->query($sql);
// output data of each row
while($row = $result->fetch_assoc()) {
error_log( "id" . $row["id"]);
}
Now i want to use all the values attained using $row["id"] in javascipt function and use it in a variable (var j , lets say). How to do this?
Try something like this:
<?php
$sql="Select * from xyz";
$errorsData = array();
$result = $conn->query($sql);
// output data of each row
while($row = $result->fetch_assoc()) {
error_log( "id" . $row["id"]);
$errorData[]=$row["id"]
}
$errorJson = json_encode($errorsData);
?>
<script>
var errorJson = <?= $errorJson ?> ;
console.log(errorJson);
<script>
Good luck!!
in jquery I would have done like this,
php
$sql="Select * from xyz";
$arr_json = array();
$result = $conn->query($sql);
// output data of each row
while($row = $result->fetch_assoc()) {
error_log( "id" . $row["id"]);
$arr_json[] = $row['id'];
}
echo json_encode($arr_json);
jquery
$.get(
<THAT CALLED URL>,
function(ret_data){
console.log(ret_data);
/* you can use the ret_data as ret_data.<INDEX> */
}
);
Can someone help me with this? My sql code only works if I match only integers like 2=2 but if I change it to like this orange=orange it wont work...can anyone help me figure whats wrong with my code.
index.php:
<script type="text/javascript" src="jquery/jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="jquery.jCombo.min.js"></script>
<form>
Caraga Region: <select name="region" id="region"></select>
Municipalities: <select name="town" id="town"></select>
Unique ID: <select name="uniq_id" id="uniq_id"></select> <br />
</form>
<script type="text/javascript">
$( document ).ready(function() {
$("#region").jCombo({ url: "getRegion.php" } );
$("#town").jCombo({ url: "getTown.php?townid=", parent: "#region", selected_value : '510' } );
$("#uniq_id").jCombo({ url: "getID.php?unqid=", parent: "#town", data: String, selected_value : '150' } );
});
</script>
getRegion.php:
<?php
// Connect Database
mysql_connect("localhost","root","");
mysql_select_db("klayton");
// Execute Query in the right order
//(value,text)
$query = "SELECT id, municipalities FROM regions";
$result = mysql_query($query);
$items = array();
if($result && mysql_num_rows($result)>0) {
while($row = mysql_fetch_array($result)) {
$option = array("id" => $row[0], "value" => htmlentities($row[1]));
$items[] = $option;
}
}
mysql_close();
$data = json_encode($items);
// convert into JSON format and print
$response = isset($_GET['callback'])?$_GET['callback']."(".$data.")":$data;
echo $data;
?>
getTown.php:
<?php
// Connect Database
mysql_connect("localhost","root","");
mysql_select_db("klayton");
// Get parameters from Array
$townid = !empty($_GET['townid'])
?intval($_GET['townid']):0;
// if there is no city selected by GET, fetch all rows
$query = "SELECT town FROM towns WHERE tcode = $townid";
// fetch the results
$result = mysql_query($query);
$items = array();
if($result && mysql_num_rows($result)>0) {
while($row = mysql_fetch_array($result)) {
$option = array("id" => $row['town'], "value" => htmlentities($row['town']));
$items[] = $option;
}
}
mysql_close();
$data = json_encode($items);
echo $data;
?>
getID.php: The problem is in this code. It wont work if I match character to character it only works if its integer=integer.
<?php
// Connect Database
mysql_connect("localhost","root","");
mysql_select_db("klayton");
// Get parameters from Array
$unqid = !empty($_GET['unqid'])
?intval($_GET['unqid']):0;
// if there is no city selected by GET, fetch all rows
$query = "SELECT uid, unq_pos_id FROM tb_uniqid WHERE tb_uniqid.uid = '$unqid'";
// fetch the results
$result = mysql_query($query);
$items = array();
if($result && mysql_num_rows($result)>0) {
while($row = mysql_fetch_array($result)) {
$option = array("id" => $row['uid'], "value" => htmlentities($row['unq_pos_id']));
$items[] = $option;
}
}
mysql_close();
$data = json_encode($items);
echo $data;
?>
(uid)field is stored with character values just like in the (town)field. I want to match it but it won't work.
Try to in getID.php replace:
$unqid = !empty($_GET['unqid'])
?intval($_GET['unqid']):0;
with:
$unqid = !empty($_GET['unqid'])
?$_GET['unqid']:0;
if you want to be able to match strings as well as integers. You see, intval() returns only the integer value of the variable, thus you strip of the other characters when you send a string to that page, and therefore you can't match anything with the code you had before.