How to update multiple columns in SQL? - php

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

Related

how to apply array_diff with php and sql

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);

Order by rand(). Put first row in the end

Is this possible somehow?:
Select all rows ( order by rand() )
Make a while loop that outputs all rows except the first one
$sql = 'SELECT id, name FROM tablename ORDER BY rand ()';
$stmt = $conn->query($sql);
while ($row = $stmt->fetch_assoc()) {
// IF NOT FIRST ROW, DO THIS
$text .= '<p>' . $row['id'] . '<br />' . $row['name'] . '</p>';
}
And then include the excluded row at end
$text .= '<p>' . $FIRSTROW_id . '<br />' . $FIRSTROW_name . '</p>';
Create a count and if it's first value, save it in variable.
Then, after loop, you use your variable with data from first row.
$sql = 'SELECT id, name FROM tablename ORDER BY rand ()';
$stmt = $conn->query($sql);
$i = 0;
while ($row = $stmt->fetch_assoc())
{
if ( $i == 0 )
$firstrow = $row;
else
$text .= '<p>' . $row['id'] . '<br />' . $row['name'] . '</p>';
$i++;
}
if ( $firstrow )
$text .= '<p>' . $firstrow['id'] . '<br />' . $firstrow['name'] . '</p>';
EDIT : From what you said in comments, you can just pass first row as param in AJAX and exclude it in your query :
$sql = "SELECT id, name FROM tablename WHERE id != '".intval($_GET['id'])."' ORDER BY rand ()";
$stmt = $conn->query($sql);
$_GET['id'] will be param you send by AJAX.

MySQL query through PHP fix

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.

Error in updating a database table using a mysql query

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

How to write query for a php array?

I have the following php array that gets all values from a form full of radios and check-boxes.
foreach(array('buss_type','anotherfield','anotherfield','...etc') as $index)
{
if (isset($this->request->post[$index])) {
$this->data[$index] = $this->request->post[$index];
} else {
$this->data[$index] = NULL;
}
}
Now, I am wondering how to write the query to send those values to my database, to a new table I just created (retailer). Every radio/checkform value has its column in my retailer table, how do I write the query so that all the values contained in $index go to their specific column.
The following is an example of how my other queries look like...
public function addCustomer($data) {
//this is the one I am trying to write, and this one works,
//but I'd have to add every single checkbox/radio name to the
//query, and I have 30!
$this->db->query("INSERT INTO " . DB_PREFIX . "retailer SET buss_t = '" .
(isset($data['buss_t']) ? (int)$data['buss_t'] : 0) .
"', store_sft = '" .
(isset($data['store_sft']) ? (int)$data['store_sft'] : 0) .
"'");
//Ends Here
$this->db->query("INSERT INTO " . DB_PREFIX . "customer SET store_id = '" .
(int)$this->config->get('config_store_id') . "', firstname = '" .
$this->db->escape($data['firstname']) . "', lastname = '" .
$this->db->escape($data['lastname']) . "', email = '" .
$this->db->escape($data['email']) . "', telephone = '" .
$this->db->escape($data['telephone']) . "', fax = '" .
$this->db->escape($data['fax']) . "', password = '" .
$this->db->escape(md5($data['password'])) . "', newsletter = '" .
(isset($data['newsletter']) ? (int)$data['newsletter'] : 0) .
"', customer_group_id = '" .
(int)$this->config->get('config_customer_group_id') .
"', status = '1', date_added = NOW()");
Thanks a lot for any insight you can provide.
the best way would be to create a function that accepts an array and table name as an argument and executes a insert query.
function insertArray($table, $array)
{
$keys =""; $values = "";
foreach($table as $k=>$v)
{
$keys.=($keys != "" ? ",":"").$k:
$values .=($values != "" ? "," :"")."'".$v."'";
}
$this->db->query("INSERT INTO ".$table." (".$keys.") VALUES (".$values.");
}
The array has to be structured like this:
array("db_attribute1"=>"value1","db_attribute2"=>"value2");
Store the column names and column values in separate arrays and use implode() to generate a comma-separated list of columns and values
$values = array();
$columns = array('buss_type','anotherfield','anotherfield','...etc');
foreach($columns as $index)
{
if (isset($this->request->post[$index]))
{
$this->data[$index] = $this->request->post[$index];
$values[] = $this->db->escape($this->request->post[$index]);
}
else
{
$this->data[$index] = NULL;
$values[] = "''";
}
}
$this->db->query("INSERT INTO table_name (" . implode(",", $columns) . ") VALUES (" . implode(",", $values) . ");

Categories