Problems with certain characters in jQuery/PHP - php

I am having problems with some characters after I added some jQuery to my code.
http://www.blueskycouncil.com/login-form.php (login: stack/this)
It worked fine when I was just doing it all in php but now it converts some of the characters weirdly.
This is the jQuery code I am using:
<script type="text/javascript">
// Check to see if document is ready
$(document).ready(function () {
// Set sort mode to Best
$.post("_db_index.php",
{sort_id: "best"},
// Take data from _db_index.php and put it into the HTML
function(output){
$('#left').html(output).show();
});
});
// Check to see whether user have voted on item before
function updateKarma(element, id, sortId){
$.post("idea_karma.php",
{pagetype: "index", karmatype: "ideaspace", id: id, sort_id: sortId},
function(output){
element.parentNode.className="karma-btn_voted";
element.parentNode.innerHTML="<span class=\"voted\">"+output+"</span>";
});
return false;
}
function viewMode(sortId){
$.post("_db_index.php",
{sort_id: sortId},
function(output){
$('#left').html(output).show();
$.post("subnavigation.php",
{sort_id: sortId},
function(output){
$('#base').html(output).show();
});
});
};
$(function(){
$(".base a").hover(function(){
$(this).children("span").fadeOut();
}, function(){
$(this).children("span").fadeIn();
})
});
and in the _db_index.php file it fetch it like this
<?php
// Start session
require_once('auth.php');
require_once('config.php');
require_once('db_open_select.php');
// Functions
include('trunctate_text.php');
$sort_id = $_POST['sort_id'];
$member_id = $_SESSION['SESS_MEMBER_ID'];
// Check for PHP Insert Hack
if(array_key_exists("sort_id",$_POST)){
$sort_allowed = array("best","new","comments");
if(in_array($_POST["sort_id"],$sort_allowed)){
$sort_id = $_POST["sort_id"];
}
}
echo "<div id=\"gradient\">";
//If User selected Best Rated or if url is empty:
if (empty($_POST) OR $sort_id == "best") {
//Perform database query
$result = mysql_query("SELECT * , (SELECT COUNT( 1 ) FROM comments C WHERE C.idea_id = I.id) AS COMMENTS, ( SELECT login FROM members M WHERE I.member_id = M.member_id ) as login FROM ideaspace I ORDER BY KARMA DESC", $connection);
$query = mysql_query("SELECT idea_id FROM vote_idea WHERE member_id = $member_id", $connection);
//Create array with which ideas the current user has voted on already
$user_voted_on_this = array();
while($row = mysql_fetch_assoc($query))
{
$user_voted_on_this[] = $row["idea_id"];
}
//If User selected newest:
} elseif ($sort_id == "new") {
$result = mysql_query("SELECT * , (SELECT COUNT( 1 ) FROM comments C WHERE C.idea_id = I.id) AS COMMENTS, ( SELECT login FROM members M WHERE I.member_id = M.member_id ) as login FROM ideaspace I ORDER BY DATE DESC", $connection);
$query = mysql_query("SELECT idea_id FROM vote_idea WHERE member_id = $member_id", $connection);
//Create array with which ideas the current user has voted on already
$user_voted_on_this = array();
while($row = mysql_fetch_assoc($query))
{
$user_voted_on_this[] = $row["idea_id"];
}
//If User selected most commented:
} else {
if ($sort_id == "comments")
$result = mysql_query("SELECT * , (SELECT COUNT( 1 ) FROM comments C WHERE C.idea_id = I.id) AS COMMENTS, ( SELECT login FROM members M WHERE I.member_id = M.member_id ) as login FROM ideaspace I ORDER BY COMMENTS DESC", $connection);
$query = mysql_query("SELECT idea_id FROM vote_idea WHERE member_id = $member_id", $connection);
$user_voted_on_this = array();
while($row = mysql_fetch_assoc($query))
{
$user_voted_on_this[] = $row["idea_id"];
}
}
if (!$result && !$query) {
die("Database connection failed: " . mysql_error());
}
// 4. Use data from database
while ($row = mysql_fetch_array($result)) {
echo
"<dt id=\"idea\">";
if (in_array($row['id'],$user_voted_on_this)) {
echo
"<div class=\"karma-btn_voted\">
<span class=\"voted\">{$row['karma']}</span>
</div>";
} else {
echo
"<div class=\"karma-btn\">
<img src=\"images/btn_lrg_karma.png\" alt=\"Alternative text\"><span class=\"voted\"><div class=\"newkarma\">{$row['karma']}</div></span>
</div>";
}
echo
"<div class=\"textbox\">
<P class=\"category\">" . $row['category'] . "</p>
<P class=\"headline\"> " . $row['d_header']."</P>
<P>" . $shortdesc = myTruncate($row['d_description'], 220, " ") . "</p>" .
"<P class=\"name\">Submitted by " . $row['login'] . " " . date('D d Y', strtotime($row['date'])) . "<img src=\"images/comments.png\" align=\"center\">". $row['COMMENTS'] ."</p>" .
"</div>
</dt></div>";
}
?>
<?Php
require_once('db_close.php');
?>
As I said it worked fine when it was PHP but now that i fetch the data it replaces some characters with diamond ? character icon.

is an encoding issue, lots of things to check - UTF-8 problem when saving to mysql

The response is encoded in cp1252, but your page in UTF8
The char that disappears has decimal-code 146
’
You should change the encoding before you send the response(or better before you insert the data to the db).
mb_convert_encoding($str, "UTF-8", "CP1252");

Thanks everyone I fixed it
mysql_query("SET NAMES utf8"); in the db_connection file.

Related

php only returning 1 row from database

I have the following php code (in a file returndata.php) to retrieve messages for a user:
$sql = 'SELECT * FROM usertimes WHERE receiver ="'. $messagesforaccount. '"';
$result = $conn->query($sql);
$response = array();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$response['message'] = $row["message"];
$response['date'] = $row["date"];
$response['sender'] = $row["sender"];
$response['receiver'] = $row["receiver"];
}
echo json_encode($response);
} else {
echo " 0 results";
}
Then the javascript is as follows (displays the message and some information on it such as the sender, date etc. on the webpage):
$.post(
"returndata.php",
{ messagesforaccount: userAccount },
function(response) {
var sender = response.sender;
var receiver = response.receiver;
var message = response.message;
var date = response.date;
console.log('Retreived data: ', sender, receiver, message, date);
p = document.createElement('p')
p.innerHTML = message + '<br>' + 'sent by ' + sender + ' at ' + date
listmessages.appendChild(p)
}, 'json'
);
This only adds one message to the page (the last one in the database). What should the php be so it loops through all results, and for each result it adds the message to the webpage?
You did a little bit mistake there. If you want associative array for multiple data then you should have a two dimensional array and you must have an index for second dimensional array as well
<?php
$sql = 'SELECT * FROM usertimes WHERE receiver ="'. $messagesforaccount. '"';
$result = $conn->query($sql);
$response = array();
$index = 0;
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$response[$index]['message'] = $row["message"];
$response[$index]['date'] = $row["date"];
$response[$index]['sender'] = $row["sender"];
$response[$index]['receiver'] = $row["receiver"];
$index++;//incrementing index variable
}
echo json_encode($response);
} else {
echo " 0 results";
}
?>
In return you can iterate that array in this way
for ($i=0;$i<count($response);$i++)
{
echo $response[$i]['message'] . "<br>" ;
echo $response[$i]['date'] . "<br>" ;
echo $response[$i]['sender'] . "<br>" ;
echo $response[$i]['receiver'] . "<br>" ;
}
You need to respond with all of them in an array like this:
$sql = 'SELECT `message`, `date`, `sender`, `receiver` FROM `usertimes` WHERE `receiver` ="'. $messagesforaccount. '"';
You should only request the fields you need. This improves performances and reduces overhead. Later, you can just push the whole row to the response.
$result = $conn->query($sql);
$response = array();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$response[] = $row;
}
echo json_encode($response);
} else {
echo " 0 results";
}

PHP: Loop looping through result set

I am having a huge issue looping through results, These two queries work hand in hand to check if a restaurant is open today. My problem is i have restaurants, id 1-5(more in the future). But the loop seems to only get restaurant id 5. I have read many posts on here and it seems like i am doing the right thing. But i cannot seem to loop to get the other restaurant id's.
I am blocked now, newbie who is very open to any suggestions or advise.
$sel = "SELECT Rest_Details.Resturant_ID,Delivery_Pcode.Pcode,Delivery_Pcode.Restaurant_ID
FROM Rest_Details INNER JOIN Delivery_Pcode
ON Delivery_Pcode.Restaurant_ID=Rest_Details.Resturant_ID
WHERE Delivery_Pcode.Pcode LIKE'$searchP'";
$res = $dbc->query($sel);
if (!$res) {
echo "invalid query '" . mysqli_error($dbc) . "\n";
}
$i=1;
while ($row_res = $res->fetch_array()) {
$rest_ = $row_res['Resturant_ID'];
$i++;
}
date_default_timezone_set("Europe/London");
$daynum = jddayofweek(unixtojd());
$query = "SELECT *
FROM Opening_hrs WHERE
Restaurant_ID = $rest_
AND Day_of_week = $daynum";
$run_qu = $dbc->query($query);
if ($run_qu->num_rows > 0) {
while ($row_qu = $run_qu->fetch_assoc()) {
$message = "open" . $row_qu["Open_time"] . "</br>";
}
} else {
$message = $message . "close" . $row_qu["Closing_time"] . "</br>";
}
You could either output whatever you want to within your loop or build-up an output string because the value of $rest_ will always be the last value in the loop and i don't think that's what you want... Again you are doing the same with $message. And I am willing to bet that this is what you want to do:
<?php
date_default_timezone_set("Europe/London");
$sel = "SELECT Rest_Details.Resturant_ID,Delivery_Pcode.Pcode,Delivery_Pcode.Restaurant_ID
FROM Rest_Details INNER JOIN Delivery_Pcode
ON Delivery_Pcode.Restaurant_ID=Rest_Details.Resturant_ID
WHERE Delivery_Pcode.Pcode LIKE'$searchP'";
$res = $dbc->query($sel);
if (!$res) {
echo "invalid query '" . mysqli_error($dbc) . "\n";
}
$i=1;
while ($row_res = $res->fetch_array()) {
$rest_ = $row_res['Resturant_ID'];
$i++; // <== YOU DON'T NEED THIS VARIABLE....
// GET THE DATES WITHIN THE LOOP...
$daynum = jddayofweek(unixtojd());
$query = "SELECT *
FROM Opening_hrs WHERE
Restaurant_ID = $rest_
AND Day_of_week = $daynum";
$run_qu = $dbc->query($query);
if ($run_qu->num_rows > 0) {
while ($row_qu = $run_qu->fetch_assoc()) {
$message = "open" . $row_qu["Open_time"] . "</br>";
}
} else {
$message = $message . "close" . $row_qu["Closing_time"] . "</br>";
}
}
I think this is what you are trying to do.
// $searchP should be checked to prevent SQL injection.
$sel = "SELECT Rest_Details.Resturant_ID, Delivery_Pcode.Pcode,
Delivery_Pcode.Restaurant_ID
FROM Rest_Details INNER JOIN Delivery_Pcode
ON Delivery_Pcode.Restaurant_ID = Rest_Details.Resturant_IDW
WHERE Delivery_Pcode.Pcode LIKE '$searchP'";
$res = $dbc->query($sel);
if (!$res) {
echo "invalid query '" . mysqli_error($dbc) . "\n";
}
// set these once as they don't change
date_default_timezone_set("Europe/London");
$daynum = jddayofweek(unixtojd());
// $i=1; - not required, never used
// loop over the original results
while ($row_res = $res->fetch_array()) {
$rest_ = $row_res['Resturant_ID'];
//$i++; not used
// check for a match
$query = "SELECT * FROM Opening_hrs
WHERE Restaurant_ID = $rest_
AND Day_of_week = $daynum";
$run_qu = $dbc->query($query);
if ($run_qu->num_rows > 0) {
// at least one match
while ($row_qu = $run_qu->fetch_assoc()) {
$message = "open" . $row_qu["Open_time"] . "<br />";
$message .= "close" . $row_qu["Closing_time"] . "<br />";
}
} else {
// no matches
$message = "No results for <i>$daynum</i>.";
}
}
It should be possible to get the details in a single query, but I would need to see your SQL tables for that (and you did not ask for that too :]).
Also, it is <br> or <br />, not </br>.

Conditional mysqli date range check to print a price in sql

This time I'm trying to make some php code to work with mysqli in order to check if today date is between a range of dates in a Mysql table, if the condition is true I need to print a price from a table otherwise it shuould print a different price from another table. so I already have all sql connections set in another php file, the problem is that when I try the code, it just shows nothing, a blank page only. This is the code im using:
<?php
$currentdate = date("Y/m/d");
//basic include files
require_once('/home/user/public_html/folder/db.php');
$seasonalpricedate = mysqli_query($conn, "SELECT `seasonal_price` FROM `hotel_seasonal_price` WHERE room_type_id = '1' AND $currentdate >= 'seasonal_from' AND $currentdate <= 'seasonal_to';");
$result = ($seasonalpricedate) or die(mysqli_error());
if (mysqli_num_rows($result) != 0) {
$standardprice = mysqli_query($conn, "SELECT `room_price` FROM `hotel_room_price` WHERE price_id = '1'");
if(! $standardprice ){
die('Could not get data: ' . mysqli_error());
}
while($standard = mysqli_fetch_array($standardprice, MYSQL_ASSOC)){
echo "$ {$standard['room_price']} ";
}
} else {
if(! $seasonalpricedate ){
die('Could not get data: ' . mysqli_error());
while($standard2 = mysqli_fetch_array($seasonalpricedate, MYSQL_ASSOC)){
echo "$ {$standard2['seasonal_price']} ";
}
}
}
?>
I already tried both codes with standardprice and seasonalprice working without a conditional, but when I try to do it like this, it does not show anything.
PostData: Im still trying to learn english, so please appologize me if I fail some words, thanks in Advance.
UPDATE: Ok so in this way it works if there is no values true its ok, it shows the standardprice, but if match the date, dont show anything, here is the code changed:
<?php
error_reporting(E_ALL);
ini_set('error_reporting', E_ALL);
$currentdate = date("Y-m-d");
//basic include files
require_once('/home/trankilo/public_html/book/db.php');
$seasonalpricedate = mysqli_query($conn, "SELECT `seasonal_price` FROM `hotel_seasonal_price` WHERE room_type_id = '1' AND '$currentdate' >= seasonal_from AND '$currentdate' <= seasonal_to");
$result = ($seasonalpricedate) or die(mysqli_error());
if (mysqli_num_rows($result) != 0) {
$seasonalprice = mysqli_query($conn, "SELECT `seasonal_price` FROM `hotel_seasonal_price` WHERE room_type_id = '1'");
if(! $seasonalprice )
{
die('Could not get data: ' . mysqli_error());
while($standard2 = mysqli_fetch_array($seasonalprice, MYSQL_ASSOC))
{
echo "$ {$standard2['seasonal_price']} ";
}
}
} else {
$standardprice = mysqli_query($conn, "SELECT `room_price` FROM `hotel_room_price` WHERE price_id = '1'");
if(! $standardprice )
{
die('Could not get data: ' . mysqli_error());
}
while($standard = mysqli_fetch_array($standardprice, MYSQL_ASSOC))
{
echo "$ {$standard['room_price']} ";
}
}
mysqli_close($conn);
?>
So close to make it work, thanks to
UPDATE: Because you are also updated your OP, now i found what causes the problem. Ther proble were when you says: die('Could not get data: ' . mysqli_error()); And after that you want to try a while loop. while won't executed, because you terminated the script with a die(); Move the while to the else case of your if condition. See my comments.
Use this:
error_reporting(E_ALL);
ini_set('error_reporting', E_ALL);
//Also display your errors.
display_errors(true);
$currentdate = date("Y-m-d");
//basic include files
require_once('/home/trankilo/public_html/book/db.php');
//Put your query into a variable, so you can dump / print it.
$sql = "SELECT `seasonal_price`"
. " FROM `hotel_seasonal_price`"
. " WHERE room_type_id = '1'"
. " AND '" . $currentdate . "' >= seasonal_from"
. " AND '" . $currentdate . "' <= 'seasonal_to'";
echo $sql;
//Try to run it in the sql directly. Is it gives back you any result?
//Do not need to
$result = mysqli_query($conn, $sql) or die(mysqli_error());
if (mysqli_num_rows($result) != 0) {
//Check if we have result by echoing some dummy text
echo "Yes, we have result!";
$sql = "SELECT `seasonal_price` FROM `hotel_seasonal_price` WHERE room_type_id = '1'";
//Do the same as the previous query. Does it gives you back anything?
$seasonalprice = mysqli_query($conn, $sql);
if (!$seasonalprice) {
//I do not really get what happens here. If you have no seasonalprice,
//then you can not fetch_array on that!
//Move this whole section.... You've say die, and after that do a while?
die('Could not get data: ' . mysqli_error());
} else {
while ($standard2 = mysqli_fetch_assoc($seasonalprice)) {
echo "$ " . $standard2['seasonal_price'] . " ";
}
}
} else {
//Same as previous
$sql = "SELECT `room_price` FROM `hotel_room_price` WHERE price_id = '1'";
$standardprice = mysqli_query($conn, $sql);
if (!$standardprice) {
die('Could not get data: ' . mysqli_error());
//same here, move the while to the else...
} else {
while ($standard = mysqli_fetch_array($standardprice, MYSQL_ASSOC)) {
echo "$ {$standard['room_price']} ";
}
}
}
mysqli_close($conn);

Drag and Drop array NOT EXIST then Insert into MySQL

I have two tables one for user and one for search. When I drag a search over to user it adds entire search list. How do I only insert the item dragged and not the entire search array?
THE PROBLEM IS recordsArray.
<?php
require("db.php");
$action = mysql_real_escape_string($_POST['action']);
$updateRecordsArray = $_POST['recordsArray'];
if ($action == "updateRecordsListings"){
$listingCounter = 1;
foreach ($updateRecordsArray as $recordIDValue) {
$query = "UPDATE records1 SET recordListingID = " . $listingCounter . " WHERE recordID = " . $recordIDValue;
mysql_query($query) or die('Error, update query failed');
//INSERTS array item that does NOT EXIT in userTable
if (mysql_affected_rows()==0) {
$query = mysql_query("INSERT INTO records1 SELECT * FROM records WHERE recordID = " . $recordIDValue);
$query = "UPDATE records1 SET recordListingID = " . $listingCounter . " WHERE recordID = " . $recordIDValue;
mysql_query($query) or die('Error, insert/update query failed');
}
$listingCounter = $listingCounter + 1;
}
echo '<pre>';
print_r($updateRecordsArray);
echo '</pre>';
echo 'If you refresh the page, you will see that records will stay just as you modified.';
}
?>
Both list arrays id must maintain the same id names in order for the above item to acknowledge and process the list items. Keeping things simple I just used the same code for the Search, User format:
<li id="recordsArray_<?php echo $result['recordID']; ?>"><?php echo $result['recordID'] . ". " . $result['recordText']; ?></li>
Javascript:
$(function() {
$("#contentLeft ul, #main ul").sortable({ accept: '.draggable', connectWith: "#contentLeft ul", opacity: 0.6, cursor: 'move', update: function() {
var order = $(this).sortable("serialize") + '&action=updateRecordsListings';
$.post("updateDB.php", order, function(theResponse){
$("#contentRight").html(theResponse);
});
}
});
}).disableSelection();
});
How can I call only the recordsArray items from #content ul?
I can only get one insert per refresh with this but it does drag and drop insert...
Still need an if statement for possible errors because +/-1 if
<?php
require("db.php");
$action = mysql_real_escape_string($_POST['action']);
$updateRecordsArray = $_POST['recordsArray'];
$uRA = $updateRecordsArray;
// Get total number of elements in $updateRecordsArray
$ifArray = $updateRecordsArray;
$resultCount = count($ifArray);
//echo '<br />';
//print_r($resultCount);
// Get total number of rows in $records1
$recordTable = array();
$result = mysql_query("SELECT recordListingID FROM records1");
$numRows = mysql_num_rows($result);
while ($row = mysql_fetch_assoc($result)) {
$recordTable = array_merge($recordTable, array_map('trim', explode(",", $row['recordListingID'])));
}
//Gets $id/$val of elements not in both arrays
$results = array_diff($uRA, $recordTable);
//echo '<br />';
//print_r($numRows);
//Give variables for +/- 1 $numRows
$plusNumRows = $numRows + 1;
$minusNumRows = $numRows - 1;
//echo '<br />';
//print_r($minusNumRows);
// Normal jQuery drag and drop ranking found online
if ($action == "updateRecordsListings"){
$listingCounter = 1;
foreach ($updateRecordsArray as $recordIDValue) {
//If statement for for +/- 1 $numRows
If ($resultCount == $numRows -1 || $resultCount == $numRows || $resultCount == $numRows + 1){
$sql = mysql_query("INSERT INTO records1 SELECT * FROM records WHERE recordID = $recordIDValue");
}
$query = "UPDATE records1 SET recordListingID = " . $listingCounter . " WHERE recordID = " . $recordIDValue;
mysql_query($query) or die('Error, update query failed');
$listingCounter = $listingCounter + 1;
}
echo '<pre>';
print_r($updateRecordsArray);
echo '</pre>';
echo 'If you refresh the page, you will see that records will stay just as you modified.';
}
?>

using only one query to update columns in the database - inplace edit

id car make sales
1 panamera porsche 100
2 italia ferrari 200
3 volante astonmartin 300
4 avantador lamborghini 400
5 slk mercedes 500
So guys, i have this simple table in my database. And i'm gonna echo this table in a while loop.
<ul>
<?php
$query = "SELECT * FROM inplace LIMIT 0, 6";
$result = mysql_query($query) or die ('Query couldn\'t be executed');
while ($row = mysql_fetch_assoc($result)) {
echo '<li class="editable" data-id="'.$row['id'].'" data-col="car">'.$row['car'].'</li>';
echo '<li class="editable" data-id="'.$row['id'].'" data-col="make">'.$row['make'].'</li>';
echo '<li class="editable" data-id="'.$row['id'].'" data-col="sales">'.$row['sales'].'</li>';
}
?>
</ul>
The idea is to update this table using jQuery in-place editor. So here is the code-
$(document).ready(function()
{
$(".editable").bind("dblclick", replaceHTML);
$(".editable2").bind("dblclick", replaceHTML2);
$(".btnSave, .btnDiscard").live("click", handler);
function handler()
{
if ($(this).hasClass("btnSave"))
{
var str = $(this).siblings("form").serialize();
$.ajax({
type: "POST",
async: false,
url: "handler.php",
data: str,
});
}
}
function replaceHTML()
{
var rowId = $(this).parent('li').data('id');
var colName = $(this).parent('li').data('col');
var buff = $(this).html()
.replace(/"/g, """);
$(this).addClass("noPad")
.html("<form><input type=\"text\" name=\"" + colName + "\" value=\"" + buff + "\" /> <input type=\"text\" name=\"buffer\" value=\"" + buff + "\" /><input type=\"text\" name=\"id\" value=\"" + rowId + "\" /></form>Save changes Discard changes")
.unbind('dblclick', replaceHTML);
}
}
);
This is an in-place edit code i got it from the internet and i just tore it down to basic level just to understand the codes. Behrang Saeedzadeh helped me improvise "replace HTML" function.
And here is the update query in handler.php file -
<?php
require("db.php");
if (isset($_POST['id']) && isset($_POST['car'])) {
$id = mysql_real_escape_string($_POST['id']);
$car = mysql_real_escape_string($_POST['car']);
$query = "UPDATE inplace SET car ='$car' WHERE id='$id'";
$result = mysql_query($query) or die ('Query couldn\'t be executed');
if ($result) {echo 1;}
}
else if (isset($_POST['id']) && isset($_POST['make'])) {
$id = mysql_real_escape_string($_POST['id']);
$make = mysql_real_escape_string($_POST['make']);
$query = "UPDATE inplace SET make ='$make' WHERE id='$id'";
$result = mysql_query($query) or die ('Query couldn\'t be executed');
if ($result) {echo 1;}
}
else if (isset($_POST['id']) && isset($_POST['sales'])) {
$id = mysql_real_escape_string($_POST['id']);
$sales = mysql_real_escape_string($_POST['sales']);
$query = "UPDATE inplace SET sales ='$sales' WHERE id='$id'";
$result = mysql_query($query) or die ('Query couldn\'t be executed');
if ($result) {echo 1;}
}
?>
Here in the update query, i have to write a different query for each column. The question is how do i update using only one query for all the columns?
if(isset($_POST['id']) {
$id = mysql_real_escape_string($_POST['id']);
$arr_check = array("car", "make", "sales");
$result = array();
foreach($arr_check as $check) {
if(isset($_POST[$check]))
$result[] = $check . '="' . mysql_real_escape_string($_POST[$check]) . '"';
}
$result = implode(", ", result);
if($result != '') {
$query = "UPDATE inplace SET {$result} WHERE id='{$id}'";
$result = mysql_query($query) or die ('Query couldn\'t be executed');
if ($result) echo 1;
}
}
that should more or less do it
First of all, you might be better off making the entire list a form to begin with, and storing the existing records in hidden form fields. Then, you should have the handler.php script check if any new form entries were submitted, and store them into variables. If no new entry was made, the variables will contain the default value.
Then, you can submit the whole update query in one shot:
$query = "UPDATE inplace SET car ='$car', make='$make', sales='$sales' WHERE id='$id'";
$result = mysql_query($query) or die ('Query couldn\'t be executed');
if ($result) echo 1;

Categories