PHP: If record exists display HTML, else display nothing - php

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";
}
}

Related

echo selected in html select option if value exists in array

I have been searching for days and trying everything, but i can't seem to get this working.
Question :
I have a user profile where a user can select some hobbies from a dropdown menu. This user can also edit his profile. On this edit page I would like to display a dropdown where the previously selected hobbies are selected and the rest of the available hobbies option are displayed for selection.
This is the basic code I have so far ( minus all the code that didnt work ). I hope someone can help he out.
$existing_hobby_values = array("Football", "Tennis", "Volleyball");
$sql = "select hobby from hobbies ORDER BY id ASC";
$result = mysqli_query($con, $sql);
if (mysqli_num_rows($result) > 0) {
echo "<select multiple>";
while($row = mysqli_fetch_assoc($result)) {
$interesse = $row['hobby'];
//if{$interesse = in_array($existing_hobby_values) echo "selected" inside option }
echo "<option value='$interesse'>$interesse</option>";
}
echo "</select>";
}
By the way...I know I should start using PDO instead of Mysqli, but because this project has a deadline I have to finish this before starting with learning PDO.
You can try something like
while ($row = mysqli_fetch_assoc($result)) {
$interesse = $row['hobby'];
echo '<option ';
if (in_array($interesse, $existing_hobby_values)) {
echo 'selected ';
}
echo "value='$interesse'>$interesse</option>";
}
And you should definitely do something about your tabulation.
change
echo "<option value='$interesse'>$interesse</option>";
to
echo "<option value='$interesse' ".( in_array($intresse,$existing_hobby_values) ? "SELECTED ": "" ) .">$interesse</option>";
though to be fair, #rept1d's answer should work just fine as well.

Find and display certain strings from database with if and else

The php-code below finds and displays an external url as a link from a database. Sometimes there is a phonenumber instead of an url in that row. How can I manage to echo out the phonenumber without making it to a link. I guess it will work with if and else but I'm not finding out how to display it the right way. My code below:
<?php
$ticketurl = $row ['show_external_url'];
$query = mysqli_query( $connection,"SELECT *, DATE_FORMAT(`show_date`, '%W (%d/%m/%y)') as dateFormatted
FROM nhto_gigpress_shows
WHERE `show_date` >= CURDATE()
AND WEEKDAY(nhto_gigpress_shows.show_date) >= 5
ORDER By show_date" );
$row = mysqli_fetch_array( $query ); {
echo "<a href='".$ticketurl."'>BOOK</a>";
}
?>
Try to check whether the column has any data or not and use condition
inside the while loop:
if(empty($row['url'])){
echo $row['phone'];
}
else{
echo 'BOOK';
}

mysql fetch array is not showing result

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?

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