Related
I want to send a message with full order details such as first name, last name, shop_name, order_id, delivery_address, mobile_number, message.
I am using below code to get first_name , last_name, order_reference.
$id_order_state = Tools::getValue('id_order_state');
if ($id_order_state == 122 && Configuration::get('122') != '') //Configuration::get('Sendin_Api_Sms_shipment_Status') == 1 &&
{
$order = new Order(Tools::getValue('id_order'));
$address = new Address((int)$order->id_address_delivery);
$customer_civility_result = Db::getInstance()->ExecuteS('SELECT id_gender,firstname,lastname FROM '._DB_PREFIX_.'customer WHERE `id_customer` = '.(int)$order->id_customer);
$firstname = (isset($address->firstname)) ? $address->firstname : '';
$lastname = (isset($address->lastname)) ? $address->lastname : '';
if (Tools::strtolower($firstname) === Tools::strtolower($customer_civility_result[0]['firstname']) && Tools::strtolower
($lastname) === Tools::strtolower($customer_civility_result[0]['lastname']))
$civility_value = (isset($customer_civility_result['0']['id_gender'])) ? $customer_civility_result['0']['id_gender'] : '';
else
$civility_value = '';
if ($civility_value == 1)
$civility = 'Mr.';
else if ($civility_value == 2)
$civility = 'Ms.';
else if ($civility_value == 3)
$civility = 'Miss.';
else
$civility = '';
$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow('
SELECT `call_prefix`
FROM `'._DB_PREFIX_.'country`
WHERE `id_country` = '.(int)$address->id_country);
if (isset($address->phone_mobile) && !empty($address->phone_mobile))
{
$order_date = (isset($order->date_upd)) ? $order->date_upd : 0;
if ($this->context->language->id == 1)
$ord_date = date('m/d/Y', strtotime($order_date));
else
$ord_date = date('d/m/Y', strtotime($order_date));
$msgbody = Configuration::get('122');
$total_pay = (isset($order->total_paid)) ? $order->total_paid : 0;
$total_pay = $total_pay.''.$this->context->currency->iso_code;
if (_PS_VERSION_ < '1.5.0.0')
$ref_num = (isset($order->id)) ? $order->id : '';
else
$ref_num = (isset($order->reference)) ? $order->reference : '';
$civility_data = str_replace('{civility}', $civility, $msgbody);
$fname = str_replace('{first_name}', $firstname, $civility_data);
$lname = str_replace('{last_name}', $lastname."\r\n", $fname);
$product_price = str_replace('{order_price}', $total_pay, $lname);
$order_date = str_replace('{order_date}', $ord_date."\r\n", $product_price);
$msgbody = str_replace('{order_reference}', $ref_num, $order_date);
$arr = array();
$arr['to'] = $this->checkMobileNumber($address->phone_mobile, $result['call_prefix']);
$arr['text'] = $msgbody;
$this->sendSmsApi($arr);
}
}
How to get other order details.
#Update
I have got all the order data except products data with the below code.
$id_order_state = Tools::getValue('id_order_state');
if ($id_order_state == 122 && Configuration::get('122') != '') //Configuration::get('Sendin_Api_Sms_shipment_Status') == 1 &&
{
$configuration = Configuration::getMultiple(
array(
'PS_SHOP_EMAIL',
'PS_MAIL_METHOD',
'PS_MAIL_SERVER',
'PS_MAIL_USER',
'PS_MAIL_PASSWD',
'PS_SHOP_NAME',
'PS_MAIL_COLOR'
), $id_lang, null, $id_shop
);
$order = new Order(Tools::getValue('id_order'));
$address = new Address((int)$order->id_address_delivery);
$dlv_adr_fields = AddressFormat::getOrderedAddressFields($address->id_country);
$deliveryAddressFormatedValues = AddressFormat::getFormattedAddressFieldsValues($address, $dlv_adr_fields);
$city = $address->city;
$address2 = $address->address1;
$number = $address->phone_mobile;
$payment = $order->payment;
$orderid = $order->id;
$shop_name = $configuration['PS_SHOP_NAME'];
$message = $this->getAllMessages($order->id);
if (!$message || empty($message))
$message = $this->l('No message');
$customer_civility_result = Db::getInstance()->ExecuteS('SELECT id_gender,firstname,lastname FROM '._DB_PREFIX_.'customer WHERE `id_customer` = '.(int)$order->id_customer);
$firstname = (isset($address->firstname)) ? $address->firstname : '';
$lastname = (isset($address->lastname)) ? $address->lastname : '';
if (Tools::strtolower($firstname) === Tools::strtolower($customer_civility_result[0]['firstname']) && Tools::strtolower
($lastname) === Tools::strtolower($customer_civility_result[0]['lastname']))
$civility_value = (isset($customer_civility_result['0']['id_gender'])) ? $customer_civility_result['0']['id_gender'] : '';
else
$civility_value = '';
if ($civility_value == 1)
$civility = 'Mr.';
else if ($civility_value == 2)
$civility = 'Ms.';
else if ($civility_value == 3)
$civility = 'Miss.';
else
$civility = '';
$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow('
SELECT `call_prefix`
FROM `'._DB_PREFIX_.'country`
WHERE `id_country` = '.(int)$address->id_country);
if (isset($address->phone_mobile) && !empty($address->phone_mobile))
{
$order_date = (isset($order->date_upd)) ? $order->date_upd : 0;
if ($this->context->language->id == 1)
$ord_date = date('m/d/Y', strtotime($order_date));
else
$ord_date = date('d/m/Y', strtotime($order_date));
$msgbody = Configuration::get('122');
$total_pay = (isset($order->total_paid)) ? $order->total_paid : 0;
$total_pay = $total_pay.''.$this->context->currency->iso_code;
if (_PS_VERSION_ < '1.5.0.0')
$ref_num = (isset($order->id)) ? $order->id : '';
else
$ref_num = (isset($order->reference)) ? $order->reference : '';
$civility_data = str_replace('{civility}', $civility, $msgbody);
$cit = str_replace('{city}', $city, $civility_data);
$addr1= str_replace('{addr1}', $address2, $cit);
$mobi= str_replace('{mobi}', $number, $addr1);
$pay= str_replace('{pay}', $payment, $mobi);
$oid= str_replace('{oid}', $orderid, $pay);
$sname = str_replace('{sname}', $shop_name, $oid);
$itms = str_replace('{itms}', $items_table2, $sname);
$msg= str_replace('{msg}', $message, $itms);
$fname = str_replace('{first_name}', $firstname, $msg);
$lname = str_replace('{last_name}', $lastname."\r\n", $fname);
$product_price = str_replace('{order_price}', $total_pay, $lname);
$order_date = str_replace('{order_date}', $ord_date."\r\n", $product_price);
$msgbody = str_replace('{order_reference}', $ref_num, $order_date);
$arr = array();
$arr['to'] = '$mobile';
$arr['text'] = $msgbody;
$this->sendSmsApi($arr);
}
}
Now I need getProducts() function code to get all the product details.
You can get information like following code. If you want any other info let me know, I will tell you .
$id_order_state = (int)$order->getCurrentState();
$carrier = new Carrier((int)$order->id_carrier, (int)$order->id_lang);
$addressInvoice = new Address((int)$order->id_address_invoice);
$addressDelivery = new Address((int)$order->id_address_delivery);
$inv_adr_fields = AddressFormat::getOrderedAddressFields($addressInvoice->id_country);
$dlv_adr_fields = AddressFormat::getOrderedAddressFields($addressDelivery->id_country);
$invoiceAddressFormatedValues = AddressFormat::getFormattedAddressFieldsValues($addressInvoice, $inv_adr_fields);
$deliveryAddressFormatedValues = AddressFormat::getFormattedAddressFieldsValues($addressDelivery, $dlv_adr_fields);
if ($order->total_discounts > 0) {
$this->context->smarty->assign('total_old', (float)$order->total_paid - $order->total_discounts);
}
$products = $order->getProducts();
/* DEPRECATED: customizedDatas #since 1.5 */
$customizedDatas = Product::getAllCustomizedDatas((int)$order->id_cart);
Product::addCustomizationPrice($products, $customizedDatas);
OrderReturn::addReturnedQuantity($products, $order->id);
$order_status = new OrderState((int)$id_order_state, (int)$order->id_lang);
$customer = new Customer($order->id_customer);
I want to store in a session, a value (a number) of the first 1-character alphabetical string that shows in the URL, as long as it is not a.
Examples, if visitor arrives to:
mydomain.com/nice-url/?a=1&p=2&v=3&vt_p=5
Then the number that should be stored is 2
(something like $_SESSION['number']=2)
mydomain.com/nice-url/?a=2&v=7
Then the number that should be stored is 7
mydomain.com/nice-url/?z=3&
Then the number that should be stored is 3
mydomain.com/nice-url/?a=1&pv=2&s=30&p=5
Then the number that should be stored is 30
mydomain.com/nice-url/?a=1&v=z&m=8
Then the number that should be stored is 8
I'm already using following code for another use, so perhaps a part of this code can be utilized for this goal as well:
function unparse_url($parsed_url) {
$scheme = isset($parsed_url['scheme']) ? $parsed_url['scheme'] . '://' : '';
$host = isset($parsed_url['host']) ? $parsed_url['host'] : '';
$port = isset($parsed_url['port']) ? ':' . $parsed_url['port'] : '';
$user = isset($parsed_url['user']) ? $parsed_url['user'] : '';
$pass = isset($parsed_url['pass']) ? ':' . $parsed_url['pass'] : '';
$pass = ($user || $pass) ? "$pass#" : '';
$path = isset($parsed_url['path']) ? $parsed_url['path'] : '';
$query = !empty($parsed_url['query']) ? '?' . trim($parsed_url['query'], '&') : '';
$fragment = isset($parsed_url['fragment']) ? '#' . $parsed_url['fragment'] : '';
return "$scheme$user$pass$host$port$path$query$fragment";
}
function strip_query($url, $query_to_strip) {
$parsed = parse_url($url);
$parsed['query'] = preg_replace('/(^|&)'.$query_to_strip.'[^&]*/', '', $parsed['query']);
return unparse_url($parsed);
}
$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
The solution using parse_url, explode and is_numeric functions:
$url = "mydomain.com/nice-url/?a=1&pv=2&s=30&p=5";
$query_papams = explode("&", parse_url($url, PHP_URL_QUERY));
$number = "not found";
foreach ($query_papams as $p) {
$pair = explode("=", $p);
if (strlen($pair[0]) == 1 && $pair[0] !== "a" && is_numeric($pair[1])) {
$number = $pair[1];
break;
}
}
print_r($number); // 30
You could use a simple function to get around this. Here you go:
<?php
$url1 = "mydomain.com/nice-url/?a=1&p=2&v=3&vt_p=5";
$url2 = "mydomain.com/nice-url/?a=2&v=7";
$url3 = "mydomain.com/nice-url/?a=1&pv=2&s=30&p=5";
$url4 = "mydomain.com/nice-url/?a=1&v=z&m=8";
$url5 = "mydomain.com/nice-url/?z=3&jk=23";
function getSavableNumberFromURL($uri){
$objStripped = new stdClass();
$objParsedQuery = new stdClass();
if(!stristr($uri, "?")){
$objStripped->RQ_URI = $uri;
$objStripped->QUERY = null;
}else{
$arrSplit = preg_split("#\?#", $uri);
$objStripped->RQ_URI = $arrSplit[0];
$objStripped->QUERY = $arrSplit[1];
}
$queryString = $objStripped->QUERY;
$queryString = preg_replace("#(^\?)#", "", $queryString);
$arrSplit = preg_split("#\&#", $queryString);
if(!empty($arrSplit) && count($arrSplit)>1 ) {
foreach ($arrSplit as $queryKVPair) {
preg_match("#(.*)(\=)(.*)#", $queryKVPair, $matches);
list($fullNull, $key, $null, $value) = $matches;
$objParsedQuery->$key = $value;
}
}
foreach($objParsedQuery as $propName=>$propVal){
if($propName != "a" && strlen($propName) == 1 && is_numeric($propVal)){
return $propVal;
}
}
return null;
}
$savableNum1 = getSavableNumberFromURL($url1);
$savableNum2 = getSavableNumberFromURL($url2);
$savableNum3 = getSavableNumberFromURL($url3);
$savableNum4 = getSavableNumberFromURL($url4);
$savableNum5 = getSavableNumberFromURL($url5);
var_dump($savableNum1); //DISPLAYS: "2"
var_dump($savableNum2); //DISPLAYS: "7"
var_dump($savableNum3); //DISPLAYS: "30"
var_dump($savableNum4); //DISPLAYS: "8"
var_dump($savableNum5); //DISPLAYS: "3"
// YOU CAN THEN STORE THE VALUES
// USING YOUR FAVORITE MECHANISM ($_SESSION) PERHAPS...
//
//
Test it HERE.
I have a HTML search which is passing variables via $_GET to a PHP which uses these passed variables to build a query string. The problem I am facing is building a query string that may only contain one search criteria or it may contain multiple. If only one criterion is used for the search then there is no need for an "AND" statement in the query. If there are multiple criteria used then "AND" will be needed between each criteria. How can one handle this "AND" related problem?
<?php
$IKfield01 = (isset($_GET['field01']) ? $_GET['field01'] : null);
$IKfield02 = (isset($_GET['field02']) ? $_GET['field02'] : null);
$IKfield03 = (isset($_GET['field03']) ? $_GET['field03'] : null);
$IKfield04 = (isset($_GET['field04']) ? $_GET['field04'] : null);
$IKfield05 = (isset($_GET['field05']) ? $_GET['field05'] : null);
$IKfield06 = (isset($_GET['field06']) ? $_GET['field06'] : null);
$IKfield07 = (isset($_GET['field07']) ? $_GET['field07'] : null);
$IKfield08 = (isset($_GET['field08']) ? $_GET['field08'] : null);
$IKfield09 = (isset($_GET['field09']) ? $_GET['field09'] : null);
$IKfield10 = (isset($_GET['field10']) ? $_GET['field10'] : null);
$searchfield01 = mysqli_real_escape_string($mysqli,$IKfield01);
$searchfield02 = mysqli_real_escape_string($mysqli,$IKfield02);
$searchfield03 = mysqli_real_escape_string($mysqli,$IKfield03);
$searchfield04 = mysqli_real_escape_string($mysqli,$IKfield04);
$searchfield05 = mysqli_real_escape_string($mysqli,$IKfield05);
$searchfield06 = mysqli_real_escape_string($mysqli,$IKfield06);
$searchfield07 = mysqli_real_escape_string($mysqli,$IKfield07);
$searchfield08 = mysqli_real_escape_string($mysqli,$IKfield08);
$searchfield09 = mysqli_real_escape_string($mysqli,$IKfield09);
$searchfield10 = mysqli_real_escape_string($mysqli,$IKfield10);
$prequery = "SELECT * FROM table WHERE";
$prequery1 = "";
$prequery2 = "";
$prequery3 = "";
$prequery4 = "";
$prequery5 = "";
$prequery6 = "";
$prequery7 = "";
$prequery8 = "";
$prequery9 = "";
$prequery10 = "";
$prequery11 = "";
$prequery12 = " LIMIT $maxsearch";
if ($searchfield01 != '') $prequery2 = "genus LIKE '%$searchfield01%'";
if ($searchfield02 != '') $prequery3 = "AND specificEpithet LIKE '%$searchfield02%'";
if ($searchfield03 != '') $prequery4 = "AND stateProvince LIKE '%$searchfield03%'";
if ($searchfield04 != '') $prequery5 = "AND county LIKE '%$searchfield04%'";
if ($searchfield05 != '') $prequery6= "AND family LIKE '%$searchfield05%'";
if ($searchfield06 != '') $prequery7 = "AND locality LIKE '%$searchfield06%'";
if ($searchfield07 != '') $prequery8 = "AND OtherCatalogNumbers LIKE '%$searchfield07%'";
if ($searchfield08 != '') $prequery9 = "AND recordedBy LIKE '%$searchfield08%'";
if ($searchfield09 != '') $prequery10 = "AND recordNumber LIKE '$searchfield09'";
if ($searchfield10 != '') $prequery11 = "AND catalogNumber LIKE '%$searchfield10%'";
$query = "$prequery $prequery2 $prequery3 $prequery4 $prequery5 $prequery6 $prequery7 $prequery8 $prequery9 $prequery10 $prequery11 $prequery12";
$row_count = 0;
$result = mysql_query($query) or die("MS-Query Error in select-query");
$querystats=mysql_num_rows($result);
$resultcounter=1;
while ($row = mysql_fetch_array($result))
{
$IKdfield01 = "$row[field01]";
$IKdfield02 = "$row[field02]";
$IKdfield03 = "$row[field03]";
$IKdfield04 = "$row[field04]";
$IKdfield05 = "$row[field05]";
$IKdfield06 = "$row[field06]";
$IKdfield07 = "$row[field07]";
$IKdfield08 = "$row[field08]";
$IKdfield09 = "$row[field09]";
$IKdfield10 = "$row[field10]";
$IKdfield11 = "$row[field11]";
$IKdfield12 = "$row[field12]";
$IKdfield13 = "$row[field13]";
$IKdfield14 = "$row[field14]";
$IKdfield15 = "$row[field15]";
$IKdfield16 = "$row[field16]";
$IKdfield17 = "$row[field17]";
$IKdfield18 = "$row[field18]";
$IKdfield19 = "$row[field19]";
$IKdfield20 = "$row[field20]";
$IKdfield21 = "$row[field21]";
$IKdfield22 = "$row[field22]";
$IKdfield23 = "$row[field23]";
$IKdfield24 = "$row[field24]";
$IKdfield25 = "$row[field25]";
$IKdfield26 = "$row[field26]";
$IKdfield27 = "$row[field27]";
//output results
echo "$IKfield01, $IKfield02, $IKfield03, $IKfield04, $IKfield05, $IKfield06, $IKfield07, $IKfield08, $IKfield09, $IKfield10, $IKfield11, $IKfield12";
echo "$IKfield13, $IKfield14, $IKfield15, $IKfield16, $IKfield17, $IKfield18, $IKfield19, $IKfield20, $IKfield21, $IKfield22, $IKfield23, $IKfield24";
echo "$IKfield25, $IKfield26, $IKfield27, (EOR) <br>";
$resultcounter++;
$row_count++;
}
?>
You could use WHERE 1 so that you always end with and AND at every clause.
The other solution is to create a variable $where with the criteria and check if there's any content before adding clauses, if yes, you add an AND
<?php
$sql = "SELECT * FROM table"
$where = "";
// ...
if($myparam) {
if(strlen($where) > 0) $where .= ' AND';
$where .= " myparam ='myval'";
}
// ...
if(strlen($where) > 0) $sql = $sql . ' WHERE ' . $where;
I would build an array of parameters, and implode them into a query:
$query_array = array();
$fields = array(
1=>'genus',
2=>'specificEpithet',
3=>'stateProvince',
4=>'county',
5=>'family',
6=>'locality',
7=>'OtherCatalogNumbers',
8=>'recordedBy',
9=>'recordNumber',
10=>'catalogNumber'
);
for($i = 1; $i <= 10; $i++){
$field = 'field' . str_pad($i, 2, " ", STR_PAD_LEFT);
if(!isset($_GET[$field])
continue;
$value = mysqli_real_escape_string($mysqli,$_GET[$field]);
$query_array[] = $fields[$i] . ' LIKE %' . $value . '%';
}
$query = "SELECT * FROM table WHERE " . implode(' AND ', $query_array) . " LIMIT $maxsearch";
$row_count = 0;
$result = mysql_query($query) or die("MS-Query Error in select-query");
//etc
In my project I have a product add page and it has an edit option.
Added product details will goto the product table in mysql database.
I want to log all the editings which includes the time and user it edits.
I done it by creating a copy of table product as product_updated.
Whenever the product is edited, the product table value of that product is stored in the product_updated table with time and user updated.
Then product table is updated with new values.
I'm done it in php mvc framework. My model has the following function.
This is worked,but it shows some error when product name contains ' symbol.
What is the correct way to do this?
function product_edit_save($id = 0,$user_id) {
$query= $this->db->query("SELECT * FROM product WHERE product_id = $id");
$result = $this->db->fetch_object($query);
foreach ($result as $row) {
$this->db->query("INSERT INTO product_updated SET product_id=$row->product_id,product_code = '$row->product_code', product_name =' $row->product_name', product_category = $row->product_category,
product_subcategory = $row->product_subcategory, product_supplier = ' $row->product_supplier', product_generic = $row->product_generic,
product_manufacturer =$row->product_manufacturer,product_image = '$row->product_image', product_combination = $row->product_combination, product_package =$row->product_package,
product_desc = '$row->product_desc', product_type = '$row->product_type', product_division = '$row->product_division',
product_chemical_name='$row->product_chemical_name',product_updatetime=now(),product_update_user=$user_id,product_banned=$row->product_banned", true);
}
$validate_form = true;
$validate_error = array();
$return['status'] = false;
$return['message'] = '';
if ($_POST) {
$code = isset($_POST['code']) ? $_POST['code'] : '';
$name = isset($_POST['name']) ? $_POST['name'] : '';
$category = isset($_POST['category']) ? $_POST['category'] : '';
$sub_category = isset($_POST['sub_category']) ? $_POST['sub_category'] : '';
$generic = isset($_POST['generic']) ? $_POST['generic'] : '';
$manufacturer = isset($_POST['manufacturer']) ? $_POST['manufacturer'] : '';
$combination = isset($_POST['combination']) ? $_POST['combination'] : '';
$package = isset($_POST['package']) ? $_POST['package'] : '';
$desc = isset($_POST['desc']) ? $_POST['desc'] : '';
$type = isset($_POST['type']) ? $_POST['type'] : '';
$division = isset($_POST['division']) ? $_POST['division'] : '';
$chemicalname = isset($_POST['chemicalname']) ? $_POST['chemicalname'] : '';
$ban = isset($_POST['ban']) ? $_POST['ban'] : 0;
if (isset($_POST['supplier'])) {
$supplier = $_POST['supplier'];
} else {
$supplier = array();
}
if ($code == "") {
$validate_error[] = "Code";
$validate_form = false;
} else {
$esc_id = $this->db->escape($id);
$esc_code = $this->db->escape($code);
if ($this->db->num_rows($this->db->query("SELECT product_code FROM product WHERE product_code = $esc_code AND product_id != $esc_id")) != 0) {
$validate_error[] = "Code Duplication";
$validate_form = false;
}
}
if ($name == "") {
$validate_error[] = "Name";
$validate_form = false;
}
if ($category == "-1") {
$validate_error[] = "Category";
$validate_form = false;
}
if ($manufacturer == "-1") {
$validate_error[] = "Manufacturer";
$validate_form = false;
}
if ($validate_form) {
$esc_filename = $this->db->escape('');
$isimage = "";
if (isset($_FILES['image']['name'])) {
$this->library('upload');
$image = $this->library['upload']->image($_FILES['image'], UPLOAD, '180');
if ($image['status'] == 0) {
$validate_error[] = 'image ( ' . $image['message'] . ' )';
$validate_form = false;
} else {
$esc_filename = $this->db->escape($image['filename']);
$isimage = ",product_image = $esc_filename";
}
} else {
$isimage = "";
}
}
if ($validate_form) {
$esc_id = $this->db->escape($id);
$sub_category = isset($_POST['sub_category']) ? $_POST['sub_category'] : '';
$generic = isset($_POST['generic']) ? $_POST['generic'] : '';
$manufacturer = isset($_POST['manufacturer']) ? $_POST['manufacturer'] : '';
$combination = isset($_POST['combination']) ? $_POST['combination'] : '';
$package = isset($_POST['package']) ? $_POST['package'] : '';
$desc = isset($_POST['desc']) ? $_POST['desc'] : '';
$type = isset($_POST['type']) ? $_POST['type'] : '';
$division = isset($_POST['division']) ? $_POST['division'] : '';
$esc_code = $this->db->escape($code);
$esc_name = $this->db->escape(strtoupper($name));
$esc_category = $this->db->escape($category);
$esc_sub_category = $this->db->escape($sub_category);
$esc_supplier = $this->db->escape(implode(",", $supplier));
$esc_generic = $this->db->escape($generic);
$esc_manufacturer = $this->db->escape($manufacturer);
$esc_combination = $this->db->escape($combination);
$esc_package = $this->db->escape($package);
$esc_desc = $this->db->escape($desc);
$esc_type = $this->db->escape(strtoupper($type));
$esc_division = $this->db->escape(strtoupper($division));
$esc_ban=$this->db->escape(strtoupper($ban));
$esc_chemicalname = $this->db->escape($chemicalname);
try {
$this->db->transaction();
$this->db->query("UPDATE product SET product_code = $esc_code, product_name = $esc_name, product_category = $esc_category,product_chemical_name=$esc_chemicalname,
product_subcategory = $esc_sub_category, product_supplier = $esc_supplier, product_generic = $esc_generic,
product_manufacturer = $esc_manufacturer, product_combination = $esc_combination, product_package = $esc_package,
product_desc = $esc_desc $isimage,product_type = $esc_type, product_division = $esc_division,product_banned=$esc_ban WHERE product_id = $esc_id", true);
$this->db->commit();
$return['status'] = true;
$return['message'] = "Successfully Updated";
return $return;
} catch (Exception $e) {
$this->db->rollback();
$return['message'] = "Failed to Update";
return $return;
}
} else {
$return['message'] = "Invalid Field " . implode(", ", $validate_error);
return $return;
}
}
}
mysql_real_escape_string() is deprecated.
Use stripslashes() to clean the variables and (optional) use addslashes() to add them back when reading them.
Example:
$supplier = stripslashes($_POST['supplier']);
As a sidenote, do not use isset(), use !empty().
if(!empty($your_variable)) { ... }
instead of
if(isset($your_variable)) { ... }
In order to make this or you should follow the best practices when it comes to prevention from SQL Injection http://en.wikipedia.org/wiki/SQL_injection
You could either use prepared statements (best option) or at least escape the data that you input in your SQL queries using mysqli_real_escape_string: http://php.net/manual/en/mysqli.real-escape-string.php
This way a query like this
SELECT * FROM table_name WHERE column_name = 'test'data';
will become this
SELECT * FROM table_name WHERE column_name = 'test\'data';
And you will stop getting errors.
I'm working on a script that checks if the url already exists in the database, and if yes adds an additional -1 or -2 etc etc at the end. I found this script
But it 'd need to to check it again after adding-1. Since it may be already existing. How can I do that? I tired i this way
$query = mysql_query("SELECT * FROM posts WHERE url='$url'");
while ( $query ) {
$result = mysql_fetch_assoc($query);
$url = $result['url'];
$urlnew = $result['url'];
$oldurl = $url;
$first = 1;
$separator = '-';
while ( $urlnew == $url ) {
$url = preg_match('/(.+)'.$separator.'([0-9]+)$/', $urlnew, $match);
$urlnew = isset($match[2]) ? $match[1].$separator.($match[2] + 1) : $url.$separator.$first;
$first++;
}
$url = $urlnew;
}
The new code above works just fine. But it checks only once. How can I make it to check untill it dose not exists in the DB?
tried adding a new sql query at the bottom after $url -$urlnew but it only breaks the function.
EDIT
Here's the correct script :D
$query = mysql_query("SELECT * FROM posts WHERE url LIKE '%".$url."%'");
if ( $query ) {
while ( $result = mysql_fetch_assoc($query) ) {
$url = $result['url'];
$urlnew = $result['url'];
$first = 1;
$separator = '-';
while ( $urlnew == $url ) {
preg_match('/(.+)'.$separator.'([0-9]+)$/', $urlnew, $match);
$urlnew = isset($match[2]) ? $match[1].$separator.($match[2] + 1) :$url.$separator.$first;
$first++;
}
}
}
$url = $urlnew;
Your code is likely vulnerable to SQL Injection. You should consider using PDO or MySQLi instead.
Here's an example of how you could do so:
$url = 'www.example.com';
$i = 0;
$max_duplicates = 100;
$query = $pdo->prepare('SELECT COUNT(id) count FROM urls WHERE url=?');
while ($i++ < $max_duplicates) {
$result = $query->execute($url);
if (!$result->fetch(PDO::FETCH_OBJ)->count)
break;
if ($i == 1) {
$url = $url . '-1';
} else {
$n = $i > 10 ? 2 : 1;
$url = substr($url, -$n) . $i;
}
}
Here's what I used for my needs
function checkLink($link, $counter=1){
global $connect;
$newLink = $link;
do{
$checkLink = mysqli_query($connect, "SELECT id FROM table WHERE link = '$newLink'");
if(mysqli_num_rows($checkLink) > 0){
$newLink = $link.'-'.$counter;
$counter++;
} else {
break;
}
} while(1);
return $newLink;
}
$link = 'www.example.com';
$uniquelink = checkLink($link);