Here is my code for the function
function multiple_delete($checkbox, $table = 0, $url = 0, $picture1 = 0, $picture2 = 0, $picture3 = 0){
echo $count = count($checkbox);
for( $j=0;$j<$count;$j++)
{
$delete_id = $checkbox[$j];
$query = "SELECT * FROM $table WHERE id = '$delete_id'";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
if( $picture1 !== 0 && $picture2 !== 0 && $picture3 !== 0)
{
$pic_1 = $picture1;
$pic_2 = $picture2;
$pic_3 = $picture3;
unlink($pic_1);
unlink($pic_2);
unlink($pic_3);
continue;
}
if( $picture1 !== 0 && $picture2 !== 0 && $picture3 == 0 )
{
$pic_1 = $picture1;
$pic_2 = $picture2;
unlink($pic_1);
unlink($pic_2);
continue;
}
}
for($i=0;$i<$count;$i++) {
$del_id = $checkbox[$i];
$sql = "DELETE FROM $table WHERE id='$del_id'";
$result_delete_data = mysql_query($sql);
}
alert('Deleted Successfully');
redirect_url($url);
return true;
}
My Problem is when i call the function using the following code.
#multiple_delete($_POST['checkbox'], 'news', 'news.php', '$row[\'pic_title\']', '$row[\'pic_brief\']', '$row[\'pic_detail\']');
the three array variables $row['pic_title'], $row['pic_brief'], $row['pic_detail'] , does not parse as the value in the function in first for loop, instead it just print the string and hence is not able to fetch the value stored in the database. for example
in the first if condition i have defined 3 variables,
$pic_1 = $picture1;
$pic_2 = $picture2;
$pic_3 = $picture3;
$picture1, $picture2, and $picture3 holds the value that i declared in the function , now when i do something like this echo $pic_1 = $picture1; it prints $row['pic_title'] the exact value which i declared in the function instead of parsing the value which is actually upload/news/title/pic_title1.jpg i tried testing it like this, instead of declaring the value in the defined function i actually just changed the value of the three variables to
$pic_1 = $row['pic_title'];
$pic_2 = $row['pic_brief'];
$pic_3 = $row['pic_detail'];
this works very fine without any problem. why is that variable $picture1 which holds the value $row['pic_title']; refuses to parse it and force it to just print the string while if i change it manually it works? where i am going wrong?
apart from the last three parameters i dont have any problem parsing the first three parameters it works perfectly fine i have tested it in many ways. the only problem i am facing is of the last three parameters
Edit : i tried double quotes, single quotes, and single quotes with double quote with the combination of concatenation operator. without quotes. nothing works.
P.S : thanks in advance
Try this:
function multiple_delete($checkbox, $table, $url, $picture1, $picture2, $picture3){
echo $count = count($checkbox);
for($j=0; $j<$count; $j++)
{
$delete_id = $checkbox[$j];
$query = "SELECT * FROM $table WHERE id = '$delete_id'";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
$pic1 = $row[$picture1];
$pic2 = $row[$picture2];
$pic3 = $row[$picture3];
if(!empty($pic1) && !empty($pic2) && !empty($pic3))
{
unlink($pic1);
unlink($pic2);
unlink($pic3);
}
else if(!empty($pic1) && !empty($pic2))
{
unlink($pic1);
unlink($pic2);
}
$sql = "DELETE FROM $table WHERE id='$delete_id'";
$result_delete_data = mysql_query($sql);
}
// this is javascript, not php
// alert('Deleted Successfully');
redirect_url($url);
return true;
}
Call the function like this:
multiple_delete($_POST['checkbox_name'], 'table_name', 'redirect_url', 'column_name_pic_1', 'column_name_pic_2', 'column_name_pic_3');
get rid of the apostrophes around your variable names in the function call, ie try
, $row[\'pic_title\'],
instead of
, '$row[\'pic_title\']',
I got the solution for this problem. in case it can benefit anyone here is the link to the solution.
How do i parse the the value from a string in the function call?
Related
I need to update a table with more then 12000 row using php Codeigniter and a txt file.. reading the file and the foreach loop are fine but when updating line by line it takes like 30 mins, I guess the problem is I'm searching by name because I have no id in the txt file...
Here is my code:
controller:
$fn = fopen($this->upload->data('full_path'),"r");
$update = true;
while(! feof($fn) && $update) {
$pieces = explode("|", fgets($fn));
if(sizeof($pieces) == 9 && is_numeric(trim($pieces[1]))) {
$update = $this->model_products->update3s($pieces);
}
}
fclose($fn);
Model:
public function update3s($product) {
if ($product) {
$product[2] = trim(str_replace("'","''",$product[2]));
$product[1] = trim($product[1]);
$product[6] = trim($product[6]);
$product[3] = trim($product[3]);
$sql = "UPDATE products set qty = $product[3], price_vente = $product[6] where (name = '$product[2]')";
echo $sql.'<br>';
$update = $query = $this->db->query($sql);
return $update;
}
return false;
}
You can use transaction and add index for column name in database table.
$fn = fopen($this->upload->data('full_path'),"r");
$update = true;
$updatedCount = 0;
while(! feof($fn) && $update) {
$pieces = explode("|", fgets($fn));
if(sizeof($pieces) == 9 && is_numeric(trim($pieces[1]))) {
if ($updatedCount == 0) {
$databaseInstance->beginTransaction();
}
$update = $this->model_products->update3s($pieces);
++$updatedCount;
if ($updatedCount > 500) { //in one transaction update 500 rows
$databaseInstance->commit();
$updatedCount = 0;
}
}
}
if ($updatedCount > 0) { // if we have not commited transaction
$databaseInstance->commit();
}
fclose($fn);
Some tips
Add index to field name
Use prepared statements
Disable the MySQL forgeign key check Read more
writing sql function can do that even in much lesser time .
using feature like :
REPLACE()
cursors
SPLIT_STRING(custom)
in a mysql user defined function
CREATE FUNCTION update3s(hole_file_content LONGTEXT) RETURNS Boolean
BEGIN
-----Your implementation(same logic in sql ) ------
END
then coll it just by if it is CI 3
$this->db->call_function('update3s', file_get_contents($this->upload->data('full_path')));
else
$this->db->query("select update3s(".file_get_contents($this->upload->data('full_path')).")");
I have a problem with creating a query through a function (all others variables works correctly) I have a function that doesn't print variables correctly (exactly $NomiFarmacie and $day)
//The problem is present in this function
function Cicla($Periodo, $FarmacieRiordinate, $Query) {
global $tabella_calendario, $count; //them works
foreach ($Periodo as $giorno) {
$day = $giorno->format("Y-m-d");
$NomiFarmacie = addslashes($FarmacieRiordinate[$count % count($FarmacieRiordinate)]);
echo $NomiFarmacie; echo $day; //Both are correct
print_r($Query); //Queries are not completed correctly. OUTPUT Below
$count++;
}
}
$FarmacieRiordinate = $_POST['elementi'];
$DataIniziale = $_POST['data1'];
$DataFinale = $_POST['data2'];
$Query = ("UPDATE $tabella_calendario SET Farmacia='$NomiFarmacie' WHERE Data='$day'");
Cicla(CalcolaPeriodo($DataIniziale, $DataFinale), $FarmacieRiordinate, $Query);
A PORTION OF OUTPUT print_r($Query)
UPDATE calendario SET Farmacia='Array' WHERE Data='1546297200'
UPDATE calendario SET Farmacia='Array' WHERE Data='1546297200'
UPDATE calendario SET Farmacia='Array' WHERE Data='1546297200'
UPDATE calendario SET Farmacia='Array' WHERE Data='1546297200'
The problem is your $Query already be combined as string BEFORE passed into your function.
You can use vsprintf in this case.
function Cicla($Periodo, $FarmacieRiordinate, $Query) {
global $tabella_calendario, $count; //them works
foreach ($Periodo as $giorno) {
$day = $giorno->format("Y-m-d");
$NomiFarmacie = addslashes($FarmacieRiordinate[$count % count($FarmacieRiordinate)]);
echo $NomiFarmacie; echo $day; //Both are correct
$realQuery = vsprintf($Query, array($NomiFarmacie, $day));
print_r($realQuery); //Queries are not completed correctly. OUTPUT Below
$count++;
}
}
$FarmacieRiordinate = $_POST['elementi'];
$DataIniziale = $_POST['data1'];
$DataFinale = $_POST['data2'];
$Query = ("UPDATE $tabella_calendario SET Farmacia='%s' WHERE Data='%s'");
Cicla(CalcolaPeriodo($DataIniziale, $DataFinale), $FarmacieRiordinate, $Query);
You can read more about vsprintf here:
http://php.net/manual/en/function.vsprintf.php
.
Below is my PHP code. I'm tying to retrieve values from a database and round them to the nearest 10 (upwards only). All the values in the database in this column are integers.
<?PHP
#$Teach_ID = $_POST['txtteachID'];
#$Class_ID = $_POST['txtclass'];
#$BookingDate = $_POST['txtbookingdate'];
#$BookingPeriod = $_POST['txtperiod'];
require_once('../BookingSystem/DBconnect.php');
$capacity = 'SELECT ClassSize FROM classes WHERE ClassID = 1';
$result = $dbh->query($capacity);
$result = (int)$result;
function ceiling($number, $significance = 1)
{
return ( is_numeric($number) && is_numeric($significance) ) ? (ceil($number/$significance)*$significance) : false;
}
}
if ($result->num_rows > 0) {
echo ceiling($result, 10);
}
?>
Error Description
Am I missing something obvious?
You need to loop through your $result variable, which is a mysqli_result object, to get its different entries.
Use mysqli_fetch_assoc to get the values, which will end in something like this :
$capacity = 'SELECT ClassSize FROM classes WHERE ClassID = 1';
$result = $dbh->query($capacity);
function ceiling($number, $significance = 1)
{
return ( is_numeric($number) && is_numeric($significance) ) ? (ceil($number/$significance)*$significance) : false;
}
}
while ($row = $result->fetch_assoc()) {
// if ($result->num_rows > 0) { /* I think this condition is not needed anymore */
$value = intval($row['ClassSize'], 10); // will convert the string from database to an int in base 10
echo ceiling($value, 10); /* I suppose you wanted to use the ClassSize key since it's the one you query */
// }
}
You can't do this $result = (int)$result;. You have to irritate over each row and then extract the data.
I need help...I'm trying to retrieve data from sql table and compare it with if statement for certain IDs and updating a variable accordinly. But it seems that the variable is not updating for some reason. Below is my code..
$query2 = "SELECT prcID, tProDone
FROM vw_fdwTracker
WHERE AgrNo = '$agreement'";
$result2= sqlsrv_query($conn, $query2);
if ($result2==false){
die( "<pre>".print_r(sqlsrv_errors(), true));
}
$current = 0;
while($id= sqlsrv_fetch_array($result2, SQLSRV_FETCH_ASSOC)){
//echo $id['prcID']." ". $id['tProDone'].'<br>';
if(($id['prcID']===3) && ($id['tProDone']===TRUE)){
$current=12.5;
}elseif(($id['prcID']===4) && ($id['tProDone']===TRUE)){
$current=25;
}elseif(($id['prcID']===5) && ($id['tProDone']===TRUE)){
$current=37.5;
}elseif(($id['prcID']===9) && ($id['tProDone']===TRUE)){
$current=50;
}elseif(($id['prcID']===10) && ($id['tProDone']===TRUE)){
$current=62.5;
}elseif(($id['prcID']===14) && ($id['tProDone']===TRUE)){
$current=75;
}elseif(($id['prcID']===12) && ($id['tProDone']===TRUE)){
$current=87.5;
}elseif(($id['prcID']===17) && ($id['tProDone']===TRUE)){
$current=100;
}else{
$current=0;
}
}
Try saving to an array so you know if it's working or not:
function getCurrentArr($agreement,$conn)
{
$query = "SELECT prcID, tProDone FROM vw_fdwTracker WHERE AgrNo = '$agreement'";
$result = sqlsrv_query($conn, $query);
if(!$result){
die( "<pre>".print_r(sqlsrv_errors(), true));
}
return $result;
}
function getCurrVal($value)
{
$return[3] = 12.5;
$return[4] = 25;
$return[5] = 37.5;
$return[9] = 50;
$return[10] = 62.5;
$return[14] = 75;
$return[12] = 87.5;
$return[17] = 100;
return (isset($return[$value]))? $return[$value] : 0;
}
$curr = array();
$result = getCurrentArr($agreement,$conn);
while($id= sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC)){
if(!$id['tProDone']) {
$curr[] = 0;
continue;
}
$curr[] = getCurrVal($id['prcID']);
}
// See what this gets you for an array
// If what is in this array is what you expect, then
// make the $curr array the variable, but you will overwrite
// every time it loops, just keep that in mind
print_r($curr);
You don't need to define $current variable value at starting of code just do your code like below it will also work on loop
$id['prcID']=3;
$id['tProDone']=false;
if(($id['prcID']==3) && ($id['tProDone']==true)){
$current=12.5;
}else{
$current=0;
}
echo $current;
I currently have a php page that grabs information from a database and produces HTML with data attributes that are filled in by from the MySQL query. The database is going to be used to search, with many different options for searches.
What I need help with is knowing a way so to organize how the many variables are handled. It's a really big mess of code, and even with all the comments I put it gives me a headache trying to figure out how to add another variable to the search.
All the variables, except for the LIMIT to which row and how many results, are optional. So if someone leaves everything except that blank, I still want it to function as well as if they meticulously filled in all the fields.
Here's what I have, with 6 variables.
<?php
$product_size = "(".$_GET['size']." BETWEEN productsizeDOWN AND productsizeUP)"; // This code sets the variable to input into the MySQL string based on the URL
$product_size_check = $_GET['size']; // the _checks check are used to see if the value is or isn't empty using if statements below
$manufacturer = $_GET['manufacturer'];
$product_manufacterer_check = $_GET['manufacturer']; // _check
$product_invisible = "(hideproduct = '".$_GET['invisible']."')"; // Checks if product is hidden
$product_invisible_check = $_GET['invisible']; // _check
$product_instock_check = $_GET['instock']; // _check
$product_limit0 = $_GET['startat']; // This is the first number after LIMIT; the row to start in.
$product_limit1 = $_GET['results']; // This is how many results to load.
$manufacturer_array = explode(",", $manufacturer); // The manufacturer comes in as "Nike,Addidas,Rebok" and is turned into an array
$manufacturer_imploded = implode("' OR productmanufacturer = '", $manufacturer_array); // Puts it back together with "OR productmanufacturer =" between each name.
$product_manufacterer = ("(productmanufacturer = '".$manufacturer_imploded."')"); // formats it so it can be directly inserted into MySQL string with a WHERE in front.
if($product_invisible_check == ""){
$product_invisible = "";
}else{$where = "WHERE ";}; //Useless code that I havn't deleted that I tried to use when I searched the entire database
if($product_size_check == ""){
$product_size = "";
}else{$where = "WHERE ";};
if($product_manufacterer_check == ""){
$product_manufacterer = "";
}else{$where = "WHERE ";};
if($product_instock_check == "N"){
$product_instock = "(stockstatus <= '0' AND donotallowbackorders = 'Y') AND "; // Checks if product is in stock (Allowing backordering OR stock >1)
$where = "WHERE ";
}
elseif($product_instock_check == "Y") {
$product_instock = "(stockstatus > '0' OR donotallowbackorders = 'N') AND ";
$where = "WHERE ";
}
else {
$product_instock = "";
};
$sql="Select * FROM ioa7pd_Products WHERE ".$product_instock.$product_size."AND".$product_manufacterer_and.$product_manufacterer."".$product_invisible." LIMIT ".$product_limit0.", ".$product_limit1; // The end result of it all.
echo $sql;
?>
When the URL is
test.php?size=5&manufacturer=Nike,Addidas,Rebok&invisible=N&instock=Y&startat=0&results=30
the resulting SQL query is
Select * FROM ioa7pd_Products WHERE (stockstatus > '0' OR donotallowbackorders = 'N') AND (5 BETWEEN productsizeDOWN AND productsizeUP)AND(productmanufacturer = 'Nike' OR productmanufacturer = 'Addidas' OR productmanufacturer = 'Rebok')(hideproduct = 'N') LIMIT 0, 30
But I plan to add more options to the search.
My main question is simply: What way can I organize this to make it simple to add more variables? Tiered if statements?
Travesty has been helping me with my code and has really been great in organizing it.
Here is the current code. It needs to be secure to prevent injection.
// Database connection
$con = mysql_connect("[CENSORED]","[CENSORED]","[CENSORED]")
or die("Could not connect: " . mysql_error());
mysql_select_db("[CENSORED]") or die('Could not select database');
// Begin organization of URL variables into MYSQL Query
$get_size = $_GET['size'];
$get_manufacturer = $_GET['manufacturer'];
$get_invisible = $_GET['invisible'];
$get_instock = $_GET['instock'];
$get_sex = $_GET['sex'];
$get_startat = $_GET['startat'];
$get_results = $_GET['results'];
if ($get_size != ""){
$all_selectors[] = "(".$get_size." BETWEEN productsizeDOWN AND productsizeUP)"; // Add to array if size is not blank.
};
if ($get_manufacturer != ""){
$manufacturer_exploded = explode(",", $get_manufacturer);
$manufacturer_imploded = implode("' OR productmanufacturer = '", $manufacturer_exploded);
$all_selectors[] = ("(productmanufacturer = '".$manufacturer_imploded."')");
};
if ($get_invisible != ""){
$all_selectors[] = "(hideproduct = '".$get_invisible."')";
};
if($get_instock == "N" or $get_instock == "n"){
$all_selectors[] = "(stockstatus <= '0' AND donotallowbackorders = 'Y')";
}elseif($get_instock == "Y" or $get_instock == "y") {
$all_selectors[] = "(stockstatus > '0' OR donotallowbackorders = 'N')";
};
if ($get_startat != "" or $get_results != ""){
$number_results = "LIMIT ".$get_startat.", ".$get_results;
} else {
$number_results = "LIMIT 0, 15";
};
// All variables are now in an array, except "startat" and "results"
$all_selectors0 = "WHERE ".implode(" AND ", $all_selectors);
// Create SQL query
$sql="Select * FROM sadsads_Products ".$all_selectors0." ".$number_results;
I would do something more like this. It's not tested and probably not 100% complete...you may need to do some further customization, particularly with adding more special cases to the switch statement, but this will make adding more variables much easier:
REMOVED OLD EXAMPLE, SEE UPDATED EXAMPLE BELOW
One key thing to note is that you aren't sanitizing your database inputs. Your code is vulnerable to SQL injection. My example above helps to solve that, but this code isn't fully tested, so you should ensure that all user input is sanitized before using it in any query.
If your field names don't match up with your MySQL columns (which it looks like they don't), then you can fix them with an associative array:
$columns = array(
// [form field] => [mysql column]
'size' => 'product_size',
'manufacturer' => 'product_manufacturer',
'invisible' => 'hideproduct'
// ...
);
And then in your switch statement, do something more like this:
$whereClause[] = "{$columns[$key]} = '{$value}'";
FINAL UPDATE:
DOCUMENTED SAMPLE - has plenty of comments and extra stuff to make it work on Codepad
EXACT WORKING CODE - you should be able to copy and paste this (and add your DB credentials) and it should work:
$con = mysqli_connect("[CENSORED]", "[CENSORED]", "[CENSORED]") or die("Could not connect: ". mysqli_error());
mysqli_select_db("[CENSORED]") or die("Could not select database");
$columns = array(
'size' => 'product_size',
'manufacturer' => 'product_manufacturer',
'invisible' => 'hideproduct'
);
$whereClause = array();
$limit = array("startat" => 0, "results" => 15);
foreach ($_GET as $key=>$value) {
$key = mysqli_real_escape_string($key);
if (is_array($value)) {
for ($i = 0; $i < count($value); $i++) {
$value[$i] = mysqli_real_escape_string($value[$i]);
}
} else {
$value = mysqli_real_escape_string($value);
}
switch ($key) {
case 'size':
$whereClause[] = "({$value} BETWEEN productsizeDOWN AND productsizeUP)";
break;
case 'startat':
case 'results':
$limit[$key] = $value;
break;
case 'instock':
$whereClause[] = "(stockstatus ". ($value == 'N' ? "<=" : ">") ." '0' ". ($value == 'N' ? "AND" : "OR") ." donotallowbackorders = '". ($value == 'N' ? "Y" : "N") ."')";
break;
default: {
if (is_array($value)) {
$whereClause[] = "{$columns[$key]} IN ('". implode("', '", $value) ."')";
} else {
$whereClause[] = "{$columns[$key]} = '{$value}'";
}
}
}
}
$sql = "SELECT * FROM ioa7pd_Products". (empty($whereClause) ? "" : " WHERE ". implode(" AND ", $whereClause)) ." LIMIT {$limit['startat']}, {$limit['results']}";
echo $sql;
after
else {
$product_instock = "";
};
do:
$limit = '';
if( !empty($product_limit0) && !empty($product_limit1) )
$limit = " LIMIT $product_limit0, $product_limit1";
$sql="Select * FROM ioa7pd_Products WHERE ".$product_instock.$product_size."AND".$product_manufacterer_and.$product_manufacterer."".$product_invisible." $limit"; // The end result of it all.
echo $sql;
If you have separate params in $_GET, you would have to traverse with multiple if statements. you can pass the params as an array into $_GET, with numeric keys, that would help a bunch.