this is only my second question so please be gentle, I am new to PHP.
I have written a statement that queries a database, then checks a file to see if the relevant is present before creating a div to put the image into. The problem is that the output creates divs for rows that have no images.
$query = "SELECT vehicle_make_logo FROM vehicle_makes";
$result = mysql_query($query);
if(!$result) die ("Database access failed: " . mysql_error());
$rows = mysql_num_rows($result);
for ($j = 0; $j < $rows; ++$j)
{
$row = mysql_fetch_row($result);
$image = 'images/vehicleBrands/'.$row[0];
if(file_exists($image)){
echo '<div class="component"><img class="icons" src="images/vehicleBrands/'.$row[0].'"></div>';
}
}
I have tried adding an empty else-statement, but that didn't do anything.
Any help would be greatly appreciated.
Another possibility for what is happening is that your DB table has rows in there which haven an empty field for verhicle_make_logo, at which point your if statement is checking if that folder exists, which it obviously does. If you are certain this is not the case ignore the below, if it is then this might be a solution.
<?php
$query = "SELECT vehicle_make_logo FROM vehicle_makes";
$result = mysql_query($query);
if(!$result) die ("Database access failed: " . mysql_error());
$rows = mysql_num_rows($result);
for ($j = 0; $j < $rows; ++$j)
{
$row = mysql_fetch_row($result);
$image = 'images/vehicleBrands/'.$row[0];
if(!empty($row[0]) && file_exists($image)){
echo '<div class="component"><img class="icons" src="images/vehicleBrands/'.$row[0].'"></div>';
}
}
A browser can never overwrite PHP code because it never sees the PHP code. A browser will only render exactly what the PHP code passes to it. In the case where IE creates extra div tags, it could be that your HTML is malformed and IE tries to normalise it and creates extra divs in the process to close off some open tags that you may have overlooked.
Try copying the view-source code of the page and run it through a HTML validator to see.
Do not ever think for a minute that, Whatever kind of Browser you are using can actaully influence the way how PHP behaves. Because, it Can not! It may seem that way to you, because sometimes, the HTML tags/codes... outputted/echo'ed by your PHP script may be rendered in a different way, according to the browser type you are using, specially by IE, because it sucks. Now, to get back to your code, try this
<?php
$query = "SELECT vehicle_make_logo FROM vehicle_makes";
$result = mysql_query($query) or die(mysql_error());
if(mysql_num_rows($rows) > 0) {
for($j=0; $j < count($rows); ++$j){
$row = mysql_fetch_row($result);
$image = 'images/vehicleBrands/'.$row[0];
if(file_exists($image)){
echo '<div class="component">
<img class="icons" src="images/vehicleBrands/'.$row[0].'"></div>';
}
}
}else {echo 'No record found';}
Related
I have a table with par_id and columns (par1-5) 1 up to 5, but I'm trying to have my php function below to echo any number of columns
//-------------------------------------- get about ----------------------------------------------
function getAbout($option){
$div = array();
$sql_st = "undefined";
if($option == "about")
$sql_st = "SELECT * FROM `about` where par_id='1'";
// connect to database
mysql_connect($_SESSION['dbSever'],$_SESSION['dbUser'],$_SESSION['dbPass']) or die(mysql_error());
mysql_select_db($_SESSION['tblName']) or die(mysql_error());
$result = mysql_query($sql_st) or die(mysql_error()."<br/>".$sql_st);
$num_rows = mysql_num_rows($result);
while ($row = mysql_fetch_array($result) ){
// not sure what to do here
}
// disconnect
mysql_close();
return $div;
}
From your question title I'm assuming you have an ID maybe in your first column and you want to keep that from being printed. You could try something like:
$numberOfColumns = mysql_num_fields($result);
while ($row = mysql_fetch_array($result) ){
for ($i = 1; $i < $numberOfColumns; $i++){
echo $row[$i];
}
}
The $i iterator in the for loop is initiated with value of 1 because PHP handles (like many languages) arrays as zero-based, which means that the first element is referenced by $row[0] (as in this example) - by starting the loop at one and going for as many elements there are in the array, you're effectively grabbing all elements except for the first one.
A really simple one would be to have a flag like so:
$skippedFirstRow = false;
while ($row = mysql_fetch_array($result)){
if(!$skippedFirstRow) {
//do whatever you want here
}
$skippedFirstRow = true;
}
However, keep in mind that this is just a quick hack for what you want and considering your code, but it is not an elegant solution.
I've got a database that contains info on some images. The columns are id, name, description, location and visible.
I'm trying to have PHP read in the location column as an array WHERE visible=1, but it's not working. Can anyone see where I'm going wrong?
I know I should be using mysqli, before anyone points this out to me. I will do, once I've got this array syntax sorted out.
My code is below:
<?php
$con = mysql_connect("localhost", "root", "mypassword");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db("shibby",$con);
$sql = "SELECT location from gallery WHERE visible=1";
$photos= mysql_query($sql,$con);
print_r(mysql_fetch_array($result));
mysql_close($con);
$i = 0;
foreach ($photos as $photo) {
$i = 0;
if ($i < 3) {
echo '<td><center><img src="'.$photo.'.jpg"></td>';
$i++;
} elseif ($i == 3) {
echo '</tr><tr>';
$i = 0;
}
}
Undefined variable 'result' (line 12)
Change
$photos= mysql_query($sql,$con);
print_r(mysql_fetch_array($result));
with
$photos= mysql_query($sql,$con);
print_r(mysql_fetch_array($photos));
Use:
$photos= mysql_fetch_array(mysql_query($sql,$con));
And remove the line:
print_r(mysql_fetch_array($result));
And yes, use PDO or MySQLi :)
Please do NOT USE MYSQL methods on new projects!! Use mysqli or PDO (I prefer the latter as the first one is a PITA to get right)
If you really insist on correcting the existing code, fix the location retrieval as follows:
$result= mysql_query($sql,$con);
while ($row = mysql_fetch_row($result)) {
$photos[] = $row['location'];
}
mysql_fetch_array and mysql_fetch_row only get one row of the results, not the complete set, hence the need for the loop in the above
remove print_r from this line and replace this
mysql_fetch_array($photos); // you had used wrong variable
I've been mocking up a mysql & php searching page, which is functioning as expected. But, when the form is POSTed and returns no results, the <option> tags are reset, i was wondering whether i could prevent this from happening?
META: I'm aware of the deprecation of mysql_* and the posibilities of mySQL injections, this is just a quick mockup.
<?php
mysql_connect("localhost","root","") or die('Could not connect');
mysql_select_db("webhost") or die ('Could not find DB');
$output = '';
// Queries
if (isset($_POST['submit'])) {
$dsquery = $_POST['Diskspace'];
$prquery = $_POST['Price'];
$query = mysql_query("
SELECT * FROM data WHERE Diskspace BETWEEN $dsquery
AND Price BETWEEN $prquery
") ;
$count = mysql_num_rows($query);
if ($count == 0){
$output = "No such results, sorry.";
}else{
while($row = mysql_fetch_array($query)){
$diskspace = $row['Diskspace'];
$price = $row['Price'];
$host = $row['Provider'];
$output .= '<div>'.$host.' '.$diskspace.' '.$price.'</div>';
}
}
print ("$output");
}
?>
You can use AJAJ/AJAX. That's one way of retaining form data.
There are many jQuery features like .post & .ajax to do this.
You could also create an Object and store post data.
You could also use sessions.
I'm trying to update the first column in a table with new values, using something like what I've got below..
the problem is that the $userTemp variable is not incrementing in mysql but it seems to run through the elements in an array (as expected) within a php for loop. however in mysql_query this does not seem to be reflecting? I don't quite understand why as when I echo $userTemp before the mysql_query it shows that it is incrementing correctly. the query is run through the function queryMysqlPopulate($userTemp,$row[0]); but the argument does not seem to get passed to the function. however after the function call running another echo for $userTemp shows that the value has infact incremented.
like seriously?! please could someone enlighten me as to why? does session control have something to do with this?
any help is greatly appreciated!
PS. this is not the full program I've just snipped the parts that are applicable, so as not to take up too much of your time (hope that helps).
$userlogins = array('c001','d001','dj001','ed001',
'k001','nr001','ol001','pt001',
'py001','rx001','s005');
if (tableExists('mytable'))
{
$tempQuery = queryMysql("SELECT username FROM students");
$numRows = mysql_num_rows($tempQuery);
for ($j = 0 ; $j < $numRows ; ++$j)
{
$userTemp = "$userlogins[$j]";
echo $userTemp;
$row = mysql_fetch_row($tempQuery);
queryMysqlPopulate($userTemp,$row[0]);
echo $userTemp;
}
}
and the function
function queryMysqlPopulate($tempLogin, $tempRow){
$result = mysql_query("UPDATE mytable SET username='$tempLogin' WHERE username='$tempRow'") or die(mysql_error());
return $result;}
i can't answer my own question cause i#M a newbie :P
so edit insteaD:
No problems this works fine, although it's not exactly what i was looking for as it's not exactly array access, but explicitly referring to a field by it's value :(
for($i = 0; $i < $loops; ++$i)
{
queryMysql("INSERT INTO $name VALUES" .
"('hi$i', 'there', 'all', 'you', 'cats')");
}
then changing update ...set to
if (tableExists('mytable'))
{
$tempQuery = queryMysql("SELECT username FROM mytable");
$numRows = mysql_num_rows($tempQuery);
for ($j = 0 ; $j < $numRows ; ++$j)
{
$userTemp = "$userlogins[$j]";
echo $userTemp;
$row = mysql_fetch_row($tempQuery);
queryMysqlPopulate($userTemp,'hi'.$j);
echo $userTemp;
//echo $row[0];
}
//echo tableExists('none');
}
I'd still prefer to do this by array access i.e. accessing the first field of the first column by element number in the update ... set mysql query. so any help with that is greatly appreciated.
For some reason my if statements don't work as expected.
$query = "SELECT title FROM blog";
$result = mysql_query($query);
$rows = mysql_num_rows($result);
for ($j = 0; $j < $rows; ++$j)
{
if (isset($_POST['$j']))
{
$id = mysql_real_escape_string($_POST['id']);
$query = "DELETE FROM blog WHERE id='$id'";
mysql_query($query);
echo 'Deleted post.. ';
echo 'Click here';
}
else
{
echo 'Failed!';
}
}
What happens is that "Deleted post.." and the "link" get echoed the number of rows I have in my table blog. Only one row in my table gets deleted though which is what I want. One button gets pressed each time, so shouldn't it echo "Deleted post.." only one time and "Failed!" the rest of the times? Thanks =)
Note: I'm still new to programming, sorry if the question is stupid.
Note 2: I have many buttons on another page.. they are labeled by numbers '1, 2, 3' etc.
change:
$_POST['$j'] // here, due to the single quotes you're
// always testing for the literal `$j`, and not
// the value of current loop iteration.
to:
$_POST[$j]
Variables are not parsed in single quotes, you need to use double quotes. isset($_POST["$j"]
Also you are trying to delete the same record over and over in the loop, you're checking if $_POST["$j"] is set but using $_POST['id']
Try this
<?php
$query = "SELECT title FROM blog";
$result = mysql_query($query);
$rows = mysql_num_rows($result);
for ($j = 0; $j < $rows; ++$j)
{
if (isset($_POST[$j]))
{
$id = mysql_real_escape_string($_POST['id']);
$query = "DELETE FROM blog WHERE id='" .$id ."'";
mysql_query($query);
echo 'Deleted post.. ';
echo 'Click here';
}
else
{
echo 'Failed!';
}
}
?>
The problem is that you're looping through $_POST[0] to $_POST[Whatever], but you're only deleting where ID = $_POST['id']. $_POST['id'] never changes. Even though you're looping over and over, you're still trying to delete the same row for each loop
It will not work because the POST or GET or REQUEST only takes what was posted to the current page from the previous page.
You need to POST some variable to some page then only is it that you can use the $_POST['j']. You cannot use the variables in the current page inside POST
If you are posting j from some other page then I think you can use this condition instead of using like that
$j = $_POST['j'];
if(isset($_POST['j'])){
for($j = 0; $j < $rows; ++$j){
//your code
}
}
Hope this helps