foreach() not "for eaching" items in array PHP - php

if I do this, it works:
$data_array2 = mysql_query("SELECT pic_loc FROM pictures WHERE user_id = '".$id."'");
$cell_pictures = mysql_fetch_array($data_array2);
foreach($cell_pictures as $pics_being_deleted)
{
unlink($pics_being_deleted);
}
Problem being is that the above code is nested meaning it runs a new MySQL query for each time it runs the unlink function so I made the below code to make it not do that:
$the_pics_raw_2 = array();
$data_array2 = mysql_query("SELECT pic_loc FROM pictures WHERE user_id = '".$id."'");
while($cell_pictures = mysql_fetch_array($data_array2))
{
$the_pics_raw = $cell_pictures['pic_loc'];
$the_pics_raw_2[] = $the_pics_raw;
}
$the_pics_raw_3 .= " \"../../". implode("\" , \"../../" ,$the_pics_raw_2)."\"";
$the_pics = array($the_pics_raw_3);
foreach($the_pics as $pics_being_deleted)
{
unlink($pics_being_deleted);
}
I get this error in return:
Warning: unlink( "../../users/biondizzle/photos/pic_3387677.png" , "../../users/biondizzle/photos/pic_1581185.png") [function.unlink]: No such file or directory
it's obviously not going to find the "../../users/biondizzle/photos/pic_3387677.png" , "../../users/biondizzle/photos/pic_1581185.png" directory because that's 2 separate directories running at the same time so the foreach() isn't "foreaching".
Any way to get the unlink() to run separately for each directory i have listed in the array, I thought I would get it to work by adding the commas and quotations with the implode()?
Thanks a bunch, hope I explained it well enough
-Mike

I think this is what you want to do:
while($cell_pictures = mysql_fetch_array($data_array2)) {
$the_pics_raw = $cell_pictures['pic_loc'];
$the_pics[] = "../../" . $the_pics_raw;
}
foreach($the_pics as $pics_being_deleted) {
unlink($pics_being_deleted);
}
You will notice I have removed the $the_pics_raw_3 .= " \"../../". implode("\" , \"../../" ,$the_pics_raw_2)."\""; line as it was converting the array into a string, which was making it impossible to then foreach over.

Use this code:
$the_pics_raw = array();
$data_array2 = mysql_query("SELECT pic_loc FROM pictures WHERE user_id = '".$id."'");
while($cell_pictures = mysql_fetch_array($data_array2))
{
array_push($the_pics_raw,"../../".$cell_pictures['pic_loc']);
}
foreach($the_pics as $the_pics_raw)
{
unlink($pics_being_deleted);
}

Related

How to use string variable that have special character "#" in select query statement mysql php

<?php
include('dbLink2.php');
$quizqr = $_GET['quizQR'];
$recordsID1 = $_GET['recordsID1'];
$recordsID2 = $_GET['recordsID2'];
$m_array1=array();
$m_array=array();
$sql = "SELECT quizQR, recordsID FROM `registertestactivity` WHERE (quizQR = '$quizqr' OR recordsID = '$recordsID1' OR recordsID = '$recordsID2') LIMIT 1";
$result = #mysqli_query($link, $sql) or die();
if (#mysqli_affected_rows($link) > 0) {
while($row = #mysqli_fetch_assoc($result))
{
$m_array[]=$row;
}
} else {
$m_array1 += ["quizQR" => "NoRecords"];
$m_array1 += ["recordsID" => "NoRecords"];
$m_array[0] = $m_array1;
}
echo json_encode($m_array);
#mysqli_free_result($result);
#mysqli_close($link);
?>
Can someone help me out, i have tried the mysqli_real_escape_string and it still doesnt work :(
The $quizqr value has a '#' character in the string and this is the error msg that pops when the ajax call this php:
Because you have a # in the URL you're dealing with a URL Fragment which means that everything past the # is not available in the query string. PHP offers a flag, PHP_URL_FRAGMENT for its parse_url() function which can help you get what you need from the string.
Here is one example using the URL you provided:
$fragment = parse_url($url, PHP_URL_FRAGMENT);
echo $fragment;
$fragmentSection = explode('&', $fragment);
print_r($fragmentSection);
foreach($fragmentSection AS $section) {
if(0 != strpos($section, '=')) {
$sectionParts = explode('=', $section);
$queryParts[$sectionParts[0]] = $sectionParts[1];
}
}
print_r($queryParts);
This ultimately returns two array members which could then be used in your query:
Array
(
[recordsID1] => records_001
[recordsID2] => records_002
)
The best thing to do would be to write a function to which you pass the URL to return the elements you need.
Keep in mind that this is not fool-proof. If the URL is in a different format then what I have done here will have to be modified to work as you would like it to.
Additionally you have been given some warnings and guidance in the comments you should follow to keep your code safe and efficient, so I will not repeat them here.

My foreach query is not working and i am getting an error

I am getting a Warning: Invalid argument supplied for foreach() message with the code below.
The idea is that I have 2 tables, one is a stock table which has a large amount of data imported to it daily, and is linked. The other table (although not a parent table) is a list of sites, they have a common field called StockName.
The idea of this code, is that, when run, it is supposed to loop through all of the sites in the site table, get the StockName field, then use that to lookup the latest value in the stockdetails table, and then update the Site table with up to date info. Thats the theory, here is the code:
$rstmp = CustomQuery("SELECT * FROM Sites");
$datatmp = db_fetch_array($rstmp);
$SitePk = $datatmp['SitePk'];
foreach ($SitePk as $item)
{
echo $item."<BR>";
$rstmp2 = CustomQuery("SELECT * FROM ImportStockDetails where StockName='".$datatmp['StockName']."' ORDER BY `Date` DESC LIMIT 1");
$datatmp2 = db_fetch_array($rstmp2);
$latestdate = $rstmp2["LastStockDate"];
$latestcylpropane = $rstmp2["PropaneCylinders"];
$latestcylbutane = $rstmp2["ButaneCylinders"];
$latestbulkpropane = $rstmp2["BulkPropane"];
$latestbulkbutane = $rstmp2["BulkButane"];
$latesttotal = $latestcylpropane+$latestcylbutane+$latestbulkpropane+$latestbulkbutane;
$latestratio = $latesttotal/$datatmp['SiteMaxCapacity'];
global $dal;
$dal_table = $dal->Table("Sites");
$dal_table->Param["SitePk"] = $item;
$dal_table->Value["LatestPropaneCylinderStock"] = $latestcylpropane;
$dal_table->Value["LatestButaneCylinderStock"] = $latestcylbutane;
$dal_table->Value["LatestBulkPropaneStock"] = $latestbulkpropane;
$dal_table->Value["LatestBulkButaneStock"] = $latestbulkbutane;
$dal_table->Value["LatestTotalStock"] = $latesttotal;
$dal_table->Value["`Stock/LimitRatio`"] = $latestratio;
$dal_table->Value["LastStockDate"] = $latestdate;
$dal_table->Update();
}
You are getting the warning because $SitePk is not an array, it is just a value. You should try with $datatmp as db_fetch_array($rstmp); return array which is stored in $datatmp.

PHP: Fastest way to loop through a array / stringbuiler or something else

We have a PHP script that loops through many XML / CSV files from different websites. Right now we manage to build a good XML / CSV parser script.
The PHP script we wrote is looping though some BIG XML or CSV files. In these XML or CVS files contains Barcodes from different products.
Right now before the script starts I fill an array with the Product ID + Barcode from the MySQL like this:
function Barcodes_Array() {
$sql = "SELECT ProductId, Barcode FROM Products WHERE (Barcode <> '') ";
$res = mysql_query($sql);
while ($rijen = mysql_fetch_assoc($res)) {
$GLOBALS['arrBarcodes'][] = $rijen;
}
}
Each time we loop through the XML (or CSV) files we have to check if the Barcode exists in the array and return the Product ID.
For searching in the function:
$ProductId = SearchBarcodeProduct($EanNr, 'Barcode');
And yet the function:
function SearchBarcodeProduct($elem, $field)
{
$top = sizeof($GLOBALS['arrBarcodes']) - 1;
$bottom = 0;
$ProductId = 0;
while($bottom <= $top)
{
if($GLOBALS['arrBarcodes'][$bottom][$field] == $elem) {
return $GLOBALS['arrBarcodes'][$bottom]['ProductId'];
}
else {
if (is_array($GLOBALS['arrBarcodes'][$bottom][$field])) {
if (in_multiarray($elem, ($GLOBALS['arrBarcodes'][$bottom][$field]))) {
return $GLOBALS['arrBarcodes'][$bottom]['ProductId'];
}
}
}
$bottom++;
}
return $ProductId;
}
We fill in the array because it took forever each time we ask the MySQL Products Table.
My Question is now:
It still takes a VERY long time each time looping through the array of the barcodes. Is there a faster way for any other solutions maybe a different way then a array?
Can someone help please i am working like weeks on this stupid :) thing!
Why do you need 2 functions?
Try just one
function itemBarcode($id) {
$id = intval($id);
$sql = "SELECT ProductId, Barcode FROM Products WHERE ProductId = $id Barcode <> '') ";
$res = mysql_query($sql);
if ($row = mysql_fetch_assoc($res)) {
return $row['barcode'];
} else {
return 0;
}
}
Update if you need to search by barcode you can create another function:
function itemProduct($barcode) {
$sql = "SELECT ProductId, Barcode FROM Products WHERE Barcode = $barcode ";
$res = mysql_query($sql);
if ($row = mysql_fetch_assoc($res)) {
return $row['ProductId'];
} else {
return 0;
}
}
Sounds like you are missing an index on your Barcode column in your database.. A single row lookup using a presumably unique single indexed column should be blisteringly fast.
CREATE INDEX Barcode_Index ON Products (Barcode)
Then simply:
SELECT ProductId FROM Products WHERE Barcode = *INPUT*
You could also make the index UNIQUE if you NULL the Barcode where they currently = '' if there are more than one of these.
Another option is keying the array you have with the Barcode:
while ($rijen = mysql_fetch_assoc($res)) {
$GLOBALS['arrBarcodes'][$rijen['Barcode']] = $rijen;
}
or even just:
while ($rijen = mysql_fetch_assoc($res)) {
$GLOBALS['arrBarcodes'][$rijen['Barcode']] = $rijen['ProductId'];
}
Then you can do a straight look up:
$ProductId = isset($GLOBALS['arrBarcodes'][$Barcode])
?$GLOBALS['arrBarcodes'][$Barcode]['ProductId']
:0;
or:
$ProductId = isset($GLOBALS['arrBarcodes'][$Barcode])
?$GLOBALS['arrBarcodes'][$Barcode]
:0;
N.B Please read the warnings in the comments about use of $GLOBALS and mysql_query.
If you need it, store the barcodes array in an object or variable instead.
PDO is pretty handy, and I think it can also key your returned array for you on fetch.

Rename images in database to md5 but keep extensions

As the title says I'm wanting to change the image names stored in a database to md5 but keep the image extension, I had a go with the code below but it failed (probably due to the fact I haven't a clue what I'm doing) ...any ideas on how I could achieve my goal?
function get_file_extension($file_name) {
return substr(strrchr($file_name,'.'),1);
}
$query = "SELECT img FROM post";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)) {
$name = substr($row['img'], -4, 4);
$ext = get_file_extension($row['img']);
$notmd5 = $row['img'];
$md5img = md5($name).'.'.$ext;
$q = "UPDATE post SET img='$md5img' WHERE img='{$notmd5}'";
$r = mysql_query($q) or die(mysql_error());
}
..........................................................
Update
Answer:
Rename files in dir/folder and db names at same time:
function get_file_extension($file_name) {
return substr(strrchr($file_name,'.'),1);
}
//path to directory to scan
$directory = "thumbs/";
$directory2 = "md5/";
//get all image files with a .jpg extension.
$images = glob($directory . "*.*");
//print each file name
foreach($images as $image)
{
$imag = str_replace($directory, '', $image);
$ex = get_file_extension($imag);
$new = md5($imag).'.'.$ex;
rename($image, $directory2.$new);
$q = "UPDATE post SET img='$new' WHERE img='{$imag}'";
$r = mysql_query($q) or die(mysql_error());
}
When I originally asked my question I had already renamed the images in dir/folder but I had a backup of them so mixed the to jobs together and got my goal :)
First off, I'd recommend a batch update like this just be done with pure SQL, especially if the business logic is as simple as this, it can all be done natively in MySQL for sure.
Anyway.., one thing that pops out is the substr call to get the $name of the file, it's hardcoded to get only 4 characters and it's actually getting the extension not the name.
Try this instead:
$ext = get_file_extension($row['img']); // get ext first
// use length of $row['img'] - length of file extension to extract name
substr($row['img'], 0, strlen($row['img']) - strlen($ext) - 1);
Just do it in pure SQL:
UPDATE post SET img = CONCAT_WS('.',
MD5(TRIM(TRAILING CONCAT('.', SUBSTRING_INDEX(img, '.', -1)) FROM img)),
SUBSTRING_INDEX(img, '.', -1)
)

PHP Function Dependent on presence of MySQL data entry

I code a weekly trivia program for one of my clients through facebook.
I have a bit of code commented out where we display the winner when we need to. Currently I just remove the comment brackets and update when it's time to display. I'm trying to make this so someone non-savvy can handle updates so I've moved my code into an include:
winner-display.php
I am trying to write a function so that if the winner is set in MySQL, it includes the file in-line, and if the winner field is empty in the database, it does not.
Here is what I have so far, any ideas?
<?php
$target="3";
$myDataID = mysql_query("SELECT topic_desc from ref_links WHERE ref_categories_id = '$target' AND topic_name = '$property'", $connectID);
while ($row = mysql_fetch_row($myDataID)) {
$displayvalue = $row ['topic_desc'];
}
if ( $displayvalue != 'null') {
include('../includes/winner-display.php');
} else {
}
?>
Ok, thanks for helping guys, got it to work as:
<?php
$target="3";
$myDataID = mysql_query("SELECT topic_desc from ref_links WHERE ref_categories_id = '$target' AND topic_name = '$property'", $connectID);
while ($row = mysql_fetch_row($myDataID)) {
foreach ($row as $field) {
if ($field != null) {
include('../includes/winner-display.php');
}
}
}
?>
You can definitely put an include within an if. That solution that you posted should work as you would like it to, although I personally would have used a function instead of a completely separate file to include (although that is personal preference).
All you have to do to make it work is remove the quotes around 'null'.
<?php
$target="3";
$myDataID = mysql_query("SELECT topic_desc from ref_links WHERE ref_categories_id = $target' AND topic_name = '$property'", $connectID);
while ($row = mysql_fetch_row($myDataID)) {
$displayvalue = $row ['topic_desc'];
}
if ( $displayvalue != null) {
include('../includes/winner-display.php');
}
?>
Keep in mind that if your query returns more than one row, only the last row will be retained. I don't know if that is the functionality you want (in which case, there are some changes you could make, just ask me to edit my answer), but I didn't change that.

Categories