Running public function for each iteration in a While Loop - php

I am new to PHP and have done a few tutorials on how to code pages to run code behind. I am having trouble though figuring out why my While loop is only executing a Public Function for the first iteration through the loop. Any ideas?
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
$info = array("name" => "", "class" => "", "description" => "", "characteristics" => "");
for ($c=0; $c < $num; $c++) {
echo $data[$c] . "<br />\n";
$info[$c] = $data[$c];
}
echo print_r($info);
infoDB::getInstance()->create_record($info[0],$info[1],$info[2],$info[3]);}
The code above prints the $info array for each iteration of the While loop, but the create_record function only inserts the results of the first iteration into the corresponding MYSQL Database. Is there something inherent to the logic in PHP/Instantiation that means it only executes on the first iteration?
Below is the function it is calling to for reference (works correctly for the 1st iteration and then does not recur)
public function create_record ($info, $class, $description, $characteristics) {
$this->query("INSERT INTO tbl_info (toon, zeta, description, characteristics)" . " VALUES ('" . $toon . "', '" . $zeta . "', '" . $description . "', '" . $characteristics . "')");
}

Problem Solved
public function create_record ($info, $class, $description, $characteristics) {
$this->query("INSERT INTO tbl_info (toon, zeta, description, characteristics)" . " VALUES ('" . $toon . "', '" . $zeta . "', '" . $description . "', '" . $characteristics . "')");
}
Is Now
public function create_record ($info, $class, $description, $characteristics) {
$name = $this->real_escape_string($name);
$class = $this->real_escape_string($class);
$description = $this->real_escape_string($description);
$characteristics = $this->real_escape_string($characteristics);
$this->query("INSERT INTO tbl_info (toon, zeta, description, characteristics)" . " VALUES ('" . $toon . "', '" . $zeta . "', '" . $description . "', '" . $characteristics . "')");
}
The query was failing based on something it was reading in from the source spreadsheet needing to be escaped

Related

SQL Can't Delete from Table

I have a PHP and I want to do 2 inserts and 1 delete, but I can only make an insert. If the array containt the last parameter == "historico" should delete from instant_table all register with same serial_num and inserte the array intro the instant_table and insert in historical_table("SensorData"). Ifnot (the array don't hace the parameter "historico"), should de delete from instant_table all register with same serial_num and only inserte the array intro the instant_table.
My code:
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$serial_numb = test_input($_POST["serial_numb"]);
$DHTtempC = test_input($_POST["DHTtempC"]);
$DHThumid = test_input($_POST["DHThumid"]);
$CCS811_CO2 = test_input($_POST["CCS811_CO2"]);
$CCS811_tVOC = test_input($_POST["CCS811_tVOC"]);
$PM25 = test_input($_POST["PM25"]);
$PM10 = test_input($_POST["PM10"]);
$reading_date = date("Y-m-d");
$update_status = test_input($_POST["update_status"]);
$tipo_tabla = test_input($_POST["tipo_tabla"]);
// Create connection
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
if ($tipo_tabla == "historico"){
$sql = "INSERT INTO SensorData (serial_numb, DHTtempC, DHThumid, CCS811_CO2, CCS811_tVOC, PM25, PM10, reading_date, update_status)
VALUES ('" . $serial_numb . "', '" . $DHTtempC . "', '" . $DHThumid . "', '" . $CCS811_CO2 . "', '" . $CCS811_tVOC . "', '" . $PM25 . "', '" . $PM10 . "', '" . $reading_date . "', '" . $update_status . "')";
}
$sql = "DELETE FROM instant_data WHERE (serial_numb = '" . $serial_numb . "')";
$sql = "INSERT INTO instant_data (serial_numb, DHTtempC, DHThumid, CCS811_CO2, CCS811_tVOC, PM25, PM10, reading_date, update_status)
VALUES ('" . $serial_numb . "', '" . $DHTtempC . "', '" . $DHThumid . "', '" . $CCS811_CO2 . "', '" . $CCS811_tVOC . "', '" . $PM25 . "', '" . $PM10 . "', '" . $reading_date . "', '" . $update_status . "')";
if ($mysqli->query($sql) === TRUE) {
echo "New record created successfully";
}
else {
echo "Error: " . $sql . "<br>" . $mysqli->error;
}
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
$mysqli->close();
}
else {
echo "No data posted with HTTP POST.";
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
Tu sum up, If the array contains the parameter, INSERTE(TABLE1) + DELETE with same serial_num(TABLE2) + INSERTE(TABLE2). If not DELETE with same serial_num(TABLE2) + INSERTE(TABLE2).
EDIT: Now this code only make the second INSERT
It seems like you are overwriting the content of $sql without executing the queries in between. You have to either:
execute each query before redefining $sql
use $sql .= (instead of $sql =) to concatenate the next query. If you do this, you have to terminate your sql query with an ; before concatenating the next query.
Are you using this code just for an small personal project or are you going to publish this in any way? In case of the later one:
please read into PHP SQL best practices. With your current approach you are vulnerable to SQL injections and your code is kinda difficult to read.

Internal server error 500 when try to insert huge amount of data?

i had a problem. I try to insert huge amount of data ~400K rows.
Somewhere in middle of execution - i get error
"internal server error 500".
Can you help me to solve it? (Laravel 5.1, IIS)
public function updateForClients(Request $request) {
Debugbar::disable();
if($request->has('sku_list') && $request->has('clients')) {
DB::disableQueryLog();
$sku_list = array_map('trim', explode('|', $request->get('sku_list')));
$clients = array_map('trim', explode('|', $request->get('clients')));
$text_color_date = Carbon::parse($request->get('text_color_date'));
$text_color = $request->get('color');
$sql = [];
$today = Carbon::now()->format('Y-m-d H:i:s');
foreach($clients as $client) {
$sql[$client] = "BEGIN TRANSACTION ";
$sql[$client] .= "DELETE FROM eltk.dbo.system_products_meta_client WHERE client_id = '" . $client . "' AND sku IN ('". implode("', '", $sku_list) ."') ";
foreach($sku_list as $sku) {
$sql[$client] .= "INSERT INTO eltk.dbo.system_products_meta_client VALUES ('" . $sku . "', '" . $client . "', '" . $text_color . "', '" . $text_color_date . "', '" . $today ."', '" . $today ."') ";
}
$sql[$client] .= "COMMIT TRANSACTION GO";
}
foreach($sql as $query) {
DB::statement($query);
}
return redirect()->route('product.index')->with('form_success', true)->with('form_message', 'Information saved successfully!');
}
return redirect()->back();
}

I want to show an error if duplicates are there in database using php and mysql

I'm trying to show an error while entering duplicates using php and mysql, but i'm not getting how to complete, please give an solution........
this is my code:
mysql_query(
"INSERT INTO productcost (product, productCategory, model, purchasePrice, mrp, customerPrice, marginCustomer, dealerPrice, marginDealer)
VALUES ('" . $_POST["product"] . "','" . $_POST["productCategory"] . "','" . $_POST["model"] . "','" . $_POST["purchasePrice"] . "','" . $_POST["mrp"] . "','" . $_POST["customerPrice"] . "','" . $_POST["marginCustomer"] . "','" . $_POST["dealerPrice"] . "', '" . $_POST["marginDealer"] . "')");
$current_id = mysql_insert_id();
if(!empty($current_id)) {
$message = "New Product Added Successfully";
}
}
You have to create unique key in productcost table , using unique fields like (product, productCategory, model). Now execute insert query, if there is a recode in the table return error . now you can handle error and give message.
try{
mysql_query("INSERT INTO productcost (product_key_id,product, productCategory,model,purchasePrice, mrp, customerPrice, marginCustomer, dealerPrice, marginDealer)
VALUES
('" . $_POST["created_product_id"] . "','" . $_POST["product"] . "','".$_POST["productCategory"] . "','" . $_POST["model"] . "','".$_POST["purchasePrice"] . "','" . $_POST["mrp"] . "','".$_POST["customerPrice"] . "','" . $_POST["marginCustomer"] . "','".$_POST["dealerPrice"] . "', '" . $_POST["marginDealer"] . "')");
return TRUE;
}
catch(Exception $e){
return FALSE;
}
or you can check is there a recode in table before insert
select count(*) as cc from doc_upload where product_key_id = $_POST["created_product_id"];
To show an error message while entering duplicates:
// First check there are same data available or not using a query by counting the row
$sqlCheck = "SELECT COUNT(`id`) WHERE product = '" . $_POST["product"] . "' AND productCategory = '" . $_POST["productCategory"] . "' AND model = '" . $_POST["model"] . "'"; // You have to add mroe thing in where clause
$CheckQuery = mysql_query($sqlCheck);
// if there is no duplicate data
//
if ($CheckQuery > 0) {
# code...
mysql_query(
"INSERT INTO productcost (product, productCategory, model, purchasePrice, mrp, customerPrice, marginCustomer, dealerPrice, marginDealer)
VALUES ('" . $_POST["product"] . "','" . $_POST["productCategory"] . "','" . $_POST["model"] . "','" . $_POST["purchasePrice"] . "','" . $_POST["mrp"] . "','" . $_POST["customerPrice"] . "','" . $_POST["marginCustomer"] . "','" . $_POST["dealerPrice"] . "', '" . $_POST["marginDealer"] . "')");
$current_id = mysql_insert_id();
if(!empty($current_id)) {
$message = "New Product Added Successfully";
}
} else {
$message = "Data is Duplicated";
}
Note : I'm Giving you an Example . this is how you have to check
duplicate data

How to write query for a php array?

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

escape null values(Nestoria UK)

I am able to retrieve data from a website(Nestoria) and store into my PostGIS database. However not every individual result that is returned have latitude and longitude values and as such they are not stored into the database. I tried using (pg_escape_string) so that it can return null values as double quotes(") but it didn't work. The field type of my lat and long columns in the database is "double precision".
This is a sample output of the error: ("Warning: pg_query() [function.pg-query]: Query failed: ERROR: invalid input syntax for type double precision: "" LINE 1: ...droom garden flat set in a period building with...', '', '') ^ in C:\XAMMP...\database.php on line 12")
Please see the code below for retrieving the data:
<?php
$url = ("http://api.nestoria.co.uk/api?action=search_listings&centre_point=51.5424,-0.1734,2km&listing_type=rent&property_type=all&price_min=min&price_max=max&bedroom_min=0&bedroom_max=0&number_of_results=50&has_photo=1&page=4");
$xml = simplexml_load_file($url);
foreach ($xml->response->listings as $entry) {
echo $entry->attributes()->title;
echo $entry->attributes()->bathroom_number;
echo $entry->attributes()->bedroom_number;
echo $entry->attributes()->datasource_name;
echo $entry->attributes()->guid;
echo $entry->attributes()->img_url;
echo $entry->attributes()->keywords;
echo $entry->attributes()->lister_name;
echo $entry->attributes()->listing_type;
echo $entry->attributes()->price;
echo $entry->attributes()->price_type;
echo $entry->attributes()->property_type;
echo $entry->attributes()->summary;
echo $entry->attributes()->latitude;
echo $entry->attributes()->longitude;
// Process XML file
}
?>
Find below the code to store values into database:
<?php
require 'nestoriauk.php';
// Opens a connection to a PostgresSQL server
$connection = pg_connect("dbname=postgis user=postgres password=xxxx");
// Execute query
foreach ($xml->response->listings as $entry) {
$query = "INSERT INTO nestoriaphp(title, bathroom, bedroom, datasource, guid, image, keywords, lister, listype, price, pricetype, property_type, summary, latitude, longitude) VALUES ('" . pg_escape_string($entry->attributes()->title) . "', '" . pg_escape_string($entry->attributes()->bathroom_number) . "', '" . pg_escape_string($entry->attributes()->bedroom_number) . "', '" . pg_escape_string($entry->attributes()->datasource_name) . "', '" . pg_escape_string($entry->attributes()->guid) ."', '" . pg_escape_string($entry->attributes()->img_url) . "', '" . pg_escape_string($entry->attributes()->keywords) . "', '" . pg_escape_string($entry->attributes()->lister_name) . "', '" . pg_escape_string($entry->attributes()->listing_type) . "', '" . pg_escape_string($entry->attributes()->price) . "', '" . pg_escape_string($entry->attributes()->price_type) . "', '" . pg_escape_string($entry->attributes()->property_type) ."', '" . pg_escape_string($entry->attributes()->summary) . "', '" . pg_escape_string($entry->attributes()->latitude) . "', '" . pg_escape_string($entry->attributes()->longitude) . "')";
$result = pg_query($query);
printf ("These values are inserted into the database - %s %s %s", $entry->attributes()->title, $entry->attributes()->bathroom_number, $entry->attributes()->bedroom_number, $entry->attributes()->datasource_name, $entry->attributes()->guid, $entry->attributes()->img_url, $entry->attributes()->keywords, $entry->attributes()->lister_name, $entry->attributes()->listing_type, $entry->attributes()->price, $entry->attributes()->price_type, $entry->attributes()->property_type, $entry->attributes()->summary, $entry->attributes()->latitude, $entry->attributes()->longitude);
}
pg_close();
?>
Yemi
If a POI has no lat-lon, which value it has? empty string?
assuming that an empty string is returned when there is no lat-lon.
$lon = "NULL";
if($entry->attributes()->longitude != "")
$lon = "'".$entry->attributes()->longitude."'";
$lat = "NULL";
if($entry->attributes()->latitude != "")
$lat = "'".$entry->attributes()->latitude."'";
so query looks like this:
$query = "INSERT INTO nestoriaphp(title, bathroom, bedroom, datasource, guid, image, keywords, lister, listype, price, pricetype, property_type, summary, latitude, longitude) VALUES ('" . pg_escape_string($entry->attributes()->title) . "', '" . pg_escape_string($entry->attributes()->bathroom_number) . "', '" . pg_escape_string($entry->attributes()->bedroom_number) . "', '" . pg_escape_string($entry->attributes()->datasource_name) . "', '" . pg_escape_string($entry->attributes()->guid) ."', '" . pg_escape_string($entry->attributes()->img_url) . "', '" . pg_escape_string($entry->attributes()->keywords) . "', '" . pg_escape_string($entry->attributes()->lister_name) . "', '" . pg_escape_string($entry->attributes()->listing_type) . "', '" . pg_escape_string($entry->attributes()->price) . "', '" . pg_escape_string($entry->attributes()->price_type) . "', '" . pg_escape_string($entry->attributes()->property_type) ."', '" . pg_escape_string($entry->attributes()->summary) . "', " . $lat . ", " . $lon . ")";
Note that the NULL value has no '' in sql.

Categories