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.
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);
Currently, I program a module for Prestashop 1.6.10 which is in the administration panel, using an external API and my problem is that I don't understand how to add a product in the database in back-office.
This is the code I have wrote :
public function Product() {
if (empty($_GET['product'])) {
return false;
}
switch($_GET['product']) {
case 'add' :
$product = new ProductCore();
$product->id_shop_default = 1;
$product->id_manufacturer = 1;
$product->id_supplier = 1;
$product->reference = "adding_product";
$product->supplier_reference = "";
$product->location = "";
$product->width = "0.00000";
$product->height = "0.00000";
$product->depth = "0.00000";
$product->weight = "0.00000";
$product->quantity_discount = "0";
$product->ean13 = "0";
$product->upc = "";
$product->cache_is_pack = "0";
$product->cache_has_attachments = "0";
$product->is_virtual = "0";
$product->save();
$product->add();
break;
/** Product suppression.
case 'del' :
if (Product::existsInDatabase()) {
}
break;
}
return false;
}
I use the "product" object but it is not work and I don't why :(
Could someone help me please ?
You should use Product class instead of ProductCore.
save function is enough to save product in DB. It is not necessary to use add function after that.
If product values are incorrect it will display an error. But you should activate DEBUG MODE first: Activate Prestashop Debug Mode
Good luck.
Try using the following code.
{
$object = new Product();
foreach ($_POST as $key => $value) {
if (array_key_exists($key, $object) && $key != 'id_product') {
$object->{$key} = $value;
}
}
$languages = Language::getLanguages(false);
$class_vars = get_class_vars(get_class($object));
$fields = array();
if (isset($class_vars['definition']['fields'])) {
$fields = $class_vars['definition']['fields'];
}
foreach ($fields as $field => $params) {
if (array_key_exists('lang', $params) && $params['lang']) {
foreach ($languages as $language) {
$value = '';
if (Tools::getIsset($field . '_' . (int)$language['id_lang'])) {
$value = Tools::getValue($field . '_' . (int)$language['id_lang']);
} elseif (isset($object->{$field}[(int)$language['id_lang']])) {
$value = $object->{$field}[(int)$language['id_lang']];
}
foreach ($languages as $lang) {
if (Tools::getIsset($field . '_' . (int)$lang['id_lang']) && Tools::getValue($field . '_' . (int)$lang['id_lang']) != '')
$value = Tools::getValue($field . '_' . (int)$lang['id_lang']);
}
if ($field == 'description_short') {
$short_description_limit = Configuration::get('PS_PRODUCT_SHORT_DESC_LIMIT')
? Configuration::get('PS_PRODUCT_SHORT_DESC_LIMIT') : 400;
$object->{$field}[(int)$language['id_lang']] = strip_tags(
$this->clipLongText(
$value,
'',
$short_description_limit,
false
)
);
} else {
$object->{$field}[(int)$language['id_lang']] = $value;
}
}
}
}
foreach ($languages as $language) {
$keywords = '';
if (Tools::getIsset('meta_keywords_' . $language['id_lang'])) {
$keywords = Tools::getValue('meta_keywords_' . $language['id_lang']);
} elseif (isset($object->meta_keywords[$language['id_lang']])) {
$keywords = $object->meta_keywords[$language['id_lang']];
}
$keywords = $this->cleanMetaKeywords(
Tools::strtolower($keywords)
);
$object->meta_keywords[$language['id_lang']] = $keywords;
}
$_POST['width'] = (!Tools::getIsset('width')) ? '0' : str_replace(',', '.', Tools::getValue('width'));
$_POST['height'] = (!Tools::getIsset('height')) ? '0' : str_replace(',', '.', Tools::getValue('height'));
$_POST['depth'] = (!Tools::getIsset('depth')) ? '0' : str_replace(',', '.', Tools::getValue('depth'));
$_POST['weight'] = (!Tools::getIsset('weight')) ? '0' : str_replace(',', '.', Tools::getValue('weight'));
if (Tools::getIsset('unit_price') != null) {
$object->unit_price = str_replace(',', '.', Tools::getValue('unit_price'));
}
$object->available_for_order = (int)Tools::getValue('available_for_order');
$object->show_price = $object->available_for_order ? 1 : (int)Tools::getValue('show_price');
$object->on_sale = (int)Tools::getValue('on_sale');
$object->online_only = (int)Tools::getValue('online_only');
$ecotaxTaxRate = Tax::getProductEcotaxRate();
if ($ecotax = Tools::getValue('ecotax')) {
$_POST['ecotax'] = Tools::ps_round($ecotax / (1 + $ecotaxTaxRate / 100), 6);
}
if (Tools::getIsset('ecotax') != null) {
$object->ecotax = str_replace(',', '.', Tools::getValue('ecotax'));
}
$object->add();
}
I found a problem in my code : the function Product is not executed by the controller adminController when I click on "Adding a product" from the catalog page.
Moreover, the function works if I force Prestashop to execute the function but Prestashop don't like this because I create a bug and the module is not accessible.
[UPDATE 01-09-2017 at 17:35 GMT]
Currently, the code is working, but I have this problem now ... I think it's about the language parameters when I create the product, but I do not do what I need to do to solve this problem.
enter image description 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
I´m pretty much entirely new to PHP, so please bear with me.
I´m trying to build a website running on a cms called Core. I'm trying to make it so that the previous/next buttons cycle through tags rather than entries. Tags are stored in a database as core_tags. Each tag has it own tag_id, which is a number. I've tried changing the excisting code for thep previous/next buttons, but it keeps giving me 'Warning: mysql_fetch_array() expects parameter 1 to be resource, null given in /home/core/functions/get_entry.php on line 50'.'
Any help would be greatly appreciated.
Get_entry.php:
<?php
$b = $_SERVER['REQUEST_URI'];
if($entry) {
$b = substr($b,0,strrpos($b,"/")) . "/core/";
$id = $entry;
$isPerma = true;
} else {
$b = substr($b,0,mb_strrpos($b,"/core/")+6);
$id = $_REQUEST["id"];
}
$root = $_SERVER['DOCUMENT_ROOT'] . $b;
$http = "http://" . $_SERVER['HTTP_HOST'] . substr($b,0,strlen($b)-5);
require_once($root . "user/configuration.php");
require_once($root . "themes/".$theme."/configuration.php");
require_once($root . "functions/session.php");
if(is_numeric($id)) {
$type = "entry";
} else {
$type = "page";
}
$id = secure($id);
if($type == "page") {
$data = mysql_query("SELECT p.* FROM core_pages p WHERE p.page_title = \"$id\"");
$page_clicks = 0;
while($p = mysql_fetch_array($data)) {
$url = $p["page_url"];
$path = $root . "user/pages/" . $url;
$page_clicks = $p['hits']+1;
require($path);
}
mysql_query("UPDATE core_pages p SET
p.hits = $page_clicks
WHERE p.page_title = $id");
}
if($type == "entry") {
// queries the dbase
$data_tags = mysql_query("SELECT entry_id,entry_title FROM core_entries WHERE entry_show = 1 ORDER BY entry_position DESC") or die(mysql_error());
$navArr=array();
while($tmparray = mysql_fetch_array($data_entries,MYSQL_ASSOC)){
array_push($navArr,$tmparray['entry_id']);
}
function array_next_previous($array, $value) {
$index = array_search($value,$array);
//if user clicked to view the very first entry
if($value == reset($array)){
$return['prev'] = end($array);
$return['next'] = $array[$index + 1];
//if user clicked to view the very last entry
}else if($value == end($array)){
$return['prev'] = $array[$index - 1];
reset($array);
$return['next'] = current($array);
}else{
$return['next'] = $array[$index + 1];
$return['prev'] = $array[$index - 1];
}
return $return;
}
$data = mysql_query("SELECT e.* FROM core_entries e WHERE e.entry_id = $id AND e.entry_show = 1");
$entry_clicks = 0;
if(#mysql_num_rows($data) < 1) {
die("Invalid id, no entry to be shown");
}
while($e = mysql_fetch_array($data)) {
$nextPrevProject = array_next_previous($navArr,$id);
$entry_id = $e['entry_id'];
$entry_title = $e['entry_title'];
// DATE
$t = $e["entry_date"];
$y = substr($t,0,4);
$m = substr($t,5,2);
$d = substr($t,8,2);
$entry_date = date($date_format,mktime(0,0,0,$m,$d,$y));
$entry_text = $e['entry_text'];
$entry_extra1 = $e['entry_extra1'];
$entry_extra2 = $e['entry_extra2'];
$entry_client = $e['entry_client'];
$entry_position = $e['entry_position'];
$entry_hits = $e['hits']+1;
$entry_new = $e['entry_new'];
if($entry_new == 1) {
$isNew = true;
} else {
$isNew = false;
}
if($nice_permalinks) {
$entry_perma = "$http".$entry_id;
} else {
$entry_perma = "$http"."?entry=$entry_id";
}
$data_e2t = #mysql_query("SELECT e2t.tag_id FROM core_entry2tag e2t WHERE e2t.entry_id = $entry_id");
$tag_str = "";
while($e2t = #mysql_fetch_array($data_e2t)) {
$tag_id = $e2t["tag_id"];
$data_tags = #mysql_query("SELECT t.tag_text FROM core_tags t WHERE t.tag_id = $tag_id");
while($t = #mysql_fetch_array($data_tags)) {
$tag_text = $t["tag_text"];
$tag_str = $tag_str . "<a class=\"tag-link\" name=\"tag".$tag_id."\" href=\"#tag-"._encode($tag_text)."\">".$tag_text."</a>".$separator_tags;
}
}
$entry_tags = substr($tag_str,0,strlen($tag_str)-strlen($separator_tags));
$layout_path = $root . "user/uploads/" . treat_string($entry_title) . "/layout.php";
if(is_file($layout_path) && (#filesize($layout_path) > 0)) {
require($layout_path);
} else {
require($theme_path . "parts/entry.php");
}
}
mysql_query("UPDATE core_entries e SET
e.hits = $entry_hits
WHERE e.entry_id = $id");
}
if($isPerma) {
echo "<a class=\"index-link\" href=\"$http\">back to index</a>";
}
?>
You have not defined $data_entries, before using it here:
while($tmparray = mysql_fetch_array($data_entries,MYSQL_ASSOC)){
array_push($navArr,$tmparray['entry_id']);
}
That is why you get the very descriptive error message.
Did you mean to use $data_tags?
Use: "SELECT p.* FROM core_pages p WHERE p.page_title = '".$id."'
Note: mysql_connect is not sql-injection save. If you use mysql_connect, change to PDO.
$data_entries is not defined on line 50, then mysql_fetch_array return an exception of null value given.
Try to change $tmparray = mysql_fetch_array($data_entries,MYSQL_ASSOC) to $tmparray = mysql_fetch_array($data_tags,MYSQL_ASSOC).
Hope this help!
I am using the following code to enter submitted names into the database. The code, when working correctly, should capture the names and other information submitted in the form and create three unique entries in the database. This is not happening. Instead the code is capturing the last name in the three pack and entering its information into the database. You can view the form here beta website. The payment processing script is disabled on the form. What do I need to change in the for loop code to fix this issue? Any assistance is greatly appreciated. Thank you. I have added all of the code that is used in the script below. Hopefully this will give you a better understanding of what is going on in the script.
class DreamModelDream extends JModel {
function getDetails()
{
$session = JFactory::getSession();
if($session->get('dreamticket'))
{
return $session->get('dreamticket');
}
$data = new stdClass();
$data->tickets = -1;
$data->fiftytickets = '';
$data->qty = 0;
$data->fiftyqty = 0;
$data->firstname = '';
$data->firstname2 = '';
$data->firstname3 = '';
$data->lastname = '';
$data->lastname2 = '';
$data->lastname3 = '';
$data->address = '';
$data->address2 = '';
$data->address3 = '';
$data->city = '';
$data->city2 = '';
$data->city3 = '';
$data->postal = '';
$data->postal2 = '';
$data->postal3 = '';
$data->phone = '';
$data->phone2 = '';
$data->phone3 = '';
$data->altphone = '';
$data->altphone2 = '';
$data->altphone3 = '';
$data->email = '';
$data->email2 = '';
$data->email3 = '';
$data->giftname = '';
$data->giftaddress = '';
$data->giftcity = '';
$data->giftpostal = '';
$data->sec_firstname = '';
$data->sec_firstname2 = '';
$data->sec_firstname3 = '';
$data->sec_lastname = '';
$data->sec_lastname2 = '';
$data->sec_lastname3 = '';
$data->agegroup = 0;
$data->expm = 0;
$data->expy = 0;
$data->nameoncard = '';
$data->cctype = '';
$data->ccnum = '';
$data->Media_Radio = false;
$data->Media_TV = false;
$data->Media_Newspaper = false;
$data->Media_Mail = false;
$data->Media_Web = false;
$data->Media_Kinsmen_Member = false;
$data->Media_Other = false;
$data->Radio_CJCY = false;
$data->Radio_MY96 = false;
$data->Radio_ROCK = false;
$data->Radio_CHAT = false;
$data->Radio_POWER = false;
$data->Radio_Other = false;
$data->total = false;
$data->billingphone = '';
$data->agree = 0;
$data->ord_type = 0;
$data->creditcard = '';
$data->user_ip = $_SERVER['REMOTE_ADDR'];
return $data;
}
function getConfirmDetails()
{
$post = JRequest::get('post');
$ticket = new stdClass();
foreach($post as $key => $value)
{
$ticket->$key = $value;
}
$session = JFactory::getSession();
$session->set('dreamticket', $ticket);
if(!strlen($post['firstname'])){
return "Your first name is missing<br>";
}
if(!strlen($post['lastname'])){
return "Your last name is missing<br>";
}
if(!strlen($post['address'])){
return "Your address is missing<br>";
}
if(!strlen($post['city'])){
return "Your city is missing<br>";
}
if(!strlen($post['postal'])){
return "Your postal code is missing<br>";
}
if (!preg_match("/^T\d\w\d\w\d$/i", $post['postal'])) {
//return "Your postal code is invalid for this province<br>";
}
if(!strlen($post['phone'])){
return "Your phone number is missing<br>";
}
if(!strlen($post['email'])){
return "Your email is missing<br>";
}
if($post['tickets'] == '-1'){
////////// TICKET 2
if(!strlen($post['firstname2'])){
return "Your first2 name is missing<br>";
}
if(!strlen($post['lastname2'])){
return "Your last2 name is missing<br>";
}
if(!strlen($post['address2'])){
return "Your address2 is missing<br>";
}
if(!strlen($post['city2'])){
return "Your city2 is missing<br>";
}
if(!strlen($post['postal2'])){
return "Your postal2 code is missing<br>";
}
if (!preg_match("/^T\d\w\d\w\d$/i", $post['postal2'])) {
//return "Your postal2 code is invalid for this province<br>";
}
if(!strlen($post['phone2'])){
return "Your phone number2 is missing<br>";
}
/////////////Ticket 3
if(!strlen($post['firstname3'])){
return "Your first name3 is missing<br>";
}
if(!strlen($post['lastname3'])){
return "Your last name3 is missing<br>";
}
if(!strlen($post['address3'])){
return "Your address3 is missing<br>";
}
if(!strlen($post['city3'])){
return "Your city3 is missing<br>";
}
if(!strlen($post['postal3'])){
return "Your postal code3 is missing<br>";
}
if (!preg_match("/^T\d\w\d\w\d$/i", $post['postal3'])) {
//return "Your postal code3 is invalid for this province<br>";
}
if(!strlen($post['phone3'])){
return "Your phone number3 is missing<br>";
}
}
//////// END TICKET CHECK
if(!strlen($post['nameoncard'])){
return "Your Name on Credit Card is missing<br>";
}
if($post['cctype'] == "Please select one"){
return "Your Credit Card Type is missing<br>";
}
if(!strlen($post['ccnum'])){
return "Your Credit Card Number is missing<br>";
}
if(!strlen($post['billingphone'])){
return "Your billing phone number is missing<br>";
}
if(!strlen($post['agree'])){
return "Your must agree to the Lottery rules in order to proceed<br>";
}
return $ticket;
}
function process()
{
$user = JFactory::getUser();
jimport('joomla.database.table');
$params = JComponentHelper::getParams('com_dream');
$session = JFactory::getSession();
$data = $session->get('dreamticket');
if(!is_object($data))
{
return false;
}
$dif = strtotime("-1 hour");
$timestamp = date("F j, Y, g:i a",$dif);
$ord_id = date('ymdHis') . rand(1000,9999);
$ticket_total = (int) (($data->tickets == '-1') ? '250' : (int) $data->tickets * 100);
$fiftyticket_total = (int) (($data->fiftytickets == '0') ? '' : (int) $data->fiftytickets * 10);
$ordertotal = $ticket_total + $fiftyticket_total;
if(strlen($data->expm) == 1)
{
$data->expm = '0'.$data->expm;
}
if(strlen($data->expy) != 2)
{
$data->expy = substr($data->expy, 2, 2);
}
$data->total = $ordertotal;
JTable::addIncludePath(JPATH_BASE.DS.'administrator'.DS.'components'.DS.'com_dream'.DS.'tables');
$table = JTable::getInstance('Tickets', 'Table');
$table->auth = $auth;
$table->billingphone = $data->billingphone;
$table->Media_Radio = isset($data->Media_Radio) ? 1 : 0;
$table->Media_TV = isset($data->Media_TV) ? 1 : 0;
$table->Media_Newspaper = isset($data->Media_Newspaper) ? 1 : 0;
$table->Media_Mail = isset($data->Media_Mail) ? 1 : 0;
$table->Media_Web = isset($data->Media_Web) ? 1 : 0;
$table->Media_Kinsmen_Member = isset($data->Media_Kinsmen_Member) ? 1 : 0;
$table->Media_Other = isset($data->Media_Other) ? 1 : 0;
$table->Radio_CJCY = isset($data->Radio_CJCY) ? 1 : 0;
$table->Radio_MY96 = isset($data->Radio_MY96) ? 1 : 0;
$table->Radio_ROCK = isset($data->Radio_ROCK) ? 1 : 0;
$table->Radio_CHAT = isset($data->Radio_CHAT) ? 1 : 0;
$table->Radio_POWER = isset($data->Radio_POWER) ? 1 : 0;
$table->Radio_Other = isset($data->Radio_Other) ? 1 : 0;
$table->agegroup = $data->agegroup;
$table->orderdate = date('Y-m-d H:i:s');
$table->ip = $_SERVER['REMOTE_ADDR'];
$table->ord_type = ($user->get('id') > 0) ? 'CallCentre' : 'online';
$table->ord_id = $ord_id;
if($data->tickets == '0') {
$table->ticket_type = 'None';
} elseif($data->tickets == '-1') {
$table->ticket_type = '3Pack';
} elseif($data->tickets == '1') {
$table->ticket_type = '1ticket';
} elseif($data->tickets == '5') {
$table->ticket_type = '8tickets';
}
if($data->fiftytickets == '0') {
$table->fiftyticket_type = 'None';
} elseif($data->fiftytickets == '1') {
$table->fiftyticket_type = '1ticket';
} elseif($data->fiftytickets == '2') {
$table->fiftyticket_type = '3tickets';
}
$table->province = 'AB';
$table->creditcard = $data->cctype;
if(isset($data->giftpurchase)) {
$table->giftname = $data->giftname;
$table->giftadress = $data->giftadress;
$table->giftcity = $data->giftcity;
$table->giftpostal = $data->giftpostal;
}
$data->ord_id = $ord_id;
$tickets = 1;
$table->qty = $data->tickets;
if($data->tickets === '-1')
{
$tickets = 3;
$table->qty = 3;
} elseif($data->tickets === '1')
{
$tickets = 1;
$table->qty = 1;
} elseif($data->tickets === '5')
{
$tickets = 8;
$table->qty = 8;
}
$threepack = '';
$i = '';
for($i = 0; $i < $tickets; $i++)
{
$firstname = 'firstname'.$threepack;
$lastname = 'lastname'.$threepack;
$address = 'address'.$threepack;
$city = 'city'.$threepack;
$postal = 'postal'.$threepack;
$phone = 'phone'.$threepack;
$altphone = 'altphone'.$threepack;
$sec_firstname = 'sec_firstname'.$threepack;
$sec_lastname = 'sec_lastname'.$threepack;
$email = 'email'.$threepack;
$table->firstname = $data->$firstname;
$table->lastname = $data->$lastname;
$table->address = $data->$address;
$table->city = $data->$city;
$table->postal = $data->$postal;
$table->phone = $data->$phone;
$table->altphone = $data->$altphone;
$table->sec_firstname = $data->$sec_firstname;
$table->sec_lastname = $data->$sec_lastname;
$table->email = $data->$email;
$table->id = 0;
if($data->tickets === '-1' || $data->tickets === '5')
{
if($threepack == 2)
{
$threepack = 3;
} else {
$threepack = 2;
}
}
}
$fiftytickets = 1;
$table->fiftyqty = $data->fiftytickets;
if($data->fiftytickets === '1')
{
$fiftytickets = 1;
$table->fiftyqty = 1;
} elseif($data->fiftytickets === '2')
{
$fiftytickets = 3;
$table->fiftyqty = 3;
}
$table->order_total = $data->total;
$table->store();
//sending confirmation mail
$mailcontent = '';
for($i = 0; $i < $data->tickets; $i++)
I have figured out the issues with the for loop. The fiftytickets code needed to be moved above the for loop and the $table->store() function needed to be moved into the for loop and placed after the $table->id line. Now when a ticket or tickets are purchased, three entries with the same name or unique names are inserted into the database.