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

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;

Related

updating my database values through php

Hi I am trying to do a Registration that the users will put their name password and their answers to some questions and then an admin will manually answer to it if it's accepted.I did the system that loads their name password and answers in the database,and I also ran the things that will show the answers to the admin,but I can't figure a way to change a value just for one user not for all of them,I will leave you my codes and everything over here.
Here is my admin.viewapplications.php code
(Here,it shows everything fine,but I can't figure a way that the button to act just for one id not for all)
<?php
//include(__DIR__ . "/signup.php");
include("../resources/config.php");
//$name = $_POST['Name'];
//$mg = $_POST['MG'];
//$pg = $_POST['PG'];
//$rk = $_POST['RK'];
$sql = "SELECT id, name, tutorial, MG, PG, RK FROM rp_users WHERE tutorial = 2";
//$tutorial = "SELECT tutorial FROM rp_users";
$result = mysql_query($sql);
//$result2 = mysql_query($tutorial);
//$value = mysql_fetch_object($result2)
/*if($result)
{
echo "Succes";
}
else
{
die(mysql_error());
}*/
//if($value > 1)
//
while($row = mysql_fetch_array($result))
{
//$tutorial = row["tutorial"];
//f($tutorial == 2)
//}
$id = $row["id"];
$name = $row["name"];
$mg = $row["MG"];
$pg = $row["PG"];
$rk = $row["RK"];
echo "ID: " . $id."<br> <br>";
echo "Nume: " . $name."<br> <br>";
echo "MG: " . $mg."<br> <br>";
echo "PG: " . $pg."<br> <br>";
echo "RK: " . $rk."<br> <br>";
echo '<form action="./?p=applicationaccept" method="POST">';
echo '<input type="submit" name="accept" value="Accepta">';
echo '</form><br>';
echo '<form action="./?p=applicationdeny" method="POST">';
echo '<input type="submit" name="deny" value="Respinge">';
echo '</form><br> <br> <br>';
}
//}
//
?>
And here is my applicationaccept.php
<?php
include("../admin/admin.viewapplications.php");
include("../resources/config.php");
$iduser = $id;
$sql = "UPDATE rp_users SET tutorial=0";
$result = mysql_query($sql);
if($result)
{
echo "Succes";
}
else
{
die(mysql_error());
}
/*while($row = mysql_fetch_array($result))
{
}*/
?>
I think what you want to do is a simple UPDATE to your MySQL database..
but make sure you format the PHP code you're using otherwise it'll give you an ERROR!
Also you have to use 'mysqli' now in PHP!
<?php
$someID = '1';
$sql = "UPDATE `rp_users` SET `tutorial`= '0' WHERE `id` = $someID";
$result = mysqli_query($link, $sql);
if($result)
{
echo "Success";
}
else
{
echo ("Error");
}
?>
BTW I forgot to mntion the '$link' is the connection to your database!
As of my understanding of your question if your form action is applicationaccept.php and you are trying to update for one user in applicationaccept.php file, try this:
<?php
include("../admin/admin.viewapplications.php");
include("../resources/config.php");
$iduser = $_POST["id"]; // pass id as parameter in form
$sql = "UPDATE rp_users SET tutorial=0";// change this line to following line
$sql = "UPDATE rp_users SET tutorial=0 where id=$iduser";
$result = mysql_query($sql);
if($result)
{
echo "Succes";
}
else
{
die(mysql_error());
}
?>
Be aware your code is vulnerable

When I display this page the PHP part of the code is not working. It will not display the topics

Code will not display topics from database. I just get a blank pages.
Any solutions?
The pages loads but it will not display any thing. They want me to add more context but it breaks it so here you go.
<?php
//Database stuff.
include_once("connect.php");
if ($conn->connect_error) {
trigger_error('Database connection failed: ' . $conn->connect_error, E_USER_ERROR);
}else{
mysqli_select_db($conn,"2159928_db");
}
$tid = '';
$cid = $_GET['cid'];
$tid = $_GET['tid'];
$sql = "SELECT * FROM topics WHERE category_id='".$cid."' AND id='".$tid."' LIMIT 1";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) == 1){
echo "<table width ='75%'>";
if (isset($_SESSION['uid'])) {
//echo "<form action ='post_reply.php?cid=".$cid." &tid =".$tid. "' method = 'post'>
//<input type = 'submit' name = 'submit' value = 'Reply'/>";
//echo "<tr><td colspan ='2'><center><input type='submit' value='Reply' onClick = 'window.open = 'post_reply.php?cid=".$cid." &tid =".$tid."' />";
echo "<tr><td colspan ='2'><center><input type='submit' value='Reply' onClick='window.open(\"post_reply.php?cid=$cid&tid=$tid\")' />";
} else {
echo "<tr><td colspan = '2'><p><center> Please login to reply to topics.</p></td></tr>";
}
//Trying to display this. Doesn't even display border box.
while ($row = mysqli_fetch_assoc($result)) {
$sql2 = "SELECT * FROM posts WHERE category_id='".$cid."' AND topic_id='".$tid. "'";
$result2 = mysqli_query($conn, $sql2);
while ($row2 = mysqli_fetch_assoc($result2)){
echo "<tr><td valign ='top' style = 'border: 5px solid #ffffff;'><div style = 'min-height: 125px;'>".$row['topic_title']."<br/>
by ".$row2['post_username']. " - " .$row2['post_date']. "<hr/>".$row2['post_content']."</div></td>";
}
//This part not relevant.
$old_views = $row['topic_views'];
$new_views = $old_views + 1;
$sql3 = "UPDATE topics SET topic_views='".$new_views."' WHERE category_id='".$cid."' AND id ='".$tid."' LIMIT 1";
$result3 = mysqli_query($conn, $sql3);
}
echo "</table>";
} else {
echo "<p>This topic does not exist.</p>";
}
?>
Try echo-ing out your $sql to see if the query is correct.
If query is correct. Try var_dump to see if there are any results.

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.';
}
?>

Update Multiple Rows (PHP + MySQL)

I am working on a lead management system - and as the database for it grows the need for more bulk functions appears - and unfortunately I am getting stuck with one of them. The database stores many different leads - with each lead being assigned to a specific closer; thus the database stores for each lead the lead id, name, closer name, and other info. The main lead list shows a checkbox next to each lead which submits the lead id into an array:
<input type=\"checkbox\" name=\"multipleassign[]\" value=\"$id\" />
Now this all goes to the following page:
<?php
include_once"config.php";
$id = $_POST['multipleassign'];
$id_sql = implode(",", $id);
$list = "'". implode("', '", $id) ."'";
$query = "SELECT * FROM promises WHERE id IN ($list) ";
$result = mysql_query($query);
$num = mysql_num_rows ($result);
if ($num > 0 ) {
$i=0;
while ($i < $num) {
$closer = mysql_result($result,$i,"business_name");
$businessname = mysql_result($result,$i,"closer");
echo "$closer - $businessname";
echo"<br>";
++$i; } } else { echo "The database is empty"; };
echo "<select name=\"closer\" id=\"closer\">";
$query2 = "SELECT * FROM members ";
$result2 = mysql_query($query2);
$num2 = mysql_num_rows ($result2);
if ($num2 > 0 ) {
$i2=0;
while ($i2 < $num2) {
$username = mysql_result($result2,$i2,"username");
$fullname = mysql_result($result2,$i2,"name");
echo "<option value=\"$fullname\">$fullname</option>";
++$i2; } } else { echo "The database is empty"; }
echo "</select>";
?>
I want to be able to use the form on this page to select a closer from the database - and then assign that closer to each of the leads that have been selected. Here is where I have no idea how to continue.
Actually - i got it. I don't know why I didn't think of it sooner. First off I passed the original $list variable over to the new page - and then:
<?php
include_once"config.php";
$ids = $_POST['list'];
$closer = $_POST['closer'];
$query = "UPDATE `promises` SET `closer` = '$closer' WHERE id IN ($ids) ";
mysql_query($query) or die ('Error updating closers' . mysql_error());
echo "A new closer ($closer) was assigned to the following accounts:";
$query = "SELECT * FROM promises WHERE id IN ($list) ";
$result = mysql_query($query);
$num = mysql_num_rows ($result);
if ($num > 0 ) {
$i=0;
while ($i < $num) {
$businessname = mysql_result($result,$i,"business_name");
echo "<li>$businessname";
++$i; } } else { echo "The database is empty"; };
?>
The updated page before this:
$query = "SELECT * FROM promises WHERE id IN ($list) ";
$result = mysql_query($query);
$num = mysql_num_rows ($result);
if ($num > 0 ) {
$i=0;
while ($i < $num) {
$closer = mysql_result($result,$i,"business_name");
$businessname = mysql_result($result,$i,"closer");
echo "$closer - $businessname";
echo"<br>";
++$i; } } else { echo "The database is empty"; };
echo "<form name=\"form1\" method=\"post\" action=\"multiple_assign2.php\">";
echo "<input type=\"hidden\" name=\"list\" value=\"$list\" />";
echo "<select name=\"closer\" id=\"closer\">";
$query2 = "SELECT * FROM members ";
$result2 = mysql_query($query2);
$num2 = mysql_num_rows ($result2);
if ($num2 > 0 ) {
$i2=0;
while ($i2 < $num2) {
$username = mysql_result($result2,$i2,"username");
$fullname = mysql_result($result2,$i2,"name");
echo "<option value=\"$fullname\">$fullname</option>";
++$i2; } } else { echo "The database is empty"; }
echo "</select>";
echo "<input name=\"submit\" type=\"submit\" id=\"submit\" value=\"Reassign Selected Leads\">";
?>
After you select the leads and submit the form , your script should show them in a list with hidden inputs (with name=leads[] and value=the_lead's_id) and next to each lead there will be a dropdown box () which will be populated with all the closers.
After choosing and sending the second form your script will "run" all-over the leads' ids array and update each and every one of them.
Got the idea or you want some code?

To delete queries! I've tried with the posts already available. It didn't work.

My first page to delete queries selected by user query.php which is working absolutely fine:
<form method=post action="delete.php">
List of queries<br/>
<?php
$ebits = ini_get('error_reporting');
error_reporting($ebits ^ E_NOTICE);
mysql_connect("localhost","root","") or die(mysql_error());
mysql_select_db("testdb") or die(mysql_error());
echo "<br />";
$query = "select * from queries ";
$result = mysql_query($query) or die(mysql_error());
$count=mysql_num_rows($result);
while($row = mysql_fetch_array($result))
{
print "<input type='checkbox' name='Query[]' value=\"".$row['queryId']."\"> ";
echo " ". $row['name']." ". $row["address"]." ". $row["contactNo"]."
". $row["query"];
echo "<br />";
}
?>
<input type="submit" value="Delete" name="Delete">
<br/>
</form>
I've tried with following codes for second page delete.php but nothing seems to work.
Code1:
<?php
if($_POST['Delete'])
{
if(count($_POST['checkbox']) > 0) {
foreach($_POST['checkbox'] as $checkbox)
{
$del_id=$checkbox;
$sql = "DELETE * FROM queries WHERE `queryId`= '$del_id'";
$result = mysql_query($sql);
mysql_error();
}
echo "Selected Rows deleted";
} else {
$NEW="Nothing to Delete";
}
}
?>
Code2:
<?php
if(($_POST['Delete']))
{
$count=array();
$count=$_POST['checkbox'];
for($i=0;$i<count($count);$i++){
$del_id = $checkbox[$i];
$sql = "DELETE FROM queries WHERE queryId='$del_id' ";
$result = mysql_query($sql);
}
$NEW="Selected records Deleted";
}
var_dump($_POST['checkbox']);
var_dump($count);
?>
Your checkbox names are "Query", but you're accessing it as $_POST['checkbox']. This should be $_POST['Query'] instead.
EDIT checking from your updated code:
if($_POST['Delete']) {
if(count($_POST['Query']) > 0) {
foreach($_POST['Query'] as $checkbox) {
$del_id=$checkbox;
$sql = "DELETE * FROM queries WHERE queryId= '$del_id'";
$result = mysql_query($sql);
mysql_error();
}
echo "Selected Rows deleted";
}
else {
$NEW="Nothing to Delete";
}
}
Instead of this:
$del_id=$checkbox;
do this:
// if queryId is numeric
$del_id=intval($checkbox);
This makes sure that the value you're working with is numeric, instead of potential malicious input from your user. I'm going under the assumption that queryId is numeric. If it's not, then you need to do this:
// if queryId is not numeric:
$del_id = mysql_real_escape_string($checkbox);
Your DELETE syntax is incorrect:
$sql = "DELETE * FROM queries WHERE queryId= '$del_id'";
You want just DELETE FROM. Also if the value for queryId is numeric, you don't need the quotes around it:
$sql = "DELETE FROM `queries` WHERE `queryId` = $del_id";
Finally, your MySQL error call doesn't do anything useful as is:
mysql_error();
Here's how you should do this, along with the rest of the code:
if($_POST['Delete']) {
if(count($_POST['Query']) > 0) {
foreach($_POST['Query'] as $checkbox) {
$del_id= intval($checkbox);
$sql = "DELETE FROM `queries` WHERE `queryId` = $del_id";
$result = mysql_query($sql);
if(!$result) {
echo "There was an error in the query: " . mysql_error();
}
}
echo "Selected Rows deleted";
}
else {
$NEW="Nothing to Delete";
}
}

Categories