how to break it into function - php

I have some 'else if' cases in a page. Now I want to make only a single function so that code length may be shorten.
elseif ($domain == 1 && $case == 2) {
$result = array();
foreach ($array as $data) {
$result[] = $data;
}
foreach ($result as $index) {
foreach ($index as $value) {
$resultArr[] = explode(' ', $value[0]);
}
}
$valuesArr = array();
//////********Below code is repeated in this page **************///////
$sql = "INSERT INTO LEAD_TMP_UPLOAD (LEAD_SOURCE , LAST_NAME , EMAIL , MOBILE , IVR_NUMBER , RECORDING_URL , COUNTRY , LEAD_STATUS , DEAD_REASON , PROJECT_NAME
, CUSTOMER_QUERY , DESCRIPTION , LEAD_OWNER , FOLLOW_UP_DATE , CITY_INTERESTED_IN , LOCALITY , UPLOAD_DATE , UPLOAD_BY_ID , REFERED_BY
, REFERED_LEAD_ID , SUB_BROKER_DETAIL , BUDGET , USER_ENQUIRY_TIME , LEAD_TYPE , INSERT_STATUS , PROCESSING_STATUS , UPDATED_AT , LEAD_STAGE ) values ";
foreach ($resultArr as $data) {
$lead_source = "99Acres";
$name = trim(strip_tags(str_replace('Name : ', '', $data[0]))) ;
$emailId = trim(strip_tags(str_replace(array('Email : ', 'Verified'), '', $data[1])));
$contactNo = trim(strip_tags(str_replace(array('Phone number : ', ' Verified'), '', $data[2])));
$ivr_no = ""; //null
$recording_url = ""; //null
$country = "";
$lead_status = "New";
$dead_reason = ""; //null
$project_name = trim(strip_tags($value[2]));;
$customer_query = " ";
$description = " ";
$lead_owner = "sachin.sharma";
$follow_up_date = date('Y-F-j h:i:s A'); //current date
$city_interested_in = "";
$locality = "";
$upload_date = date('Y-F-j h:i:s A'); //current date
$upload_by_id = 2;
$reffered_by = 0;
$reffered_lead_id = 0;
$sub_broker_detail = 0;
$budget = ""; //max range
$user_enquiry_time = ""; //mailbox time
$lead_type = "";
$insert_status = "";
$processing_status = "";
$updated_at = "";
$lead_stage = "cold";
$valuesArr[] .= "('$lead_source', '$name', '$emailId', '$contactNo', '$ivr_no', '$recording_url', '$country', '$lead_status', '$dead_reason', '$project_name ', '$customer_query', '$description', '$lead_owner', '$follow_up_date', '$city_interested_in', '$locality', '$upload_date', '$upload_by_id', '$reffered_by', '$reffered_lead_id', '$sub_broker_detail' , '$budget' , '$user_enquiry_time', '$lead_type', '$insert_status', '$processing_status', '$updated_at', '$lead_stage')";
}
$sql .= implode(',', $valuesArr);
echo $sql;
//////********Till Here, code is repeated in this page **************///////
}
please tell my how can i break above code into another function so that I can save my code length from same code repetition.

you mean something like this?
elseif ($domain == 1 && $case == 2) {
$result = array();
foreach ($array as $data) {
$result[] = $data;
}
foreach ($result as $index) {
foreach ($index as $value) {
$resultArr[] = explode(' ', $value[0]);
}
}
$valuesArr = array();
_insert($resultArr);
}
function _insert($resultArr){
$sql = "INSERT INTO LEAD_TMP_UPLOAD (LEAD_SOURCE , LAST_NAME , EMAIL , MOBILE , IVR_NUMBER , RECORDING_URL , COUNTRY , LEAD_STATUS , DEAD_REASON , PROJECT_NAME
, CUSTOMER_QUERY , DESCRIPTION , LEAD_OWNER , FOLLOW_UP_DATE , CITY_INTERESTED_IN , LOCALITY , UPLOAD_DATE , UPLOAD_BY_ID , REFERED_BY
, REFERED_LEAD_ID , SUB_BROKER_DETAIL , BUDGET , USER_ENQUIRY_TIME , LEAD_TYPE , INSERT_STATUS , PROCESSING_STATUS , UPDATED_AT , LEAD_STAGE ) values ";
foreach ($resultArr as $data) {
$lead_source = "99Acres";
$name = trim(strip_tags(str_replace('Name : ', '', $data[0]))) ;
$emailId = trim(strip_tags(str_replace(array('Email : ', 'Verified'), '', $data[1])));
$contactNo = trim(strip_tags(str_replace(array('Phone number : ', ' Verified'), '', $data[2])));
$ivr_no = ""; //null
$recording_url = ""; //null
$country = "";
$lead_status = "New";
$dead_reason = ""; //null
$project_name = trim(strip_tags($value[2]));;
$customer_query = " ";
$description = " ";
$lead_owner = "sachin.sharma";
$follow_up_date = date('Y-F-j h:i:s A'); //current date
$city_interested_in = "";
$locality = "";
$upload_date = date('Y-F-j h:i:s A'); //current date
$upload_by_id = 2;
$reffered_by = 0;
$reffered_lead_id = 0;
$sub_broker_detail = 0;
$budget = ""; //max range
$user_enquiry_time = ""; //mailbox time
$lead_type = "";
$insert_status = "";
$processing_status = "";
$updated_at = "";
$lead_stage = "cold";
$valuesArr[] .= "('$lead_source', '$name', '$emailId', '$contactNo', '$ivr_no', '$recording_url', '$country', '$lead_status', '$dead_reason', '$project_name ', '$customer_query', '$description', '$lead_owner', '$follow_up_date', '$city_interested_in', '$locality', '$upload_date', '$upload_by_id', '$reffered_by', '$reffered_lead_id', '$sub_broker_detail' , '$budget' , '$user_enquiry_time', '$lead_type', '$insert_status', '$processing_status', '$updated_at', '$lead_stage')";
}
$sql .= implode(',', $valuesArr);
echo $sql;
}

Related

How to Get more order data as variables in prestashop

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

Php Mysql Insert Array in columns

I have the follow problem:
I have differents arrays, each array contain a list of items.
I try to insert in database but each item of list result togheter.
This is my code:
(i use preg_replace for delete between items)
$codice = preg_replace('/(<br>)+$/', '', $_POST['jcitemcodice']);
$prodotto = preg_replace('/(<br>)+$/', '', $_POST['jcitemname']);
$quantita = preg_replace('/(<br>)+$/', '', $_POST['jcitemqty']);
$prezzo = preg_replace('/(<br>)+$/', '', $_POST['jcitemprezzo']);
$a1 = array("$codice","$prodotto","$quantita","$prezzo");
$res = implode("','" ,$a1);
$sql = "INSERT INTO test (codice,prodotto,quantita,prezzo) VALUES ('$res')";
mysql_query($sql);
Making echo of query the result is:
INSERT INTO test (codice,prodotto,quantita,prezzo) VALUES ('SUT03M SUT02M','Arrabbiata Albahaca','12 6','1.25 1.3')
but for to be correct i need the result:
INSERT INTO test (codice,prodotto,quantita,prezzo) VALUES ('SUT03M','Arrabbiata','12','1.25'), VALUES ('SUT02M','Albahaca','6','1.3')
$codice contain: SUT03M SUT02M
$prodotto contain: Arrabbiata Albahaca
$quantita contain: 12 6
$prezzo contain: 1.25 1.3
I have try a lot of codes looking around but always same result.
Thanks you.
Assuming codice, prodotto, quantita, prezzo don't contain value with _ (underscore), you can explode their content separated by it:
//Change existing tag with defined delimiter
$d = "_";//delimiter
$codice = preg_replace('#<[^>]+>#', $d, $_POST['jcitemcodice']);
$prodotto = preg_replace('#<[^>]+>#', $d, $_POST['jcitemname']);
$quantita = preg_replace('#<[^>]+>#', $d, $_POST['jcitemqty']);
$prezzo = preg_replace('#<[^>]+>#', $d, $_POST['jcitemprezzo']);
//replace space in quantita and in prezzo with the delimiter
$quantita = preg_replace(' ', $d, $quantita);
$prezzo = preg_replace(' ', $d, $prezzo);
//Separate data
$tCodice = explode($d, $codice);
$tProdotto = explode($d, $prodotto);
$tQuantita = explode($d, $quantita);
$tPrezzo = explode($d, $prezzo);
//Formulate values string
$values = "";
foreach($tCodice as $key => $_codice){
if($_codice > ""){
$a1 = array(trim($tCodice[$key]), trim($tProdotto[$key]), trim($tQuantita[$key]), trim($tPrezzo[$key]));
$res = implode("','" ,$a1);
if($values != ""){
$values .= ", ";
}
$values .= "('".$res."')";
}
}
$sql = "INSERT INTO test (codice,prodotto,quantita,prezzo) VALUES $values";
echo $sql;
Please improve this for more custom data from you $_POST
This is a generalized code and no matter how many variables u have and it will add null if no match found in the strings u were already split.
$codice = "SUT03M SUT02M";
$prodotto = "Arrabbiata";
$quantita = "12 6";
$prezzo = "1.25 1.3";
$column_keys = array("codice","prodotto","quantita","prezzo");
$res = array();
$c = 0;
$sql = "";
$max = array("k" => 0,"v" => "");
foreach ($column_keys as $key => $value) {
$res[$value] = explode(" ",${$value});
$c = count($res[$value]);
if($c > $max["k"])
$max = array("k" => $c,"v" => $value);
}
if($max["k"] > 0){
$sql = "INSERT INTO test (".implode($column_keys,",").") VALUES ";
for ($i=0; $i < $max["k"] ; $i++) {
$ar = array();
foreach ($column_keys as $key => $value)
$ar[] = isset($res[$value][$i]) ? $res[$value][$i] : "NULL";
$adstrng = $i>0 ? ",":"";
$sql.= $adstrng."(".implode($ar,",").")";
}
}
echo $sql;
As like #tadman commented don't use deprecated codes and try to do in
updated standards like PDO

Getting same data repeatedly more than multiple times(in thousands)

I am trying to get data in table format from database with multiple queries. I am getting the exact data but the data am getting is same data repeatedly more than thousand times. Please I need a help to fix this to get actual data not multiple data below is my code. Please have a look at it. I am not getting any error but the data am getting is multiple and repeated data.
controller:
public function getReports()
{
$records = [];
$data = [];
$data['title'] = 'test Report';
$date_type = $this->input->get('filter_options');
$course = $this->input->get('course');
$filter_options = $date_type;
$department = $this->input->get('department');
$division = $this->input->get('division');
$month = 1;
$year = date('Y');
$day = date('d');
$data['department'] = $department;
$data['course'] = $course;
$data['division'] = $division;
$data['date_type'] = $date_type;
$course_condition = ' AND 1=1 ';
if($course)
$course_condition = ' AND o.title="'.$course.'"';
$department_condition = ' AND 1=1 ';
if($department)
$department_condition = ' AND u.department="'.$department.'"';
$date_condition = ' and 1=1 ';
if($date_type==1)
{
$date_condition = ' and ta.submittimestamp BETWEEN DATE_SUB(NOW(), INTERVAL 300 DAY) AND NOW() ';
//dd($date_condition);
}
else if($date_type==2)
{
$date_condition = ' and MONTH(ta.submittimestamp) = MONTH(CURRENT_DATE())
AND YEAR(ta.submittimestamp) = YEAR(CURRENT_DATE()) ';
}
else if($date_type==3)
{
$year = $this->input->get('year');
$month = $this->input->get('month');
$date_condition = ' and YEAR(ta.submittimestamp) = "'.$year.'" and MONTH(ta.submittimestamp) = "'.$month.'" ';
}
$group_condition = "GROUP by u.usr_id";
if ($course)
$users_query="SELECT o.title as course_title,u.*,u.usr_id,o.obj_id FROM object_data o,usr_data u,obj_members rn WHERE o.obj_id=rn.obj_id AND u.usr_id=rn.usr_id AND o.type='crs' AND o.obj_id=$course";
$user_records = $this->base_model->executeSelectQuery($users_query);
$final_data = [];
foreach($user_records as $user)
{
if(!$course)
continue;
$user_course_query="SELECT *, (select obj_id FROM object_reference f WHERE e.child = f.ref_id limit 1 ) as final_reference FROM object_data a , object_data g,tree c,tree e , object_reference b ,object_reference f,object_reference d WHERE a.obj_id = b.obj_id AND b.ref_id = c.parent AND c.child = d.ref_id AND d.ref_id = e.parent AND f.obj_id = g.obj_id AND a.obj_id=$course ";
$user_course_records = $this->base_model->executeSelectQuery($user_course_query);
foreach($user_course_records as $course_data)
{
$final_reference=$course_data->final_reference;
$user_tests_query = "SELECT u.firstname,o.*,ta.*,tpr.workingtime,tcr.mark_official,(tcr.reached_points/tcr.max_points)*100 as result FROM usr_data u,object_data o,tst_active ta,tst_tests tt ,tst_pass_result tpr, tst_result_cache tcr WHERE u.usr_id=ta.user_fi AND tt.obj_fi=o.obj_id AND ta.test_fi=tt.test_id AND ta.active_id=tpr.active_fi AND tcr.active_fi=ta.active_id AND u.usr_id=$user->usr_id AND o.obj_id = $final_reference ".$date_condition;
$user_tests = $this->base_model->executeSelectQuery($user_tests_query);
foreach($user_tests as $test)
{
$dta['usr_id'] = $user->usr_id;
$dta['firstname'] = $user->firstname;
$dta['email'] = $user->email;
$dta['matriculation'] = $user->matriculation;
$dta['approve_date'] = $user->approve_date;
$dta['department'] = $user->department;
$dta['tries'] = $test->tries;
$dta['test_title'] = $test->title;
$dta['submittimestamp'] = $test->submittimestamp;
$dta['workingtime'] = $test->workingtime;
// $dta['mark_official'] = $test->mark_official;
$dta['result'] = $test->result;
if($test->mark_official=='passed')
$result_status = '<span class="label label-primary"> Passed </span>';
else if($test->mark_official=='failed')
$result_status = '<span class="label label-danger"> Failed </span>';
$dta['status'] = $result_status;
$dta['division'] = $this->udfTextData(2);
$dta['job_title'] = $this->udfTextData(6);
$final_data[] = $dta;
}
}
}
$data['records'] = $final_data;

PHP Building of MySQL Query String from Passed Variables

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

How to disable this search.php file from inserting MYSQL entries?

I'm currently using a script which when someone searches for a movie on my site, it checks the MySQL db to see if the movie data exists.
If it does, it shows the search result. If it doesn't, it goes to IMDB.com, scrapes content and then inserts that data into the MySQL database.
Does anyone know from quickly looking at the code below if there's a way to quickly disable that from happening by just commenting out a line or will it require someone to go over it thoroughly?
I don't want it to go to IMDB if it doesn't see the movie data in the MySQL DB.
<?php
function PageMain() {
global $TMPL;
include('./includes/imdb.php');
$all = 'Sorry, it seems that the movie you where looking for doesn\'t exist or we don\'t have it in our database...';
$text = $_GET['a'];
$name = htmlspecialchars(urldecode($_GET['q']), ENT_QUOTES);
$per_page = 50;
$page_query = mysql_query("SELECT COUNT(id) from imdb WHERE title LIKE '%%$name%'");
$pages = ceil(mysql_result($page_query, 0) / $per_page);
$page = (isset($_GET['page']) AND (int)$_GET['page'] > 0) ? (int)$_GET['page'] : 1;
$start = ($page - 1) * $per_page;
if(!empty($name)) {
$queryid = 'SELECT * FROM imdb WHERE title LIKE "%%'.$name.'%"';
if(mysql_fetch_row(mysql_query($queryid)) >= 1) {
$query = "SELECT * FROM imdb WHERE title LIKE '%%%s%%' LIMIT %d, %d;";
$query = sprintf($query, $name, $start, $per_page);
$result = mysql_query($query);
$TMPL_old = $TMPL; $TMPL = array();
$skin = new skin('search/rows'); $all = '';
while($TMPL = mysql_fetch_assoc($result)) {
if ($TMPL['votes'] == NULL) {$TMPL['votes'] = '?';}
if ($TMPL['tagline'] == NULL) {$TMPL['tagline'] = 'None';}
$TMPL['title_encoded'] = str_replace("+", "-", urlencode($TMPL['title']));
$TMPL['genre'] = '';
foreach(explode(', ', $TMPL['genres']) as $v)
$TMPL['genre'] .= ''.$v.', ';
$TMPL['actor'] = '';
foreach(explode(', ', $TMPL['actors']) as $v)
$TMPL['actor'] .= ''.$v.', ';
$all .= $skin->make();
}
//Incepe selectarea actorilor
$query_actors = "SELECT `actors` FROM `imdb` ORDER BY `id` DESC LIMIT 0,3";
$actors_result = mysql_query($query_actors);
$TMPL = array (); $skin = new skin('shared/actors'); $actors = '';
while ($TMPL = mysql_fetch_assoc($actors_result))
{
$TMPL['actor'] = '';
foreach(explode(', ', $TMPL['actors']) as $v)
$TMPL['actor'] .= ''.$v.' <br />';
$actors .= $skin->make();
}
// Incepe paginarea
$skin = new skin('shared/pagination'); $pagination = '';
if ($pages >= 1 && $page <= $pages) {
for ($x=1; $x<=$pages; $x++) {
$TMPL['pagination'] = ($x == $page) ? '<strong>'.$x.'</strong> ' : ''.$x.' ';
$pagination .= $skin->make();
}
}
$TMPL = $TMPL_old; unset($TMPL_old);
$TMPL['actors'] = $actors;
$TMPL['rows'] = $all;
$TMPL['pagination'] = $pagination;
$text = 'content';
} else {
$imdb = new Imdb();
$movieArray = $imdb->getMovieInfo(htmlEntities($_GET['q']));
if(!isset($movieArray['title_id'])) { $TMPL['rows'] = $all; } else {
$title_id = $movieArray['title_id'];
$poster = $movieArray['poster'];
$title = $movieArray['title'];
$tagline = $movieArray['tagline'];
$year = $movieArray['year'];
$release = $movieArray['release_date'];
$votes = $movieArray['rating'];
$plot = $movieArray['plot'];
$runtime = $movieArray['runtime'];
$storyline = $movieArray['storyline'];
$genres = $movieArray['genres'];
$stars = $movieArray['stars'];
$oscars = $movieArray['oscars'];
$mpaa = $movieArray['mpaa_rating'];
$country = $movieArray['country'];
$actori = implode(", ", $stars);
$genuri = implode(", ", $genres);
$countries = implode(", ", $country);
$trivia = $movieArray['trivia'];
$selectData = "SELECT * FROM `imdb` where `imdbid` = '$title_id'";
if(strlen($poster) >= 5) {
if(mysql_fetch_row(mysql_query($selectData)) === false) {
$insertData = "INSERT INTO `imdb` (`imdbid` , `poster` , `title` , `tagline` , `plot` , `year` , `release`, `country`, `runtime` , `storyline`, `genres`, `actors`, `votes`, `oscars`, `mpaa`, `trivia`) VALUES ('$title_id', 'posters/$title_id.jpg', '$title', '$tagline', '$plot', '$year', '$release', '$countries', '$runtime', '$storyline', '$genuri', '$actori', '$votes', '$oscars', '$mpaa', '$trivia')";
mysql_query($insertData);
$ch = curl_init ($poster);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.12 Safari/535.2');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
$rawdata=curl_exec ($ch);
curl_close ($ch);
$fp = fopen('posters/'.$title_id.'.jpg', 'w');
fwrite($fp, $rawdata);
fclose($fp);
}
} else {
if(mysql_fetch_row(mysql_query($selectData)) === false) {
$insertData = "INSERT INTO `imdb` (`imdbid` , `poster` , `title` , `tagline` , `plot` , `year` , `release`, `country`, `runtime` , `storyline`, `genres`, `actors`, `votes`, `oscars`, `mpaa`, `trivia`) VALUES ('$title_id', 'posters/noposter.jpg', '$title', '$tagline', '$plot', '$year', '$release', '$countries', '$runtime', '$storyline', '$genuri', '$actori', '$votes', '$oscars', '$mpaa', '$trivia')";
mysql_query($insertData);
}
}
$query = "SELECT * FROM imdb WHERE title LIKE '%%%s%%' LIMIT %d;";
$query = sprintf($query, $name, 40);
$result = mysql_query($query);
$TMPL_old = $TMPL; $TMPL = array();
$skin = new skin('search/rows'); $all = '';
while($TMPL = mysql_fetch_assoc($result)) {
if ($TMPL['votes'] == NULL) {$TMPL['votes'] = '?';}
if ($TMPL['tagline'] == NULL) {$TMPL['tagline'] = 'None';}
$TMPL['title_encoded'] = str_replace("+", "-", urlencode($TMPL['title']));
$TMPL['genre'] = '';
foreach(explode(', ', $TMPL['genres']) as $v)
$TMPL['genre'] .= ''.$v.', ';
$TMPL['actor'] = '';
foreach(explode(', ', $TMPL['actors']) as $v)
$TMPL['actor'] .= ''.$v.', ';
$all .= $skin->make();
}
//Incepe selectarea actorilor
$query_actors = "SELECT `actors` FROM `imdb` ORDER BY `id` DESC LIMIT 0,3";
$actors_result = mysql_query($query_actors);
$TMPL = array (); $skin = new skin('shared/actors'); $actors = '';
while ($TMPL = mysql_fetch_assoc($actors_result))
{
$TMPL['actor'] = '';
foreach(explode(', ', $TMPL['actors']) as $v)
$TMPL['actor'] .= ''.$v.' <br />';
$actors .= $skin->make();
}
$TMPL = $TMPL_old; unset($TMPL_old);
$TMPL['actors'] = $actors;
$TMPL['rows'] = $all;
$text = 'content';
}
}
}
$TMPL['query'] = $name;
$TMPL['title'] = 'yourgamecodes.com/ - Movie - '.$name.'';
$skin = new skin("search/$text");
return $skin->make();
}
?>
This:
else {
$imdb = new Imdb();
$movieArray = $imdb->getMovieInfo(htmlEntities($_GET['q']));
You could comment out that whole else block and it would not make any more calls to imdb
Comment out the queries with INSERT
// $insertData = "INSERT INTO `imdb` (...)
// mysql_query($insertData);

Categories