why the while loop runs once? - php

the following code is only running once , while the number of times it should run is 4 , any help ?
PHP::
<?php
header("Content-Type: application/json");
require_once("config.php");
if(isset($_GET["m"])) {
$dirname = "images/main/";
$arr = array();
$conn = new mysqli(HOST, USERNAME, PASSWORD, DATABASE);
if(!$conn) {
echo "Error connecting to database";
exit();
}
if($stmt = $conn->prepare("SELECT name_ FROM projects")) {
$stmt->execute();
$stmt->bind_result($n);
//$stmt->store_result();
$result = $stmt->get_result();
if($result->num_rows == 0) {
echo "No Projects";
$stmt->close();
$conn->close();
exit();
}else {
while ($row = $result->fetch_assoc()) {
$dirname = $dirname . $row["name_"] . "/";
$images = glob($dirname . "*.*", GLOB_BRACE);
foreach($images as $image) {
echo $row["name_"];
echo$result->num_rows; // returns 4 !!!!
$image = base64_encode($image);
//$arr[] = $image;
array_push($arr, $image);
$image = "";
}
}
echo json_encode($arr); // returns 1 json row oonly
}
}
$stmt->close();
$conn->close();
exit();
}
?>
num rows return 4 so why it runs or loops for one time only ?
I am trying to get images from images folder to echo it back
FIX::
according to jhilgeman's answer I added this part to the end of foreach:
$dirname = "images/main/";

If I had to guess, I'd say that it's looping correctly, but the problem is this line:
$dirname = $dirname . $row["name_"] . "/";
Each time you loop, you're APPENDING the $row["name"] value to whatever $dirname is. So let's say that you get 4 rows back like this:
name
----
houses
boats
computers
animals
At the beginning of the loop, let's say $dirname is just "/images/". So the first loop would change $dirname to be:
/images/houses/
Then the second loop would change it to be:
/images/houses/boats/
The third loop would then make it:
/images/houses/boats/computers/
And finally the fourth loop:
/images/houses/boats/computers/animals/
So unless you're expecting the $dirname to be appended that way, you probably want to instead REPLACE $dirname instead of appending to it each time.
Try this instead for your loop:
while ($row = $result->fetch_assoc()) {
$images_dirname = $dirname . $row["name_"] . "/";
$images = glob($images_dirname . "*.*", GLOB_BRACE);
foreach($images as $image) {
...etc...
}
}

Related

Variables inside while loop

I have following code, I try to style output with CSS, but I have small problem, my code show all database entries, which is OK, but when I remove comment from WHILE loop, and comment echo, its showing only first row of entries from database.how can I do same thing and show multiple results from database by use variables in While Loop?:
<?php
error_reporting(0);
require 'connect.php';
$search = $_POST['search'];
//$checkout = $_POST['checkout'];
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM area where destination='{$search}'";
$result = mysqli_query($conn, $sql);
if($count = $result->num_rows) {
echo '<p>', $count, '</p><br><br>';
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo $row['destination'],' ',$row['place'], $row['tosee'], '<br>';
/$destination =$row["destination"];
//$place =$row["place"];
/$destination =$row["destination"];
//$place =$row["place"];
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>
and inside my HTML file:
location: <?php echo $destination; ?>
places: <?php echo $place ; ?>
views: <?php echo $tosee; ?>
Do this...
$out .= $row['destination'].' '.$row['place'].' '.$row['tosee']. '<br>';
Then you can use the $out variable anywhere else...
Even for these...
$destination .= $row["destination"];
$place .= $row["place"];
Since well....are in the while loop
I found a few small errors, you had a ',' instead of a '.' to concatenate a variable.
if($count = $result->num_rows) {
echo '<p>' . $count . '</p><br><br>';
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo $row['destination'].' '.$row['place'].' '.$row['tosee']. '<br>';
//$destination =$row["destination"];
//$place =$row["place"];
//$destination =$row["destination"];
//$place =$row["place"];
}
}
and for php comments it is: //

Bulk image insert from multiple folders wiith images in folder wont work

hi Guys my bulk image insert script for mysql isnt working.i cant figure out why.
I have the upload Script in root directory and the images in a folder called img in this folder a folders named by category with images in it so insert into mysql.but he says me everytime "There were no matching files to insert into the database." dont know why paths should be okay i think.
Here is the script guys
$connect = mysql_connect($server,$dbuser,$dbpass);
mysql_select_db($dbname,$connect);
$dirs = array_filter(glob('img/*'), 'is_dir');
foreach ($dirs as $dir) {
$path = "img/" . $dir . "/";
$files = array_map('mysql_real_escape_string', array_filter(glob("{$path}*.*"), 'is_file'));
if (empty($files)) {
echo "There were no matching files to insert into the database.";
} else {
$insertValues = array();
foreach ($files as $file) {
$data = getimagesize($file);
$width = $data[0];
$height = $data[1];
$insertValues[] = "('Titel', {$dir}, '{$file}', '$width', '$height')";
}
$query = "INSERT INTO `gbpics` (`gbpictitel`, `gbpiccat`, `gbpicurl`, `gbpicwidth`, `gbpicheight`) VALUES " . implode(', ', $insertValues);
if (!mysql_query($query)) {
echo "There was a problem inserting the data.";
trigger_error("Query failed: $query<br />Error: " . mysql_error());
} else {
echo "The data was inserted successfully.";
}
}
}
?>
I think
$path = "img/" . $dir . "/";
is duplicating the img/ part.
Probably should be
$path = $dir . "/";

Can you sum or add in a variable while inserting data?

I would like to ask if it is possible to add together with a variable, I've manage it to echo it and it worked.
But is it possible in a insert statement?
Here is my code!
<?php
include('admin/db/database_configuration.php');
$sql = "SELECT * FROM tblalbums";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
$row = $result->fetch_assoc();
$wow = $row['album_id'];
echo ($row['album_id']+1);
} else {
echo "0 results";
}
$conn->close();
?>
<?php
include('admin/db/database_configuration.php');
if (isset($_FILES["userfile"]) && !empty($_FILES["userfile"])) {
$image = $_FILES['userfile']['tmp_name'];
$imageSize = $_FILES['userfile']['size'];
$imageType = $_FILES['userfile']['type'];
// $job_desc = $_POST['desc'];
$imageName = $_FILES['userfile']['name'];
$len = count($image);
$path = "jobs/";
for ($i = 0; $i < $len; $i++) {
if (isset($imageName[$i]) && $imageName[$i] !== NULL) {
if(move_uploaded_file($image[$i], $path.$imageName[$i])) {
// $result = $conn->query("INSERT INTO tbljoba ( job_img_size, job_img_type, job_desc, job_img) VALUES ('$imageSize[$i]', '$imageType[$i]', '$job_desc', '$imageName[$i]')");
$sql = "INSERT INTO `tblphotos` ( imageName, imageSize, imageType, album_id) VALUES ('$imageName[$i]','$imageSize[$i]', '$imageType[$i]', '$wow');";
// echo"<script>alert('Image upload successfully!');location.href='employer_contact_us.php';</script>";
if ($conn->query($sql) === TRUE) {
echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
}
}
}
$conn->close();
?>
As you can see above the variable $wow is album_id in the database, and i've echo it so the last number in the database + 1.
So i've got the INSERT statement and you can see there I've put the variable $wow. So how can add or sum up + 1 in adding values?
Thank you!
remove single quoted lines ' ' from $wow in VALUES then +1
$wow=1 without single quoted lines so that it will not read as a string to the database
You can find and read information about AUTO_INCREMENT for fields in MySQL
May be this can help you.

How to use single for each loop for multiple array to update single sql statement

I want to use single for each for two array.
array 1 : has path of images (path is dynamic as per user need)
array 2: has values description field of each image (description is dynamic as per user need)
I want to insert both array in sql table using only one sql statement.
<?php $sql="INSERT INTO posts(title,description,category,createdBy,pictureURL,CreatedAt) VALUE ('$title',
'$description','$category','$creatdby','Admin/PostImages/$finalpath',now());";
$result = mysqli_query($conn,$sql);
if($result)
{
$upload_directory = 'PostImages/';
$field_values_array = $_REQUEST['desc'];
$x=0;
foreach($field_values_array as $value1){
foreach ( $_FILES['photo']['name'] AS $key => $value ){
//Move file to server directory
if(move_uploaded_file($_FILES["photo"]["tmp_name"][$x], $upload_directory . $_FILES["photo"]["name"][$x])){
$finalpath=$upload_directory . $_FILES["photo"]["name"][$x];
}
if (isset($_SESSION['p_id'])){
$p_id = $_SESSION["p_id"];
}
$sql1="INSERT INTO `postimages`(`p_id`,`description`, `img_path`) VALUES ('$p_id','$value1','$finalpath')";
$result1 = mysqli_query($conn,$sql1);
$x++;
}
}
header("Location: uploadpost_test.php");
}
else
{
echo "Error: " . $sql . "<br>" . $conn->error;
} ?>
I refactor and clean up your codes. Try this.
if(isset($_SESSION['p_id']))
{
$p_id = $_SESSION["p_id"];
}
$values = '';
$next = ',';
$len = count($field_values_array);
foreach($field_values_array as $x=>$value1)
{
if(move_uploaded_file($_FILES["photo"]["tmp_name"][$x], $upload_directory.$_FILES["photo"]["tmp_name"][$x]))
{
$tmp_name = $_FILES["photo"]["tmp_name"][$x];
$finalpath = $upload_directory.$tmp_name;
$next = $x >= $len-1 ? '' : $next;
$values .= "VALUES('$p_id','$value1','$finalpath')".$next;
}
}
$sql1="INSERT INTO `postimages`(`p_id`,`description`, `img_path`) $values";
$result1 = mysqli_query($conn,$sql1);

Search and erase db rows with file checker

Hi I am trying to get a file path from the embed field, use that path to see if a file exists in that path. If the file dose not exist then delete that entry. I am running a game site and the script that downloads the game file skipped a few so its like finding a needle in a 4000 entry db haystack. Any help is appreciated. Here is my code:
<?php
if(isset($_POST['clean'])) {
$query = "SELECT * FROM games WHERE embed";
$result = mysql_query($query) or die ("no query");
$result_array_path = array();
while($row = mysql_fetch_assoc($result))
{
$result_array_path = $row;
}
$count = mysql_num_rows($result);
for($counter=0;$counter<$count;$counter++){
if (file_exists($result_array_path[$counter])){
}else{
mysql_query("DELETE FROM games WHERE embed".$result_array_path[$counter]);
echo $result_array_path[$counter]." ";
}
}
}
?>
--------------EDIT-------------
I Updated the code to BUT it decides to delete my entire database instead of deleting the missing game entries. Here is the revised code:
<?php
if(isset($_POST['clean'])) {
$query = "SELECT * FROM games WHERE embed NOT LIKE '%mochiads.com%'";
$result = mysql_query($query) or die ("no query");
$result_array_path = array();
while($row = mysql_fetch_assoc($result))
{
$result_array_path[] = $row['embed'];
}
foreach($result_array_path as $path) {
if(!file_exists($path)) {
mysql_query("DELETE FROM games WHERE embed = '" . $path . "'");
echo $path." | ";
}
}
}
?>
-----------EDIT--------------
I debugged the program so it works now. Had to add a "$_SERVER['DOCUMENT_ROOT']" to the program. Here is the finished program
<?php
if(isset($_POST['clean'])) {
$query = "SELECT * FROM games WHERE embed NOT LIKE '%mochiads.com%'";
$result = mysql_query($query) or die ("no query");
$result_array_path = array();
while($row = mysql_fetch_assoc($result))
{
$result_array_path[] = $row['embed'];
}
foreach($result_array_path as $path) {
$rel_path = str_replace('http://www.flamegame.net', '', $path);
$rel_path = str_replace('http://flamegame.net', '', $rel_path);
$rel_path = str_replace('%20', ' ', $rel_path);
if(! file_exists($_SERVER['DOCUMENT_ROOT'] . $rel_path)) {
mysql_query("DELETE FROM games WHERE embed = '" . $path . "'");
echo $rel_path." | ";
}
}
}
?>
Thanks For all of the help Especially Gargron.
For those who are wondering this program is for my website:
http://www.FlameGame.net
I see one typo that might be your problem:
$result_array_path = array();
while($row = mysql_fetch_assoc($result))
{
// You want to append the row to the results array
// instead of replacing the array each time, so []
$result_array_path[] = $row['embed'];
// That's assuming the table field containing the path is "embed"
}
And instead of using mysql_num_rows you could instead iterate through the items in $result_array_path like this:
foreach($result_array_path as $path) {
if(! file_exists($path)) {
// Delete
// You missed a = in the query too
mysql_query("DELETE FROM games WHERE embed = '" . $path . "'");
}
}
That should make it work.

Categories