mysql fetch array is not showing result - php

So I have been working on this code for a while. I believe I am really close. My if statement that is inside my while loop isn't showing any data in the area it's suppose to show. I know mysql is old and deprecated. I am going to change it once I figure this out.
$result = mysql_query("SELECT * FROM inventoryTable",$db);
$result2 = mysql_query("SELECT * FROM users WHERE username='$username' and sub = 'yes'",$db);
echo "<TABLE style=\"background-color: #FFFFFF; border: 10px solid A4A4A4;\">";
echo"<TR><TD>"."<B>Title</B>"."</td>";
echo"<TD>"."<B>Authors First Name</B>"."</td>";
echo"<TD>"."<B>Authors Last Name</B>"."</td>";
echo"<TD>"."<B>ISBN</B>"."</td>";
echo"<TD>"."<B>Publisher</B>"."</td>";
echo"<TD>"."<B>Course Number</B>"."</td>";
echo"<TD>"."<B>Source</B>"."</td></TR>";
while ($myrow = mysql_fetch_array($result))
{
echo "<TR><TD>".$myrow["title"]."</td>";
echo "<TD>".$myrow["authorsFirst"]."</td>";
echo"<TD>".$myrow["authorsLast"]."</td>";
echo "<TD>".$myrow["ISBN"]."</td>";
echo "<TD>".$myrow["publisher"]."</td>";
echo "<TD>".$myrow["courseNum"]."</td>";
while ($subResults = mysql_fetch_row($result2))
{
If($subResults == 'yes' )
{
echo "<td>".$myrow["source"]."</td>";
} else {
echo "<TD>"."Please subscribe to View"."</td>";
}
echo "</TABLE>";
}
}
?>
This is the part of my code that isn't showing any results.
while
while ($myrow = mysql_fetch_array($result))
{
echo "<TR><TD>".$myrow["title"]."</td>";
echo "<TD>".$myrow["authorsFirst"]."</td>";
echo"<TD>".$myrow["authorsLast"]."</td>";
echo "<TD>".$myrow["ISBN"]."</td>";
echo "<TD>".$myrow["publisher"]."</td>";
echo "<TD>".$myrow["courseNum"]."</td>";
while ($subResults = mysql_fetch_row($result2))
{
If($subResults == 'yes' )
{
echo "<td>".$myrow["source"]."</td>";
} else {
echo "<TD>"."Please subscribe to View"."</td>";
}
echo "</TABLE>";
}
}
I want my session user to be able to see the source from my inventory table if they have a yes in the sub field. If they do not have a yes in the sub field, they will see please subscribe to view. Am i doing the mysql_fetch incorrectly or is there a problem because I have 2 while loops going on at once.

you need to have "==" to compare two values, otherwise you assign the second value to the first variable:
...If($username == $subResults)...
or to use a strict comparison of type and content, use "==="
If($username === $subResults)
also I am thinking the code should be
...If($subResults ==="yes"){echo"....///desired content";}else{echo"...//alternate content";}...
and you are missing the echo statement and closing </td> in the code
"<td>".$myrow["source"];
should be
echo"<td>".$myrow["source"]."</td>";
in fact - aren't you missing the closing td's in all of the cells?

Related

How do you add a variable Count on the end of a $row->variable?

We are trying to make life easier on one of our website coded platforms.
There are 8 rows in the database, each with 1-4 at the end of them.
ie. childrensrange1, childrensrange2 and so on.
Then childrennumber1, childrennumber2...
But I don't want to be creating a ton of code, so I have started writing this. But I cannot work out how to assign the number to the end of the $row->variable.
Look at the row starting with: $childrenamountrow
I need it to query the database for $row->childrenamount1, then $row->childrenamount2 and so on.
I'm sure I have done this before, but I cannot remember how to do it.
This block should cover all 4 blocks of age ranges rather than reams of code for each set.
$countchild = 1;
while ($countchild <=4) {
echo "<tr><td><select name='childrensrange$countchild'>";
$querychildren = ("SELECT * FROM `childrensagerange` ORDER BY id");
$resultchildren = $pdo->query($querychildren);
while ($rowchildren = $resultchildren->fetch(PDO::FETCH_OBJ)) {
$childrenrangerow = "$rowchildren->agerange"."$countchild";
echo "<option value='$rowchildren->agerange'";
if ($rowchildren->agerange == $childrenrangerow) { echo " selected='selected'";}
echo ">$rowchildren->agerange</option>";
}
echo "</td><td>";
$childrenamountrow = "$row->childrenamount$countchild";
echo "<input type='text' name='childrenamount$countchild' value='$childrenamountrow'></td></tr>";
$countchild ++;
}
echo "</table>```
why not something like this ?
for (var i=1;i<=4;i++) {
$querychildren = ("SELECT childrensrange"+i+" FROM `childrensagerange` ORDER BY id");
$resultchildren = $pdo->query($querychildren);
(...)
}

PHP: If record exists display HTML, else display nothing

I'm new to PHP and I'm trying to build a small customer database.
In my database, I have a column named "suspended_state" and the value can be either 'yes' or 'no' and if it's yes, I'd like it to show Suspended, if it's no I'd like it to display Active.
Here's my code:
<?php
$result = mysqli_query($con,"SELECT suspend_state FROM tbl_company WHERE company_id='$company_id'");
while($row = mysqli_fetch_array($result));
if ($row['yes'])
echo "Suspended";
else {
echo "Active";
}
?>
However, all results come back as Active regardless of weather the column is 'yes' or 'no'
Please could someone point out where I'm going wrong?
You aren't selecting a column named 'yes'... and remove the ; as mentioned by Fred and add curly brackets as mentioned by BigScar try
while($row = mysqli_fetch_array($result)) {
if ($row['suspend_state'] == "yes") {
echo "Suspended";
} else {
echo "Active";
}
}

query to display four random data from database

This is my php code for displaying the data from the database. I am trying to display the random data from table.
<?php
include('connection.php');
$query="SELECT * FROM `banner_ad` ORDER BY RAND() LIMIT 4";
if($query_run=mysql_query($query))
{
$i=4;
$rows=mysql_fetch_array($query_run);
while($rows)
{
echo $rows['banner_no'];
echo $rows['banner_name'];
echo "<a href=\"".$rows['Banner_website_url']. "\">";
echo "<img src=\"".$rows['banner_image_url']."\" width=\"100px\" height=\"100px\">";
echo"</a>";
}
} else {
echo'<font color="red"> Query does not run. </font>';
}
?>
But the problem with this code is:
It is displaying nothing. But whenever I am trying to make a little modification in the above code like:
<?php
include('connection.php');
$query="SELECT * FROM `banner_ad` ORDER BY RAND() LIMIT 4";
if($query_run=mysql_query($query))
{
$i=4;
$rows=mysql_fetch_array($query_run);
while($rows && $i<4)
{
echo $rows['banner_no'];
echo $rows['banner_name'];
echo "<a href=\"".$rows['Banner_website_url']. "\">";
echo "<img src=\"".$rows['banner_image_url']."\" width=\"100px\" height=\"100px\">";
echo"</a>";
$i=$i-1;
}
} else {
echo'<font color="red"> Query does not run. </font>';
}
?>
It is displaying the same single output 4 times. But It has to display the four different output. So, Please tell me where is the bug ... And how am i suppose to display four different random output.
Any help will be appreciated
Thanks in advance
Your first Query is fine, but the while is wrong:
Just look at what you did here:
$rows=mysql_fetch_array($query_run);
while($rows)
{
echo $rows['banner_no'];
echo $rows['banner_name'];
echo "<a href=\"".$rows['Banner_website_url']. "\">";
echo "<img src=\"".$rows['banner_image_url']."\" width=\"100px\" height=\"100px\">";
echo"</a>";
}
this will end in an "infinite Loop" cause $rows will always be set.
What you need is:
while($rows=mysql_fetch_array($query_run))
this will cause myslq_fetch_array to return a new line everytime the while condition is checked. And if all 4 rows are returned, $rows will be false and the loop is stoped.
And to be complete:
In your second Example you are exactly iterating 4 times over the SAME row, you just fetched one time by calling myslq_fetch_array.
A possible solution to that will be to fetch the row again INSIDE the while-loop:
$i=4;
while ($i>0){
$rows = mysql_fetch_array(...);
$i--;
}
However you should prefer the first solution, because then you dont need to take care that the result count matches your iterator variable.
sidenode: Call it $row without the 's', because you always just getting ONE row back.
Try constructing while loop like so
while(($rows=mysql_fetch_array($query_run)) !== false)
Using ORDER BY RAND() is not the best practice because the random value must be generated for every single row. Better way would be to randomly generate primary keys (e.g. ID) in PHP and then select according to them.
$random_id = rand(1,4);
$query="SELECT * FROM `banner_ad` WHERE id = $random_id";
Will select exactly one random row. Similar whould be selecting multiple rows using IN statement.
More info you can find here.
$query_run=mysql_query($query);
if(!$query_run)
{
echo'<span style="color:red">Query did not run.</span>';//font tag is ancient
}
else
{
if(mysql_num_rows($query_run) > 0)
{
while($row = mysql_fetch_assoc($query_run))
{
echo $rows['banner_no'];
echo $rows['banner_name'];
// more...
}
}
}

Is it possible to Query a Mysql database from a field selected from dropdown menu populated from a Query in php

Hello i am new to php and i have tried to find a piece of code that i can use to complete the task i need, i currently have a page with a form set out to view the criteria of a course. also i have a dropdown menu which currently holds all the course codes for the modules i have stored in a database. my problem is when i select a course code i wish to populate the fields in my form to show all the information about the course selected. The code i am trying to get to work is as follows:
<?php
session_start();
?>
<? include ("dbcon.php") ?>
<?php
if(!isset($_GET['coursecode'])){
$Var ='%';
}
else
{
if($_GET['coursecode'] == "ALL"){
$Var = '%';
} else {
$Var = $_GET['coursecode'];
}
}
echo "<form action=\"newq4.php\" method=\"GET\">
<table border=0 cellpadding=5 align=left><tr><td><b>Coursecode</b><br>";
$res=mysql_query("SELECT * FROM module GROUP BY mId");
if(mysql_num_rows($res)==0){
echo "there is no data in table..";
} else
{
echo "<select name=\"coursecode\" id=\"coursecode\"><option value=\"ALL\"> ALL </option>";
for($i=0;$i<mysql_num_rows($res);$i++)
{
$row=mysql_fetch_assoc($res);
echo"<option value=$row[coursecode]";
if($Var==$row[coursecode])
echo " selected";
echo ">$row[coursecode]</option>";
}
echo "</select>";
}
echo "</td><td align=\"left\"><input type=\"submit\" value=\"SELECT\" />
</td></tr></table></form><br>";
$query = "SELECT * FROM module WHERE coursecode LIKE '$Var' ";
$result = mysql_query($query) or die("Error: " . mysql_error());
if(mysql_num_rows($result) == 0){
echo("No modules match your currently selected coursecode. Please try another coursecode!");
} ELSE {
Coursecode: echo $row['coursecode'];
Module: echo $row['mName'];
echo $row['mCredits'];
echo $row['TotalContactHours'];
echo $row['mdescription'];
echo $row['Syllabus'];
}
?>
however i can only seem to get the last entry from my database any help to fix this problem or a better way of coding this so it works would be grateful
Thanks
The main error is in your final query, you're not actually fetching anything from the query, so you're just displaying the LAST row you fetched in the first query.
Some tips:
1) Don't use a for() loop to fetch results from a query result. While loops are far more concise:
$result = mysql_query(...) or die(mysql_error());
while($row = mysql_fetch_assoc($result)) {
...
}
2) Add another one of these while loops to your final query, since it's just being executed, but not fetched.
For me i would use some javascript(NOTE: i prefer jQuery)
An easy technique would be to do this(going on the assumption that when creating the drop downs, your record also contains the description):
Apart from creating your dropdown options like this <option value="...">data</option>, you could add some additional attributes like so:
echo '<option value="'.$row['coursecode'].'" data-desc="'.$row['description'].'">.....</option>
Now you have all your drop down options, next is the javascript part
Let's assume you have included jQuery onto your page; and let's also assume that the description of any selected course is to be displayed in a <div> called description like so:
<div id="course-description"> </div>
<!--style it how you wish -->
With your javascript you could then do this:
$(function(){
$("#id-of-course-drop-down").change(function(){
var desc = $(this).children("option").filter("selected").attr("data-des");
//now you have your description text
$("#course-description").html(desc);
//display the description of the course
}
});
Hope this helps you, even a little
Have fun!
NOTE: At least this is more optimal than having to use AJAX to fecch the description on selection of the option :)

How do I get only ONE link to change dynamically using PHP?

Sorry, I'm not sure how to really word my question. Here it goes.
If you go to my page http://www.eveo.org/stack/view.php you will notice on the right hand side there are links that read "restore" and "delete". If it says restore, the value for the "deleted" table in the database is "y".
The problem: When I click on a link, all of them change, not just the one. What I need to do is when I click on "delete" or "restore" on any of them, only that row will delete and restore and only will that rows link update, with all the others staying the same. The value in the database has to change from "y" to "n" or vice versa depending on the link.
The code that currently changes my link for all of them is:
echo "<td><a href='view.php?'>";
$y="$row[deleted]";
$x="$row[id]";
if ($y == 'n'){
mysql_query("UPDATE inventory SET deleted = 'y' WHERE id='$row[id]'");
echo "delete";
}
else if ($y == 'y'){
mysql_query("UPDATE inventory SET deleted = 'n' WHERE id='$row[id]'");
echo "restore";
}
echo"</a></td>";
I've been trying to solve this for hours, and it's not working.
Requirements: It has to use URL rewriting, so I can't do this change thing with javascript or something, personally I would have, but these are my professors requirements.
Source code:
VIEW.PHP
<?php { ?>
<table border="0" cellpadding="0" cellspacing="0" id="table">
<thead>
<tr>
<th>ID</th>
<th>NAME</th>
<th>MANUFACTURER</th>
<th>MODEL</th>
<th>DESCRIPTION</th>
<th>ON HAND</th>
<th>REORDER</th>
<th>COST</th>
<th>PRICE</th>
<th>SALE</th>
<th>DISCOUNT</th>
<th>DELETE</th>
</tr>
</thead>
<tbody>
<?php } ?>
<?php
// while($r = mysql_fetch_array($resultDeleted))
// {
// echo $r[0];
// }
?>
<?php while($row = mysql_fetch_array($result)) {
echo "<tr>";
echo "<td>$row[id]</td>";
echo "<td>$row[name]</td>";
echo "<td>$row[manufac]</td>";
echo "<td>$row[model]</td>";
echo "<td>$row[descrip]</td>";
echo "<td>$row[onhand]</td>";
echo "<td>$row[reorder]</td>";
echo "<td>$row[cost]</td>";
echo "<td>$row[price]</td>";
echo "<td>$row[sale]</td>";
echo "<td>$row[discont]</td>";
echo "<td><a href='view.php?'>";
$y=$row[deleted];
$x=$row[id];
if ($y == 'n'){
mysql_query("UPDATE inventory SET deleted = 'y' WHERE id='$row[id]'");
echo "delete";
}
else if ($y == 'y'){
mysql_query("UPDATE inventory SET deleted = 'n' WHERE id='$row[id]'");
echo "restore";
}
echo"</a></td>";
echo "</tr>";
} ?>
<?php { ?>
</tbody>
</table>
<?php } ?>
It looks like you are trying to get a $_GET variable using the code:
$y="$row[deleted]";
$x="$row[id]";
This is never going to work. First of all you don't need to add double quotes around your variables. Second the correct syntax for getting the $_GET variables is:
$delete = $_GET['delete'];
$id = $_GET['id'];
As you can see I have given your variable names better descriptive names.
Second, when you are just adding those variables to a query you will have a huge SQL injection hole in your application:
mysql_query("UPDATE inventory SET deleted = 'y' WHERE id='$id'");
What if I was a hacker I would add an id of: 1' or 1=1, which would result in the following query:
UPDATE inventory SET deleted = 'y' WHERE id='1' OR 1=1
And suddenly I set the deleted status of all records in the table. I could even get into others tables using this attack in do whatever I want.
So you should always use mysql_real_escape_string():
$id = mysql_real_escape_string($_GET['id']);
mysql_query("UPDATE inventory SET deleted = 'y' WHERE id='$id'");
So what you will get is the following:
$delete = mysql_real_escape_string($_GET['delete']);
$id = mysql_real_escape_string($_GET['id']);
mysql_query("UPDATE inventory SET deleted = '$delete' WHERE id='$id'");
Another thing is that you don't need to keep opening and closing the PHP tags. Only if you want to add some HTML.
Next:
instead of echoing all that stuff simply use HEREDOC:
So instead of doing:
echo "<tr>";
echo "<td>$row[id]</td>";
echo "<td>$row[name]</td>";
echo "<td>$row[manufac]</td>";
echo "<td>$row[model]</td>";
echo "<td>$row[descrip]</td>";
echo "<td>$row[onhand]</td>";
echo "<td>$row[reorder]</td>";
echo "<td>$row[cost]</td>";
echo "<td>$row[price]</td>";
echo "<td>$row[sale]</td>";
echo "<td>$row[discont]</td>";
echo "<td><a href='view.php?'>";
You can simply do:
echo <<<HTML
<tr>
<td>{$row['id']}</td>
<td>{$row['name']}</td>
etc
FOOBAR;
As you can see it need quotes to get an array element.
After that you should build your links:
$delete = 'n';
if ($row['deleted'] == 'n') {
$delete = 'y';
}
echo 'delete';
As a general note:
ALWAYS ENABLE FULL ERROR REPORTING ON DEV ENVIRONMENT so you can see what the f*&k is going on / wrong. So place this at the top of your scripts:
error_reporting(E_ALL | E_STRICT);
ini_set('display_errors', 1);
What you want will not work like that. Your code changes your database entries upon each refresh. To illustrate, if you will keep refreshing your page, the links will change from deleted to restored and vice versa indefinitely.
What you need to do is take those two update clausules out of the loop, give each link an id. Something along the lines of
if ($y == 'n'){
echo "<a href='view.php?link_id=$row[id]&case=delete'>delete</a>";
}
else if ($y == 'y'){
echo "<a href='view.php?link_id=$row[id]&case=restore'>restore</a>";
}
Then somewhere above the loop you would to the actual update.
if(!empty($_GET['link_id'])) {
if($_GET['case'] == 'restore') {
// udpate
} else {
// update
}
}
The other way would be to use a form for this. Then you would just catch the post request and do the same thing.
if($_SERVER['REQUEST_METHOD'] == 'POST') {
// do stuff
}
or
if(!empty($_POST)) {
// do stuff
}
You need to pass the id to the query, maybe something like this:
<?php while($row = mysql_fetch_array($result)) {
if($row['deleted']=='y'){$status='restore';}else{$status='delete';}
echo "<tr>";
echo "<td>{$row['id']}</td>";
echo "<td>{$row['name']}</td>";
echo "<td>{$row['manufac']}</td>";
...
echo "<td><a href='view.php?id={$row['id']}&do=$status'>".ucfirst($status)."</a></td>";
echo "</tr>";
?>
Then have the script receive a request to alter the values, something like this would go at the top of your script:
<?php
if(isset($_GET['id']) && is_numeric($_GET['id']) && isset($_GET['do'])){
$set=null;
$id=(int)$_GET['id'];
if($_GET['do']=='delete'){$set='n';}
if($_GET['do']=='restore'){$set='y';}
if($set != null){
mysql_query("UPDATE inventory SET deleted = '$set' WHERE id='$id'");
}
}
?>

Categories