Updating a database using post() - php

I am working on a calendar where the background color of the day cells can be changed by the administrator. The change gets saved to the server. Right now, it's not working. Here's a portion of the JavaScript:
for(i=0; i<myDays.length; i++) { // Goes through each TD and creates a click event
myDays[i].addEventListener("click", function(){
if(this.classList.contains("avail")) {
this.classList.toggle("avail");
this.classList.toggle("halfy");
$.post("classChange.php", { dID: this.id, dClass: "halfy" } );
}
This is the PHP code in classChange.php:
if(isset($_POST["dID"]) ){
$stmt = $db->prepare("UPDATE original SET class=? WHERE id=?");
$stmt->bind_param("ss", $dClass, $dID);
$dID = $_POST["dID"];
$dClass = $_POST["dClass"];
$stmt->execute();
$stmt->close();
} else {
echo "Code error, dummy!";
}
Clicking on a cell correctly changes the class (and color) of the cell, but does not update the database. I'm not getting any errors. I think it must be a problem with the post() code, or the PHP code. Any advice?

You need to define the variables first before using them.
$dID = $_POST["dID"];
$dClass = $_POST["dClass"];
$stmt = $db->prepare("UPDATE original SET class=? WHERE id=?");
$stmt->bind_param("ss", $dClass, $dID);

Related

PHP PDO - Update in mysql only posted value (html form)

I have an html form that has some disabled field depending of what kind of authorization the user have. When I press submit, the script should understand which form field are posted and which not, and then update only the related field in the database.
For example:
I can modify Birthday, Birth place and sex, but Name and Surname are disabled and so are not posted by the html form. Therefore have to be updated only Birthday, BirthPlace, Sex where id = $idperson. But if I have permission, I post Name and Surname too. And therefore I should update also these value.
Is there a fast way to do it with PDO? Or I have to create a long sequence of if/else?
Sorry for my bad english
The Best and easy way to do this,
First collect post data and check id is set
fetch all data from your table using id
loop your post data and check with collected details
if collected details value and post value changed update in collected details variable
update all your fields with new collected array
Check the below code for more understanding
function collect() {
if(isset($_POST['id'])) {
// validate id and get all details from table
$details = getDetails($_POST['id']);
foreach($_POST as $key=>$value) {
// loop your post data and check with collected details if value changed update in collected details
if(array_key_exists($key, $details)) {
$details[$key] = ($details[$key] != $_POST[$key]) ? $_POST[$Key] : $details[$key];
}
}
} else {
echo "id not found to update";
}
}
function getDetails($id) {
$query = "SELECT * FROM table_name WHERE id=:id";
$stmt = $conn->prepare($query);
$stmt->bindParam(':id', $id);
$stmt->execute();
return $stmt->fetch(PDO::FETCH_ASSOC);
}
function update($details) {
$query = "UPDATE table_name SET field_1=:field_1, field_2=:field_2, all_field=:all_field WHERE id=:id";
$stmt = $conn->prepare();
$stmt->bindParam(':field_1', $details['field_1']);
...
$stmt->bindParam(':id', $details[$id]);
return $stmt->execute();
}
Hope this code helps you, Happy coding.

set int from sql query

I am trying to set an int value from an sql query. In my ios app I can assign an int value to a photo ID, store it and retrieve it fine. The problem comes if I want to overwrite the photo with a new jpg but still using the existing IdPhoto and therefore the same filename, e.g. 1.jpg. I first check whether the user exists. If so I update the photo (this is where I need to set the IdPhoto) otherwise I create a photo with a new ID (works fine).
function uploadDetails($Name, $Location, $photoData, $IdPhoto) {
$uploads = query("SELECT Name, IdPhoto FROM users WHERE Name = '%s' limit 1",$Name);
if (count($uploads['result'])>0) {
$result = query("UPDATE users SET Name='$Name', Location='$Location', IdPhoto='$IdPhoto' WHERE Name = '%s'", $Name);
//Need to define IdPhoto from users table
if (move_uploaded_file($photoData['tmp_name'], "icons/".$IdPhoto.".jpg")) {
thumb("icons/".$IdPhoto.".jpg", 180);
//I can print out confirmation to the iPhone app
print json_encode(array('$IdPhoto'=>$IdPhoto));
} else {
//print out an error message to the iPhone app
errorJson('Upload on server problem');
};
}
else {
if ($photoData['error']==0) {
$result = query("INSERT INTO users(Name, Location) VALUES('%s','%s')", $Name, $Location);
if (!$result['error']) {
// fetch the active connection to the database (it's initialized automatically in lib.php)
global $link;
// get the last automatically generated ID in the table
$IdPhoto = mysqli_insert_id($link);
if (move_uploaded_file($photoData['tmp_name'], "icons/".$IdPhoto.".jpg")) {
thumb("icons/".$IdPhoto.".jpg", 180);
print json_encode(array('successful'=>1));
} else {
errorJson('Upload on server problem');
};
} else {
errorJson('Upload database problem.'.$result['error']);
}
}
}
}
So the problem lies in the first part of the code where I need to update the photo but still use the same IdPhoto
EDIT
The piece of code I needed was as follows:
$getID = mysqli_fetch_assoc(mysqli_query($link, "SELECT IdPhoto FROM users WHERE Name = '$Name'"));
$IdPhoto = $getID['IdPhoto'];
Although I got to the answer eventually myself, I appreciate feedback of how to phrase questions better in future. And writing out the full code probably helped me look at the bigger picture and see where I was going wrong.
Your question is extremely vague but I'm going to take the following assumptions:
Your query will only ever return a single record
You are using MySQLi
Once you have run the query and stored the results into $result you can use the following code to get the IdPhoto:
//Store a row from results into variable
$row = $result->fetch_assoc();
//Store IdPhoto into variable
$IdPhoto = $row['IdPhoto'];
Note: Also you are selecting Name from the database when you already have the Name since you're using it to fetch the record

Updating table via PDO prepare query

I've been having problems trying to update a value based off a code that is received on the page.
For example:
http://example.com/register.php?code=fa82f82712d1 (not the actual code, it's always a 32-char code actually).
I start a transaction, and do an update in the following way:
$stmt = $stmt->prepare("UPDATE USER SET GOT_CODE = 1 WHERE CODE = :code");
Then do a $stmt->execute(array(':code' => $code)); from the code gotten before.
But it never updates anything, I'm running a rowCount() (gives me '0') and closing the transaction but can't seem to get it updated.
The column type is CHAR(32) which should match with the length of the code received.
Is it possible that it's causing confusions because of the data type?
Maybe bind the parameter before like:
$stmt2 = $stmt->prepare("UPDATE USER SET GOT_CODE = 1 WHERE CODE = :code");
$stmt2->bindParam(":code", $code, PDO::PARAM_STR);
if ($stmt2->execute()){
$stmt->commit();
} else {
$stmt->rollBack();
}
EDIT: after comment of other people. The basic is to not use
$stmt = $stmt->prepare("UPDATE USER SET GOT_CODE = 1 WHERE CODE = :code");
but to give different var name like
$stmt2 = $stmt->prepare("UPDATE USER SET GOT_CODE = 1 WHERE CODE = :code");
because otherwise the system will overwrite $stmt and not work anymore

PHP jQuery: Passing a PHP variable FROM (not to) $.load()

I've seen questions asking about sending variables TO a document being loaded in $.load, but not retrieving variables from a $.load.
I've pasted the pertinent pieces of code below; essentially what I'm trying to do is run a PHP function every so often, and initially when the page first loads.
When the page first loads, it runs the getData function - and everything works as intended. But later down the page, when I try to load pullData.php, srcAverage doesn't update with the new value. The JS alert shows the srcAverage value.
Example: The first time the page is run, srcAverage is X. Every 5 seconds, we want to load pullData.php and update srcAverage on index.php with the new value (change X).
I feel like it's something really small I'm doing incorrectly - ideas?
conn.php
<?php
define("HOST", "stuff");
define("USER", "stuff");
define("PASSWORD", "stuff");
define("DATABASE", "stuff");
$mysqli = new mysqli(HOST, USER, PASSWORD, DATABASE);
// Connection info above all works as intended
?>
index.php
<?php
include 'inc/conn.php';
include 'inc/function.php';
$src = "none";
getData($src, $mysqli);
// This initial run of getData works as intended
// Skip to further down
// The JS alert below does NOT reflect the new srcAverage
?>
<script type="text/javascript">
$(document).ready(function() {
setInterval(function() {
// each interval, get first and second values
$("#targetDiv").load("pullData.php");
alert('New value is <?php echo $srcAverage; ?>');
}, 5000); // end setInterval
});
</script>
pullData.php
<?php
include 'incl/conn.php';
include 'incl/function.php';
$src = "none";
getData($src, $mysqli);
?>
The getData function (see code below) grabs 4 values from separate tables, averages them together (I have them all separated in different statements and variables for troubleshooting purposes), then sets the variable srcAverage to the average value. I've tested that the MySQLi statements are working fine, and srcAverage is assigned the correct value by the function. Echoing or JS alerting show the value as intended (on this page). But the variable does NOT get passed to index.php when loaded via load().
function.php
<?php
function getData($src, $mysqli) {
// Check SRC for specific source
// If no specific source, get average of all sources
// If YES specific source, get that value
global $srcAverage;
if ($src == 'alt') {
if ($stmt = $mysqli->prepare("SELECT value FROM table ORDER BY id DESC LIMIT 1;")) {
$stmt->execute(); // Execute the prepared query.
$stmt->store_result();
$stmt->bind_result($altVal); // get variables from result.
$stmt->fetch();
if($stmt->num_rows == 1) { // The entry exists, good to go
// echo $altVal;
}
} else {
// Either no results pulled or more than one.
echo "Error pulling alternate data!";
return false;
}
}
else {
// Value 1
if ($stmt = $mysqli->prepare("SELECT value FROM table ORDER BY id DESC LIMIT 1;")) {
$stmt->execute(); // Execute the prepared query.
$stmt->store_result();
$stmt->bind_result($firstVal); // get variables from result.
$stmt->fetch();
if($stmt->num_rows == 1) {
// echo $firstVal; // This works as intended
}
} else {
// Either no results pulled or more than one.
echo "Error pulling first value data!";
return false;
}
// Value 2
if ($stmt = $mysqli->prepare("SELECT value FROM table ORDER BY id DESC LIMIT 1;")) {
$stmt->execute(); // Execute the prepared query.
$stmt->store_result();
$stmt->bind_result($secondVal); // get variables from result.
$stmt->fetch();
if($stmt->num_rows == 1) { // The entry exists, good to go
// echo $secondVal;
}
} else {
// Either no results pulled or more than one.
echo "Error pulling second value data!";
return false;
}
// Value 3
if ($stmt = $mysqli->prepare("SELECT value FROM table ORDER BY id DESC LIMIT 1;")) {
$stmt->execute(); // Execute the prepared query.
$stmt->store_result();
$stmt->bind_result($thirdVal); // get variables from result.
$stmt->fetch();
if($stmt->num_rows == 1) { // The entry exists, good to go
// echo $thirdVal;
}
} else {
// Either no results pulled or more than one.
echo "Error pulling third value data!";
return false;
}
// Value 4
if ($stmt = $mysqli->prepare("SELECT value FROM table ORDER BY id DESC LIMIT 1;")) {
$stmt->execute(); // Execute the prepared query.
$stmt->store_result();
$stmt->bind_result($fourthVal); // get variables from result.
$stmt->fetch();
if($stmt->num_rows == 1) { // The entry exists, good to go
// echo $fourthVal;
}
} else {
// Either no results pulled or more than one.
echo "Error pulling fourth value data!";
return false;
}
// So everything up to this point is working fine. Statements grab data as intended, and assign variables.
// We have data - move forward
$srcCount = 4;
$srcTotal = $firstVal + $secondVal + $thirdVal + $fourthVal;
$srcAverage = $srcTotal / $srcCount;
$srcAverage = number_format((float)$srcAverage, 2, '.', '');
// echo "Total: $srcTotal .... Average: $srcAverage";
// If we were to echo above, it would display correctly. Problem is passing the variable to index
return $srcAverage;
}
}
?>
You're misunderstanding the php page lifecycle. <?php echo $srcAverage; ?> is evaluated only once when the page is initially loaded/rendered.
If you want to get the new value, you should probably switch over to using $.ajax() instead of .load(), and have pullData.php echo the result as json so you can work with the response in javascript.
Your problem is you are echoing out $srcAverage through php. The browser doesn't get php from the server or know how to execute it, it only sees the result of the php script. So, if you view source you will see that all your alert is is:
alert('New value is ');
The php already ran, $srcAverage when it was echoed was undefined due to scope so it put a null which converts to an empty string.
What gets loaded by $.load is the result of pullData.php, already parsed by php and returned through the server. pullData.php has no output. You need to echo the result of getData so that the javascript can see it.
What you need to be doing in javascript is:
alert('New value is ' + $('#targetDiv').html());
Based on your example markup you also seem to be missing #targetDiv. You probably want to wrap your original getData in #targetDiv.
So, your fixed version looks like this:
index.php
<div id='targetDiv'>
<?php
include 'inc/conn.php';
include 'inc/function.php';
$src = "none";
echo getData($src, $mysqli);
// This initial run of getData works as intended
// Skip to further down
// The JS alert below does NOT reflect the new srcAverage
?>
</div>
<script type="text/javascript">
$(document).ready(function() {
setInterval(function() {
// each interval, get first and second values
$("#targetDiv").load("pullData.php");
alert('New value is ' + $('#targetDiv').html();
}, 5000); // end setInterval
});
</script>
pullData.php
<?php
include 'incl/conn.php';
include 'incl/function.php';
$src = "none";
echo getData($src, $mysqli);
?>
Pass it as a new argument
$("#element").load("file.php", { 'myVar' : 'someValue'} );
Then on the server:
$_POST['myVar'];
will contain the value.
Edit
Maybe I mis understood, if you want to access data from the load function, you need to use the callback.
$('#element').load('file.php', function(data){
//response from the server
});

Saving to database via AJAX/jQuery, sending two variables

I have this problem that I have multiple fields that updates a database via an AJAX-call. The AJAX call looks like this:
$(".fresheditable").fresheditor("save", function (id, parsedHtml) {
$.ajax({
url: 'save.php',
type: 'POST',
data: {
id: id,
parsedHtml: parsedHtml
}
});
});
The ID value changes depending on what element is being edited. The problem is when the update gets sent to the save.php document. How do I only run the update with the specific ID?
See my save.php:
if($_POST['id']='link')
{
$link = $_POST['parsedHtml']; //get posted data
// query
$sql = "UPDATE buttons SET linkname=? WHERE id=?";
$q = $conn->prepare($sql);
if ($q->execute(array($link,$_SESSION['button'])))
{
echo 1;
}
}
//The next if-statement could look like this:
if($_POST['id']='contactperson')
{
$contactperson = $_POST['parsedHtml']; //get posted data
// query
$sql = "UPDATE buttons SET contactperson=? WHERE id=?";
$q = $conn->prepare($sql);
if ($q->execute(array($contactperson,$_SESSION['button'])))
{
echo 1;
}
}
If more than one ID is sent to the save.php say link and contactperson both if-statements are true and the update sets the same values because the parsedHtml variable.
Is there anything I can do in save.php that can prevent this? Somehow I need to associate the correct parsedHtml with the corresponding id.
The comparison operator in PHP (as well as in Javascript) is == and not =
if($_POST["id"]=="link")
Is it because you're using single equals in your IF tests, which assigns and returns true as a value exists? Not double-equals for comparison?
E.g.
if($_POST['id']=='link')
not
if($_POST['id']='link')
One thing you can use is data attribute i mean
<span item-data="some_id">data</span> now you can select in jquery, the specific item-data from your html to update.
Use else-if structure.
if($_POST['id']='link') {
}
else if($_POST['id']='contactperson') {
}

Categories