Cannot echo out the right result. PHP/MySQL - php

I want to make a code that check if a value in an exact column is equal to an 'neodobren', and if there is such value in the column to echo out the button 'Add Member' and Yes for each value. I've tried to do the following and it is not echoing the Yes:
I have the following MySQL table content:
UID Name Phone Email SchoolGymnasium City Password Status
1 neodobren
2 neodobren
and I have the following PHP code inside the HTML index page:
$con = mysql_connect("localhost","****","****");
mysql_query("SET NAMES UTF8");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("***", $con);
include("../../sql.php");
session_start();
$zaqvki = mysql_query("SELECT * FROM Directors WHERE Status='neodobren' LIMIT 1");
if(mysql_num_rows($zaqvki) > 0) {
echo '<div align="right">Add Member</div><br>';
// display data in table
// loop through results of database query, displaying them in the table
while($row = mysql_fetch_array($zaqvki)) { //$zaqvki was $result, before a guy comment me this...
echo "Yes";
} }
else {
echo "No";
}
It is showing only the button add member, and not showing the Yes, which must be echo-ed.

Use mysql_fetch_assoc to get an associative array and make a comparison on each row of a certain column:
while($row = mysql_fetch_assoc($result))
{
if($row['Status'] === 'neodobren')
echo "Yes";
else
echo "No";
}

Related

Use PHP to generate from an existing database for each row a new specific HTML that i already made

First I'm hitting on a wall here and I really could use your help. I coded the database so I have it all up and working plus all the data inside. I worked the HTML and the CSS media print query and I have it how I want it to look exactly. All I have to do now is:
for every row of the mysql select table I have to fill every specific input form
of the html page I made and print it
Can someone give me a hint of how I can do that?
Assuming you want to connect to your database and simply fetch the id you can do the following.
Ensure you change my_host, my_user, my-password, my_databse,my_tablewith your configuration settings. Then if you want to fetch anything else thanid` just change it to the column name you are looking for.
Be aware we are using PHP here.
// Open Connection
$con = #mysqli_connect('my_host', 'my_user', 'my-password', 'my_databse');
if (!$con) {
echo "Error: " . mysqli_connect_error();
exit();
}
// Some Query
$sql = 'SELECT * FROM my_table';
$query = mysqli_query($con, $sql);
while ($row = mysqli_fetch_array($query))
{
echo $row['id'];
}
// Close connection
mysqli_close ($con);
Check this link to get a in-depth explanation.
You can do this with two pages. One page gives you the overview and the other page gives you a print preview of your invoice.
The overview:
// DB select stuff here
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
echo "<tr>\n";
echo " <td>".htmlspecialchars($row['what'])."</td>\n";
echo " <td>".htmlspecialchars($row['ever'])."</td>\n";
echo " <td>Detail</td>\n";
echo "</tr>\n";
}
The detail page:
$sql = 'SELECT your, columns FROM tab WHERE id = ?';
$stmt = $db->prepare($sql);
$stmt->execute(array($_GET['id']));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$row) {
echo "There is no data for the given Id\n";
return;
}
echo "What: ".htmlspecialchars($row['what'])."<br />\n";
echo "Ever: ".htmlspecialchars($row['ever'])."<br />\n";

Select data from MySQL DB based on the URL example (www.example.co.uk/essex.php)

I am very new to php and I am looking to create dynamic pages.
Basically If a person lands on www.example.co.uk/essex.php I would like to be able to add something like <h1>Company In <?php echo $row['County']; ?> so that it would show
Company In Essex when Live and save time if I need to duplicate the page for another county or town.
So far I have setup a database in phpmyadmin
Picture of Table
My code so far to grab the table is;
$dbconnect = mysqli_connect("HOST", "USER", "PASSWORD", "DB");
if(mysqli_connect_errno()) {
echo "Connection Failed:".mysqli_connect_error();
exit;
}
$count_sql="SELECT * FROM areas";
$count_query=mysqli_query($dbconnect, $count_sql);
$count_rs=mysqli_fetch_assoc($count_query);
and then on www.example.co.uk/essex.php
<?php
do {
echo $count_rs['County'];
} while ($count_rs=mysqli_fetch_assoc($count_query))
?>
But where I have gone wrong is it pulls all the data from the table for County where I only wish it to pull the county of Essex.
Please forgive me for explaining this badly.
UPDATE -
$row = url2content();
extract($row);
function url2content($url = NULL){
if(is_null($url)){
if(isset($_SERVER["REQUEST_URI"]) && $_SERVER["REQUEST_URI"]){
$url = $_SERVER["REQUEST_URI"];
}elseif(isset($_SERVER["PATH_INFO"]) && $_SERVER["PATH_INFO"]){
$url = $_SERVER["PATH_INFO"];
}
if (substr($url,0,1) == '/'){
$url = substr($url,1);
}
}
if (DEBUG_MODE){
echo ('URL requested: "'.$url.'"<br>');
}
function get_towns($county){
$query = sprintf("select townName from " . AREAS_TABLE . " where countyName = '%s' order by rand() LIMIT 0,24" ,mysql_real_escape_string($county));
$res = mysql_query($query);
if(!$res){
printf("Unable to query ".AREAS_TABLE." table: %s \n", mysql_error());
}
$html="";
while($row = mysql_fetch_assoc($res)){
$html.="<li>".stripslashes($row["townName"])."</li>\n";
}
return $html;
}}
You have to use WHERE clause in your query in order to select a specific country from your db
SELECT * from table WHERE felid_country=$count_rs['County'];
You can use strpos() to match the County (eg.essex) with url $_SERVER['REQUEST_URI'] (eg.www.example.co.uk/essex.php) in your case.
Just like this
<?php
do {
if(strpos($_SERVER['REQUEST_URI'],$count_rs['County'])!=false)
echo $count_rs['County'];
} while ($count_rs=mysqli_fetch_assoc($count_query))

How can I SELECT field FROM table WHERE id=variable?

I have a variable of the logged in user ($steamid) that I need to use to select and echo specific fields from the database. I am using the following code, but it is working incorrectly. All database info is correct, the tables, columns, and variables are not misspelled. Not sure what I'm doing wrong.
<?php
$con=mysqli_connect("private","private","private","private");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT `bananas` FROM `es_player` WHERE `steamid` = '$steamID'";
if ($result=mysqli_query($con,$sql))
{
// Get field information for all fields
while ($fieldinfo=mysqli_fetch_field($result))
{
printf("bananas: %n",$fieldinfo->bananas);
}
// Free result set
mysqli_free_result($result);
}
mysqli_close($con);
?>
No errors are shown, it simply returns "bananas:" with nothing after it. I feel like I didn't to it correctly, does anyone know what I might've done wrong? Here is a screenshot of my database table so you know what it looks like http://puu.sh/gCY3d/983b738458.png.
Try this:
$query = Mysqli_Query($con, "SELECT * FROM `es_player` WHERE `steamid`='$steamID'") or die(mysql_error());
if( ! mysqli_num_rows($query) )
{
echo 'No results found.';
}
else
{
$bananas_array = mysqli_fetch_assoc($query);
$bananas = $bananas_array['bananas'];
echo 'Number of bananas: '. $bananas;
}
If this doesn't work, there is a problem with STEAM_ID format. You could try triming the IDs to be JUST a number, and add the STEAM_x:x: to it later.

Echo statement in PHP not executing in a specific manner

I'm having a problem with some specific PHP code that I've been working on for a few days. It's meant to be a reporting code where I can input a day and a month and it will list the total sales of that particular day.
But, I can't seem to make the last statement whereby, if there are no values(there are no data) in the query, it will display 'No Sales on this particular day'. Here's the code I've been working on. But the last echo statement is not executing. Any ideas?
<?php
session_start();
if ((isset($_SESSION["admin"])) ){
$day=#$_POST['day'];
$month=#$_POST['month'];
echo "<center><h2>Sales report on " .$day. "." .$month. ".2013</h2></center>";
echo "<center><table style='border:2px solid black;' align=center width=600>";
echo "<tr><th colspan=12><center><h2>Sales Report</h2><hr size='2' color='black' /></center></th></tr>";
echo " <th width=400> Amount Collected</th>";
?>
<br>
<?php
$x = 1; //counter
//open a connection to a MySQL server using function mysql_connect
//returns a MySQL link identifier on success, or FALSE on failure.
$conn= mysql_connect("localhost","root","");
if (!$conn)
die ("Connection error: ".mysql_error());
else {
//select a MySQL database
//returns TRUE on success or FALSE on failurue.
$db=mysql_select_db("cqfos");
if(!$db)
die ("DB not found: ".mysql_error());
else {
//put query in a variable $query
$query= "select ROUND(sum(orderdetails.tprice),2)
from orders JOIN orderdetails ON orders.orderID = orderdetails.orderID WHERE DAY(orders.date) = '$day' AND MONTH(orders.date) = '$month'";
$result=mysql_query($query);
if(!$result)
die ("Invalid query: ".mysql_error());
//if record exists
else {
//fetch a result row as both associative array and numeric array
if(mysql_num_rows($result)== 1){
while ($row=mysql_fetch_array($result,MYSQL_BOTH)){
echo "<tr>";
echo "<td align='center'>RM ".$row[0]."</td></tr>";
$x++; //increase the counter
}
}
else {
echo "<tr><th colspan=12>No sales made.</td></tr>";}
}
}
}
echo"</table></center>";
?>
Several problems here
your HTML table syntax is incorrect, and your using an old sql library - and it dose not look like your SQL syntax is right... try this code (not tested as I don't have your data)
<?php
session_start();
if ((isset($_SESSION["admin"])) ){
echo '<div style="margin:auto; textalign:center;">';
echo "<h2>Sales report on " .$_POST['day']. "." .$_POST['month']. ".2013</h2>";
echo "<h2>Sales Report</h2>"
echo "<table style='border:2px solid black;' align=center width=600>";
echo "<tr><th width=400> Amount Collected</th></tr>";
?>
<br>
<?php
$conn = new mysqli("localhost","root","","cqfos");///use mysqli, not mysql : mysql is depricated
if ($conn->mysqli)
exit ("Connection error: ".$conn->errno ." : " $conn->error);
else {
//put query in a variable $query
$eDay = $conn->mysql_real_escape_string($_POST['day']);//escape these to protect the database
$eMonth = $conn->mysql_real_escape_string($_POST['month']);;//escape these to protect the database
//your column name is probably not a rounded value, replaced it with * (return all columns)
$query= "select * from orders JOIN orderdetails ON orders.orderID = orderdetails.orderID WHERE DAY(orders.date) = '"
.$eDay."' AND MONTH(orders.date) = '".$eMonth."'";
$result=$con->query($query);
if($conn->errno)
exit ("Invalid query: ".$conn->errno ." : " $conn->error);
//if record exists
else {
$numericArray = $result->fetch_array(MYSQLI_NUM); //fetch a result row as numeric array
$associativeArray = $result->fetch_array(MYSQLI_ASSOC); //fetch as an associtive array this is not used, just an example
$bothArray = $result->fetch_array(MYSQL_BOTH); //both associtive and numeric this is not used, just an example
}
if(!empty($numericArray))
{
foreach ($numericArray as $value) {
echo "<tr><td>RM ".$value[0]."</td><tr>";//is there more then 1 col? if not you should consider an html list
}
} else {
echo "<tr><td>No sales made</td><tr>";
}
echo"</table></center>";
}
?>
Your SQL (likely) returns more than only one row, so change the line I mentioned before to this:
if(mysql_num_rows($result)>0){
Just letting you know your code is vulnerable to SQLi because you have not sanitized $day and $month. Also please consider using PDO.
If you haven't already - Try running the SQL statement into PHPMyAdmin and see where it outputs the error (if there is one), else it will output the data.*
*Manually inputting the day/month substituting for the variables.

Selecting a row based on multiple column values?

I'm working on a little system for SecondLife which involves a bit of heavy use of databases & I've run into a problem I can't for the life of me solve.
I'm trying to run a query that selects an entire row based on two different column values. I'm using the $_GET[''] call to identify which details I need, and then I need to pull all the data from the entire row and echo it onto a blank page.
Now, I got it to work at first, but it was pulling ALL the rows created by a UUID and echoing them, when I only needed a specific. Then I tried to get it to work with a second identifier (which is a column called 'field' for the purpose of testing), and that's pretty much where I lost it.
I just need to select one row that has two exact values, and I need it to be draconian so it only selects a row that has both and not just one of the two.
Any ideas?
Script enclosed (don't mind the mess or the commented out code which I kept for reference; I am going to clean the script once I get it working!)
<?php
// Get key from the parameter.
$avatar_key = $_GET['key'];
// Quest params.
$questname = $_GET['questname'];
$questid = $_GET['id'];
// Connect to the database. $con holds connection info.
$con = mysql_connect("localhost","user","pass");
// Error checking.
if(!$con)
{
die('Could not connect: '.mysql_error());
}
// Select the DB we want.
mysql_select_db("yyyyy_slcom",$con);
// Build the query.
$query = "SELECT * FROM sldb_data WHERE sldb_data.uuid = '$avatar_key' AND sldb_data.field = '$questname'";
/*$query = "select * from (
select uuid, field, value, progress, ROW_NUMBER() OVER (PARTITION BY uuid ORDER BY progress DESC)
";*/
// Run the query, store the result in variable $result.
$result = mysql_query($query);
if(!result)
{
die('Error: ' . mysql_error());
}
// Check how many rows we got back with our query.
$rows_returned = mysql_num_rows($result);
echo $row['field'];
// If we get anything back,
if($rows_returned > 0)
{
//echo $row['field'] . ' was found.' . $questname;
/*if(!$row['field'])
{
echo 'You are not on this quest yet.';
}
elseif(($row['field']) && ($row['value'] == "notstarted"))
{
echo 'This quest hasn\'t started yet.';
}
elseif(($row['field']) && ($row['value'] == "started"))
{
echo 'You are on quest: "' .$row['field']. '"';
}*/
/* $fields = mysql_list_fields("tenaar_slcom","sldb_data");
$columns = mysql_num_fields($fields);
for ($i = 0; $i < $columns; $i++) {$field_array[] = mysql_field_name($fields, $i);}
if(in_array($quest, $field_array))
{
echo 'Your quest is ' . $row['field'];
}
elseif(!in_array($questname, $field_array))
{
echo 'You are not on this quest yet.';
}
elseif((in_array($questname, $field_array)) && ($row['value'] == "notstarted"))
{
echo 'You have not started quest "' .$row['field']. '" yet.';
} */
// cycle through and print what we got.
//while($row = mysql_fetch_array($result))
//{
//echo 'Quest name: ' . $row['field'] . ' | Progress: ' .$row['value'] . '<br />';
//}
}
/*else
{
echo 'You are not on this quest yet.';
}*/
// Close the connection.
mysql_close($con);
?>
You appear to be missing a step in-between the time you get the number of rows and when you print out the field. You need to actually store the results of the query in the $row array.
$rows_returned = mysql_num_rows($result);
$row = mysql_fetch_array($result);
echo $row['field'];

Categories