I'm making a page, where depending on the HTML form data gets inserted/updated/deleted into/from the database.
As far as for the UPDATE goes, I have no more ideas how to fix it. The thing is, that you can update anything you want (for example nazwa_klubu only, if let's say you've changed your old nazwa_klubu and want to keep the new name (nazwa klubu = club name) in the database you type the name that you want to change to into Nazwa klubu in the Wprowadz zmiany form, and then in the second Nazwa klubu you type the name you want to be changed.
I believe it is a minor upgrade to make it all work, without having to put countless if cases, but it's my third day with PHP, so I'm confused.
EDIT: So basically, this function works properly, if all fields are filled. But I want it to work even if we fill some of fields - well, I hope you get my point. What's the point of UPDATE if you can't even use it correctly? Rhetorical Q.
And this is how it currently works:
UPDATE Koncerty SET nazwa_klubu = 'NewClubName', WHERE nazwa_klubu = 'OldClubName' AND
But obviously I want this to work like this:
UPDATE Koncerty SET nazwa_klubu = 'NewClubName' WHERE nazwa_klubu = 'OldClubName'
No matter how many input's I'll fill in this form. The first 5 inputs are responsible for SET side, and the second five are after WHERE clause.
Here's the code of the function
function update($table, $data)
{
$new_klub = 'nazwa_klubu = ' . '\'' . $data[data1] . '\',';
$new_adres = 'adres_klubu = ' . '\'' . $data[data2] . '\',';
$new_zespol = 'nazwa_zespolu = ' . '\'' . $data[data3] . '\',';
$new_ile = 'ilosc_czlonkow_zespolu = ' . '\'' . $data[data4] . '\',';
$new_wystep = 'data_wystepu = ' . '\'' . $data[data5] . '\',';
$klub = 'nazwa_klubu = ' . '\'' . $data[data6] . '\' AND';
$adres = 'adres_klubu = ' . '\'' . $data[data7] . '\' AND';
$zespol = 'nazwa_zespolu = ' . '\'' . $data[data8] . '\' AND';
$ile = 'ilosc_czlonkow_zespolu = ' . '\'' . $data[data9] . '\' AND';
$wystep = 'data_wystepu = ' . '\'' . $data[data10] . '\'';
if (empty($data[data1]) AND empty($data[data2]) AND
empty($data[data3]) AND empty($data[data4]) AND empty($data[data5])) {
echo '<span class="error">Zabezpieczenie: Musisz wpisac jakie zmiany chcesz wprowadzic</span>';
exit;
}
if (empty($data[data6]) AND empty($data[data7]) AND
empty($data[data8]) AND empty($data[data9]) AND empty($data[data10])) {
echo '<span class="error">Zabezpieczenie: Musisz wpisac na czym chcesz dokonac zmian</span>';
exit;
}
if (empty($data[data1])) {
$new_klub = '';
}
if (empty($data[data2])) {
$new_adres = '';
}
if (empty($data[data3])) {
$new_zespol = '';
}
if (empty($data[data4])) {
$new_ile = '';
}
if (empty($data[data5])) {
$new_wystep = '';
}
if (empty($data[data6])) {
$klub = '';
}
if (empty($data[data7])) {
$adres = '';
}
if (empty($data[data8])) {
$zespol = '';
}
if (empty($data[data9])) {
$ile = '';
}
if (empty($data[data10])) {
$wystep = '';
}
$safe_updates = "SET SQL_SAFE_UPDATES = 0";
$sql = "UPDATE $table SET
$new_klub
$new_adres
$new_zespol
$new_ile
$new_wystep
WHERE
$klub
$adres
$zespol
$ile
$wystep
";
echo $new_klub;
mysql_query($safe_updates);
$result = mysql_query($sql);
if (!$result) {
echo '<span class="error">' . mysql_error() . '</span><br>' . $sql . '';
}
else {
echo '<span class="success">Wprowadzono zmiany' . $sql . '</span><br>';
}
}
You shouldn't use stack overflow as somewhere ask questions like "Fix my code".
But, you could just put all your $new_ variables into an array
$new = array(
'klub' => 'nazwa_klubu = ' . '\'' . $data[data1] . '\',',
'adres' => 'adres_klubu = ' . '\'' . $data[data2] . '\',',
);
And then you can implode your array
$sql = implode(', ', $new);
Then you wont get trailing commas. Then use the same logic with AND and you'll get your SQL looking okay.
Related
hi am trying to update multiple column , how can i? the first column is shoe1, wanna add another column but cant
// shoe1
$query = "SELECT shoe_id, shoes_image,
shoes FROM " . $DBPrefix . "shoes";
$params[] = array(':shoe_id', floor($time_passed), 'int');
$db->query($query, $params);
$TPL_shoe1_list = '<select name="shoe1">' . "\n";
while ($row = $db->fetch())
{
$selected = ($row['shoes'] == $shoe1) ? 'selected="true"' : '';
$TPL_shoe1_list .= "\t" . '<option value="' . $row['shoes'] . '" ' . $selected . '>' . $row['shoes'] .'</option>' . "\n";
}
$TPL_shoe1_list .= '</select>' . "\n";
In General the sql syntax is
UPDATE table-name
SET column-name = value, column-name = value, ...
WHERE condition
Example:
UPDATE Supplier
SET City = 'Oslo', Phone = '(0)1-953530', Fax = '(0)1-953555'
WHERE Id = 15
Hi im unable to apply array_diff() for when user edits the stockroom detail to replace with the new result.
Here is the edit function where i call out all the variables via sql.
function einv_editStockrm($srid,$code,$name,$desc,$remark,$cat)
{
//connect to database
base_connectDatabase();
$User = base_getUserDetail($_SESSION['uID']);
$Stockroom = einv_getStockrmDetail($srid);
base_executeSQL("UPDATE einv_stockroom
SET einv_stockrm_code='" . $code . "',
einv_stockrm_name='" . $name . "',
einv_stockrm_desc='" . $desc . "',
einv_stockrm_remark='" . $remark . "',
einv_stockrm_cat = '" . $cat . "'
WHERE einv_stockrm_id=" . $srid . "");
base_addTransactionLog('Manage Stock Room', 'Edit',
"
Stock Room Code = " . $code . " ||
Stock Room Name = " . $name . " ||
Stock Room Description = " . $desc . " ||
Stock Room Remark = " . $remark . " ||
Stock Room Category = " . $cat . "
");
Here is the array_diff() function. There may be unnecessary calling and/or lack of coding..not too sure. This set of codings result in no output. The server basically crashes. Any help on this?
//oldsr is existing stockroom data
//newsr is new stockroom data through edit function
//resultsr is the end result
<?php
$StockroomGetAllDetails = array();
$arr2 = einv_getStockrmDetailFromCode($stockroomCode);
$codearr = explode(",", $arr2['einv_stockrm_code']);
$oldsr = array($codearr);
$newsr = array($codearr);
$resultsr = array_diff($newsr, $oldsr);
if(!count(array_diff($oldsr, $newsr)) && !count(array_diff($newsr, $oldsr))) {
// Arrays are equal
} else {
// Array values are different
echo $resultsr;
}
?>
This code is for redirect.
//go to stock room page
echo '<script type="text/javascript">' . "\n";
echo 'window.location="../einventory/view_stockrm.php?id='. $srid .'";';
echo '</script>';
//close the database
base_closeDatabase();
}
This set of codes able to display the new datas added and removed accordingly :)
$oldCat = $Stockroom["einv_stockrm_cat"];
$oldCatArr = explode(",",$oldCat);
$newCatArr = explode(",",$cat);
//Debugging
//print_r($oldCatArr);
//print_r($newCatArr);
$resultCatAdd = array_diff($newCatArr, $oldCatArr);
$resultCatRemove = array_diff($oldCatArr, $newCatArr);
//Debugging
print_r($resultCatAdd);
print_r($resultCatRemove);
I'm getting the error "SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens" when I try to run the below function:
public function find_products($string = '', $fields = array(), $sort_by = '', $sort_dir = 'ASC') {
$fields = empty($fields) ? '*' : ('' . implode(',', $fields) . '?');
$bindings = array('%' . $string . '%','%' . $string . '%','%' . $string . '%');
$and_where_checks = array('series','material');
$AND = '';
// Loop through the POST variables to see what is safe to play with
$allowed = array();
foreach ($and_where_checks as $awc)
if ( ! empty($_POST[$awc]))
$allowed = $awc;
if ( ! empty($allowed)) {
$tmp = array();
foreach ($allowed as $v)
$tmp = '' . $v . ' IN (' . str_pad('', count($v) * 2 - 1, '?,') . ')';
$AND = 'AND (' . implode(' AND ', $tmp) . ') ';
foreach ($allowed as $k)
foreach ($_POST[$k] as $v)
$bindings = $v;
}
$query =
"SELECT " . $fields . " FROM " . $this->product_table . " " .
"WHERE (" . $this->primary_key . " LIKE ? " .
$AND .
"ORDER BY " . $sort_by . " " . $sort_dir;
$sth = $this->$dbh->prepare($query);
$sth->execute($bindings);
return $sth->fetchAll(PDO::FETCH_ASSOC);
}
The $POST[$awc] variables are filled by checkboxes on this page http://ladd-dev.bitstormweb.com/products/interactive-product-finder/. When I choose one of each checkbox group (e.g. 1 Series and 1 Material) the results are fine, but when I choose multiple boxes in the same group, I get the PDOException.
Does anyone know why? I'm still learning this code so any help would be appreciated!
In your query, you only have one variable to be bound (the ?):
$query =
"SELECT " . $fields . " FROM " . $this->product_table . " " .
"WHERE (" . $this->primary_key . " LIKE ? " .
$AND .
"ORDER BY " . $sort_by . " " . $sort_dir;
Here, you must be either binding 0 or binding more than 1. Check how many values are in $bindings.
$sth = $this->$dbh->prepare($query);
$sth->execute($bindings);
You can check how many values are in $bindings by using print_r($bindings);
Update: Without knowing what your input is, your code seems to be using $bindings twice. It is set at the top with 3 values that are the same thing: $bindings = array('%' . $string . '%','%' . $string . '%','%' . $string . '%'); then at the bottom you have a foreach where you are not using an array at all:
foreach ($_POST[$k] as $v)
$bindings = $v;
There is problem with Query :
$outputs = rosy, rosmary; //array1
$filenames =2.2, 3.2; // array 2
Query:
$insert_col = "UPDATE `lil` SET `D`='" .$output. "' WHERE `A`= '" .$filename. "'";// does not work
Instead of the arrays when i give single value, it works very fine, like :
$insert_col = "UPDATE `lil` SET `D`='rosy' WHERE `A`= '2.2'"; // it works
for taking two arrays into the query i have written foreach loop, as follows
foreach (array_combine($outputs, $filenames) as $output => $filename) {
$insert_col = "UPDATE `4` SET `D`='" . $output . "' WHERE `A`= '" . $filename . "'";
echo $insert_col;
}
Please Help !!
try using for loop. get the size of array and run for loop for that no of times
Try
$query = 'UPDATE lil SET D = CASE A';
foreach($arr as $k => $v)
$query .= 'WHEN ' . $k . ' THEN ' . $v;
$query .= ' END';
$insert_col = 'UPDATE 4 SET D = CASE A';
foreach($arr as $output => $filename)
{
$insert_col .= 'WHEN ' . $output . ' THEN ' . $filename;
$insert_col .= ' END';
$insert_result= mysql_query($insert_col)or die("Query failed: " . mysql_error());
dint work #eli
i am trying to bring a set of texts from a PostgreSQL database (field type is text) with ajax into my webpage. The problem i encouter is the newline, it works great when there is no newlines into the text in database, but when i use new lines in the text inside database, the json doesnt give me the data it stored.
function selectCalendarEvents(user_id, event_datestart, event_datestop, callback) {
var request;
if(window.XMLHttpRequest)
request = new XMLHttpRequest();
else
request = new ActiveXObject("Microsoft.XMLHTTP");
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
if(request.responseText.substr(0, 6) == "error ")
alert(errorName[request.responseText.substr(6)]);
else {
jsonCalendarEvents = $.parseJSON(request.responseText);
selectEvents(user_id, event_datestart, event_datestop, callback);
}
}
}
request.open("GET", "php/calendar.php?action=selectCalendarEvents&user_id=" + user_id + "&event_datestart=" + event_datestart + "&event_datestop=" + event_datestop, true);
request.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
request.send();
}
this is my javascript function which requests the data set
if($action == "selectCalendarEvents") {
$user_id = $_GET["user_id"];
$event_datestart = "'" . $_GET["event_datestart"] . "'";
$event_datestop = "'" . $_GET["event_datestop"] . "'";
require_once("connect.php");
$query = "SELECT event_id, event_name, event_datestart, event_datestop, event_timestart, event_timestop, calendar_events.calendar_group, calendar_color, event_info FROM calendar_events LEFT JOIN calendar_calendars ON calendar_events.calendar_group = calendar_calendars.calendar_group WHERE user_id = " . $user_id . " AND calendar_show = true AND event_datestart <= ". $event_datestop . " AND event_datestop >= " . $event_datestart;
$result = pg_query($connect, $query);
if(!$result)
die("error 1"); // query error
$comma = '';
$json = '{"events":[';
while ($row = pg_fetch_row($result)) {
$json .= $comma . '{';
$json .= '"event_id":"' . $row[0] . '",';
$json .= '"event_name":"' . $row[1] . '",';
$json .= '"event_datestart":"' . $row[2] . '",';
$json .= '"event_datestop":"' . $row[3] . '",';
$json .= '"event_timestart":"' . $row[4] . '",';
$json .= '"event_timestop":"' . $row[5] . '",';
$json .= '"calendar_group":"' . $row[6] . '",';
$json .= '"calendar_color":"' . $row[7] . '",';
$json .= '"event_info":"' . $row[8] . '"';
$json .= '}';
$comma = ',';
}
$json .= ']}';
echo $json;
}
this is my php which returns the dataset. If row[8] aka event_info stores text with newlines in it .. when i try to populate my calendar with the events, it seems the json doesnt store any data in it or smt like that.
I found out that i should replace \r\n with <br/> and it will work. im using like this replace(/\r\n/g, "<br/>") when i give the response string to json
jsonCalendarEvents = $.parseJSON(request.responseText.replace(/\r\n/g, "<br/>"));