Error in updating a database table using a mysql query - php

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

Related

How to update multiple columns in SQL?

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

PDOException thrown in PHP

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;

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.

How to improve getTotalProducts on Opencart controllers

i didnt know before but there is a huge bug in Opencart official release, in a store when you have a lot, of products & categories, it takes upon 50sec!!! to load a page. 50sec!!! , i take a look into the code and google, and found that the problem is well documented, as almost everybody know that this line is causing everything. (counting from cache)
$product_total = $this->model_catalog_product->getTotalProducts($data);
The solution posted every where consists in comment out this line , wich by the way at least for me works better if i just set $product_total to be empty.. Like this
//$product_total = $this->model_catalog_product->getTotalProducts($data);
$product_total = "";
Anyway my problem was solved (the page load in 3 seconds instead of 50 sec) but the count was missing so i keep looking and finally i found this solution wich is pretty much , (until now, still testing) the best solution if your database is handling with a lot of products and categories..http://ergopho.be/speeding-up-opencart-using-the-cache-class/
What it does is basically wrap this entire section of code in an if block, and first checking if the file exists in the cache. If it does not, we run it like normal, and then store it to the cache. If it does, use the cached version instead.
In Controller/Common/Header.php you can found also this code (in the article he do it on categories) here is the code in this file also
$this->data['categories'] = array();
$categories = $this->model_catalog_category->getCategories(0);
foreach ($categories as $category) {
if ($category['top']) {
// Level 2
$children_data = array();
$children = $this->model_catalog_category->getCategories($category['category_id']);
foreach ($children as $child) {
$data = array(
'filter_category_id' => $child['category_id'],
'filter_sub_category' => true
);
$product_total = $this->model_catalog_product->getTotalProducts($data);
$children_data[] = array(
'name' => $child['name'] . ($this->config->get('config_product_count') ? ' (' . $product_total . ')' : ''),
'href' => $this->url->link('product/category', 'path=' . $category['category_id'] . '_' . $child['category_id'])
);
}
Yo have to wrap all this code into this lines
$this->data['categories'] = $this->cache->get('categories');
if(!count($this->data['categories'])) {
<!--Here goes the above code-->
$this->cache->set('categories', $this->data['categories']);
}
Its working fine so far, i hope this help some one else, also pls note that if you have a better way of doing this, i know there is a lot of not advanced users looking for this, so if you can share it with us, it would be great.
¿Can anyone figure out a better fix for this awful slowy bug?
Thanks and lest hope for the next version of Opencart this kind of issues are fixed.
Hope this helps. Peace
This really should go into the model as opposed to the controller.
I have a site that has over 15,000 active products. My method for this looks like so:
public function getTotalProducts($data = array()) {
if ($this->customer->isLogged()):
$customer_group_id = $this->customer->getCustomerGroupId();
else:
$customer_group_id = $this->config->get('config_customer_group_id');
endif;
$sql = "SELECT COUNT(DISTINCT p.product_id) AS total";
if (!empty($data['filter_category_id'])):
if (!empty($data['filter_sub_category'])):
$sql .= " FROM {$this->prefix}category_path cp
LEFT JOIN {$this->prefix}product_to_category p2c
ON (cp.category_id = p2c.category_id)";
else:
$sql .= " FROM {$this->prefix}product_to_category p2c";
endif;
if (!empty($data['filter_filter'])):
$sql .= " LEFT JOIN {$this->prefix}product_filter pf
ON (p2c.product_id = pf.product_id)
LEFT JOIN {$this->prefix}product p
ON (pf.product_id = p.product_id)";
else:
$sql .= " LEFT JOIN {$this->prefix}product p
ON (p2c.product_id = p.product_id)";
endif;
else:
$sql .= " FROM {$this->prefix}product p";
endif;
$sql .= " LEFT JOIN {$this->prefix}product_description pd
ON (p.product_id = pd.product_id)
LEFT JOIN {$this->prefix}product_to_store p2s
ON (p.product_id = p2s.product_id)
WHERE pd.language_id = '" . (int)$this->config->get('config_language_id') . "'
AND p.status = '1'
AND p.date_available <= NOW()
AND p2s.store_id = '" . (int)$this->config->get('config_store_id') . "'";
if (!empty($data['filter_category_id'])):
if (!empty($data['filter_sub_category'])):
$sql .= " AND cp.path_id = '" . (int)$data['filter_category_id'] . "'";
else:
$sql .= " AND p2c.category_id = '" . (int)$data['filter_category_id'] . "'";
endif;
if (!empty($data['filter_filter'])):
$implode = array();
$filters = explode(',', $data['filter_filter']);
foreach ($filters as $filter_id):
$implode[] = (int)$filter_id;
endforeach;
$sql .= " AND pf.filter_id IN (" . implode(',', $implode) . ")";
endif;
endif;
if (!empty($data['filter_name']) || !empty($data['filter_tag'])):
$sql .= " AND (";
if (!empty($data['filter_name'])):
$implode = array();
$words = explode(' ', trim(preg_replace('/\s\s+/', ' ', $data['filter_name'])));
foreach ($words as $word):
$implode[] = "pd.name LIKE '%" . $this->db->escape($word) . "%'";
endforeach;
if ($implode):
$sql .= " " . implode(" AND ", $implode) . "";
endif;
if (!empty($data['filter_description'])):
$sql .= " OR pd.description LIKE '%" . $this->db->escape($data['filter_name']) . "%'";
endif;
endif;
if (!empty($data['filter_name']) && !empty($data['filter_tag'])):
$sql .= " OR ";
endif;
if (!empty($data['filter_tag'])):
$sql .= "pd.tag LIKE '%" . $this->db->escape(utf8_strtolower($data['filter_tag'])) . "%'";
endif;
if (!empty($data['filter_name'])):
$sql .= " OR LCASE(p.model) = '" . $this->db->escape(utf8_strtolower($data['filter_name'])) . "'";
endif;
if (!empty($data['filter_name'])):
$sql .= " OR LCASE(p.sku) = '" . $this->db->escape(utf8_strtolower($data['filter_name'])) . "'";
endif;
if (!empty($data['filter_name'])):
$sql .= " OR LCASE(p.upc) = '" . $this->db->escape(utf8_strtolower($data['filter_name'])) . "'";
endif;
if (!empty($data['filter_name'])):
$sql .= " OR LCASE(p.ean) = '" . $this->db->escape(utf8_strtolower($data['filter_name'])) . "'";
endif;
if (!empty($data['filter_name'])):
$sql .= " OR LCASE(p.jan) = '" . $this->db->escape(utf8_strtolower($data['filter_name'])) . "'";
endif;
if (!empty($data['filter_name'])):
$sql .= " OR LCASE(p.isbn) = '" . $this->db->escape(utf8_strtolower($data['filter_name'])) . "'";
endif;
if (!empty($data['filter_name'])):
$sql .= " OR LCASE(p.mpn) = '" . $this->db->escape(utf8_strtolower($data['filter_name'])) . "'";
endif;
$sql .= ")";
endif;
if (!empty($data['filter_manufacturer_id'])):
$sql .= " AND p.manufacturer_id = '" . (int)$data['filter_manufacturer_id'] . "'";
endif;
$cache = md5 ((int)$customer_group_id . serialize ($data));
$total = $this->cache->get('product.total.products.' . $cache);
if (!$total):
$query = $this->db->query($sql);
$total = $query->row['total'];
$this->cache->set('product.total.products.' . $cache, $total);
endif;
return $total;
}
You'll notice the caching section near the end there.
I also converted over to memcached for caching query results as opposed to file cache. The real problem comes in when you use seo_urls for this many products, I had to completely rewite the entire SeoUrl Controller and the Url library, but it's fast and I've got awesome urls :)

how to insert the multiple array rows in the database?

i am working on dynamic array i need to insert these array in the database.when i insert dynamic array into the database instead of inserting all rows it only inserting one row in the database.
below is the array that contain result
$asma[]=GA::select($ga->population,'total',3);
below is code for inserting multiple array in database table ga
<?php
//code not tested check it
//Logic is changed instead of for looping many times
$data = array();
$j = 0;
foreach($asma as $key => $value)
{
$i = 0;
foreach ( $value as $ind => $hObject )
{
if($i==0)
{
$data[$j]['fe'] = mysql_escape_string($hObject->Voltage);
}else{
$data[$j]['fe'.$i] = mysql_escape_string($hObject->Voltage);
}
$i++;
$data[$j]['fe'.$i] = mysql_escape_string($hObject->Duration);
$i++;
$data[$j]['fe'.$i] = mysql_escape_string($hObject->Number);
$i++;
}
$j++;
}// endforeach
//multiple array
foreach($data as $array)
{
//unique array
//$array3 = array_merge($Voltage,$Duration,$Number);
$fields = implode(',',array_keys($array));
//if you want append any new field append it
$fields .= ','.'timestamp,username';
$vals = "'".implode("','",array_values($array))."'";
//if you want append any new values append it
$vals .= ",'".time()."','".$login_session."'";
$q = "INSERT INTO ga (".$fields.") VALUES(".$vals.")";
$result = mysql_query($q);
if ( ! $result ) {
die( 'Insert failed ' . mysql_errno() . ' ' . mysql_error() );
}
}
whenever user enter 3 then after computation result will store in array asma after store result will store in table ga that should be three rows but only one row insert in the table and display instead of three same in case the user enter any value in the text box.
I'm not sure what you mean, i think is an insert statement like this:
INSERT INTO `ga` (`field1`, `field2`, `field3`, `etc`)
VALUES (value11, value21, value31, more_values1),
(value12, value22, value32, more_values2),
(value13, value23, value33, more_values3)
So you should use your foreach cycle to create the values statement.
$sql = "INSERT INTO `ga` (`voltage`, `duration`, `number`, `timestamp`, `username`) VALUES ";
$values = "";
foreach ($asma as $row) {
$values .= ($values != "" ? "," : "") . "(" .
"'" . $row['voltage'] . "', " .
"'" . $row['voltage'] . "', " .
"'" . $row['number'] . "', " .
"'" . time() . "', " .
"'" . $login_session . "'" .
"),";
}
$sql .= substr($values, 0, -1) . ";";

Categories