Ok so I've searched and searched but still struggling to resolve my problem. This is my current php coding:
$show = "Select effectiveness, round((Count(effectiveness)* 100 / (Select Count(*) From acupuncture))) as Score
From acupuncture
Group By effectiveness
ORDER BY Score DESC";
$result = mysql_query ($show);
WHILE($show = mysql_fetch_array($result))
{
$field1 = $show[effectiveness];
$field2 = $show[Score];
echo "$field1: ";
echo "$field2%<br><br>";
}
In addition to displaying the above I would also love to display the number of rows in the table. I know the sql code is:
"SELECT COUNT(id) AS entries FROM acupuncture"
Problem is when I try to input this into my php page I keep getting errors. I want to show both SELECT statement results on the one php page. If someone can help I would greatly appreciate it.
Thank you
Shikz
All good, problem has been fixed. Thanks for all your help :) P.S. This is the code I inputted:
$size = #mysql_query("SELECT COUNT(*) AS `total` FROM acupuncture");
$query = mysql_fetch_array($size);
echo "Number of entries: ";
echo $query['total'];
echo "<br><br>";
I was writing up the php code incorrectly before, but now all good. Thanks again.
Try this:
while($show = mysql_fetch_assoc($result))
{
$field1 = $show['effectiveness'];
$field2 = $show['Score'];
echo "$field1: ";
echo "$field2%<br/><br/>";
}
To cound all rows found read here
Small hints:
Please stop using mysql, it is deprecated.
Use mysqli or PDO instead.
ALWAYS use quotes when using string-indexed array
Make change in
WHILE($show = mysql_fetch_array($result))
{
$field1 = $show[effectiveness];
$field2 = $show[Score];
echo "$field1: ";
echo "$field2%<br><br>";
}
TO
WHILE($row= mysql_fetch_array($result))
{
$field1 = $row[effectiveness];
$field2 = $row[Score];
echo "$field1: ";
echo "$field2%<br><br>";
}
Related
I have the following code that works by outputting as a link ( the link comes from a field in my database) I wish to do the same for the code below, however i cannot get it work, here is the example of what I have that works, and the code that i wish to make output as a link:
Working Code what I want it to look like
if (!empty($_REQUEST['term'])) {
$term = mysql_real_escape_string($_REQUEST['term']);
$sql = "SELECT * FROM adrenaline WHERE title LIKE '%".$term."%'";
$r_query = mysql_query($sql);
while ($row = mysql_fetch_array($r_query)){
echo '<br> '. $row['title'] .'';
}
}
?>
And the code that i have at the moment, it works by be manually typing in the hyper link, however I wish to make it take the link from the database like the example above
//query the database
$query = mysql_query("SELECT * FROM hobby WHERE id = '1' ");
//ferch the results / convert results into an array
WHILE($rows = mysql_fetch_array($query)):
$title = $rows['title'];
echo "<a href='shard.php'>$title</a>";
endwhile;
?>
Many thanks!
I am not 100% certain if this is what you meant to ask... let me know in comments:
<?PHP
$query = mysql_query("SELECT * FROM hobby WHERE id = '1' ");
if(mysql_num_rows($query) >= 1) {
while($rows = mysql_fetch_array($query)) {
echo sprintf("%s", $rows["description"], $rows["title"]);
}
} else { echo "No hobbies found."; }
?>
I believe you might have faced some syntax issues while dealing with quotes parsing a variable in <a html tag. Consider using sprintf something like in my example.
I have also added a mysql_num_rows() just in case and you can see its a good fail-safe method incase there are no rews found on any select query.
IMPORTANT: STOP using mysql_ functions because its deprecated from new PHP versions. Use PDO or mysqli instead.
I am currently trying to prevent sql injection by using mysqli statements. However, after completing this transition, I am not getting results from my database anymore. I have a form where users can select economic data by narrowing down year intervals, months out of the year, and a location.Here is my current coding issues:
<?php
if (isset($_POST['submitted'])) {
$gYear = $_POST["year"];
$gYear2 = $_POST["year2"];
$gMonth = $_POST["month"];
$gSelect = $_POST["location"];
if ($gYear > $gYear2) {
die('ERROR: Your second year cant be a time period before the first year you selected');
}
else {
$query = $conn->prepare("SELECT $gSelect, Year FROM unemployed WHERE year BETWEEN ? AND ? and month= ?");
$query->bind_param('sss', $gyear, $gYear2, $gMonth);
$query->execute();
$result = = $conn->query($query)
echo"<table>";
echo "<tr><th>Year</th><th>Time</th><th>$gSelect</th></tr>";
while ($row = $result->fetch_object()){
echo "<tr><td>";
echo $row->Year;
echo "</td><td>";
echo $gMonth;
echo "</td><td>";
echo $row->$gSelect;
echo "</td></tr>";
}
echo "</table";
}
} // end of main if statement
?>
It worked before I tried updating my query to prevent injection. I am currently using php 5.2.14 to work on this in case you guys were wondering. Am I missing a statement? Can anyone help me figure out what my issue is? Any help would be greatly appreciated.
$query->get_result()
seems to be unavailable in your version of PHP. See here for a workaround.
Edit: Correction, thanks to comment
I've got a php file fetching some data from a MYSQL database. This is my code so far:
<?php
include 'DB.php';
$connection=mysql_connect(DB_SERVER,DB_USER,PASS);
$db=mysql_select_db(DB_Name);
$sql="select * from lookup where id = ".$_GET['id'];
$res=mysql_query($sql) or die(mysql_error());
while($row=mysql_fetch_array($res))
{
echo $row['message'];
}
?>
What would I have to add so that if there was no data, there'd be an error message? I'm guessing an If/else statement but I'm not sure how to fit it in with the while syntax.. any help?
$res = mysql_query(...) ...;
if (mysql_num_rows($res) == 0) {
die("Hey, nothing here!");
}
Beyond that:
a) you're utterly vulnerable to SQL injection attacks. Stop your coding project and learn about them before you go any further.
b) stop using the mysql_*() functions. They're deprecated.
You can use $count = mysql_num_rows($res); to get the number of rows returend. Then you can use an if statement to display whatever error.
I did it like mentioned above:
$query = "select * from lookup where id = ".$_GET['id'];
$result = mysql_query($query) or die ("Error in query: $query " . mysql_error());
$num_results = mysql_num_rows($result);
if ($num_results == 0){
echo "nothing here</br>";
}
else{
echo "<b> $num_results </b> result(s) match your query</br>";
while($row=mysql_fetch_array($res))
{
echo $row['message'];
}
You can of course leave the "echo $num_results..." out, but there you can give the number of results, which is sometimes quite useful.
When I click on any link it opens all movies in my database. I want only that movie which begins with that letter and I don't know where I've made a mistake. Here is my code:
$azRange = range('A', 'Z');
foreach ($azRange as $letter){
echo ''.$letter.' | ';
}
if(isset($_GET["task"]) && $_GET["task"] == "view"){
$naslov = $_GET['naslov'];
$query = "SELECT filmovi.naslov, filmovi.godina, filmovi.trajanje, filmovi.slika
FROM filmovi
ORDER BY naslov";
$result = mysql_query($query)
or die ('SQL Greska: '.mysql_error());
if($result){
while($filmovi = mysql_fetch_array($result)){
echo '<center><b>';
echo '<td><img src="img/'.$filmovi["slika"].'" border="0" width="100" /></td>';
echo '</br>';
echo '<td>'.$filmovi["naslov"].'</td>';
echo '<td> ('.$filmovi["godina"].')</td>';
echo '<br>';
echo '<td>Trajanje: '.$filmovi["trajanje"].' min</td>';
echo '</b></center>';
echo '</tr>';
}
You are not passing the letter to the database query at any point.
$query =
"SELECT filmovi.naslov, filmovi.godina, filmovi.trajanje, filmovi.slika
FROM filmovi
WHERE naslov LIKE '$naslov%'
ORDER BY naslov";
Your query
$query = "SELECT filmovi.naslov, filmovi.godina, filmovi.trajanje, filmovi.slika
FROM filmovi
ORDER BY naslov";
is fetching all the movies from the database. There is no filtering here. Add some where conditions to this query and you'll get the expected result.
Changing to this query might help:
SELECT filmovi.naslov, filmovi.godina, filmovi.trajanje, filmovi.slika
FROM filmovi
WHERE `naslov` LIKE '{$naslov}%'
ORDER BY naslov
Since others have already answered your question (missing WHERE clause), I just want to mention that the <center> HTML tag is deprecated, and you should use CSS instead.
The mysql driver for PHP is also outdated, so instead of using:
mysql_query($query);
you should use
mysqli_query($link, $query);
for better security, OOP support, prepared statements, and transactions.
You can read about it here
Even if you are a beginner and you don't care about what those features mean, you should try and get into the habit of using mysqli anyway, so that when the day comes that you learn to appreciate it, you don't have to go back and update all of your code.
$sql = "SELECT messages.text, users.name FROM messages INNER JOIN users ON messages.user_id=users.id ORDER BY messages.ms_id DESC LIMIT 10";
$result = mysql_query($sql);
$rows = array();
while($row = mysql_fetch_array($result))
{
$rows[]=$row;
}
echo $rows[0][1].$rows[0][0];
/* for($i=0;$i<=10;$i++)
{
echo $rows[i][1].$rows[i][0];
}
*/
This script is supposed to show the last 10 messages in a chat.What I'm doing is getting the Name of the user from the users table and the text from the message table and I want to display them in my chat window.Right now I have only 4 messages recorded and don't know how this affects the whole script I should implement a check for this too, but the bigger problem is that when i use echo $rows[0][1].$rows[0][0]; the info is displayed correctly, but when I try to make a loop so I can show tha last 10 (I tried the commented one) then nothing is displayed.I thought at least when I use this loop I'll see the 4 recorded messages but what really happen is a blank window.Obvously I have the info recorded in $rows[] and can echo it, but don't understand why this loop don't work at all.I'll appreciate if someone can help me with this and with the check if the messages are less then 10.
Thanks.
Leron
P.S
Here is the edited script, thanks to all of you, I need the array because otherwise the most recent message is shown at the top which is not an opiton when I use it for diplaying chat masseges.
for($i=10;$i>=0;$i--)
{
if($rows[$i][1]!="" || $rows[$i][0]!="")
{
echo $rows[$i][1].' : '.$rows[$i][0];
echo "</br>";
}
}
Your FOR loop was running 11 times even if only 10 records. The second clause should be a < instead of <=. Plus the $ was missing on the i variable.
For example sake, you don't really need to make an array from the rows, and you can refer to the fields by name:
while($row = mysql_fetch_array($result))
{
echo $row['name'] . ' says: ' . $row['message'] . '<BR>';
}
why not just do
while($row = mysql_fetch_array($result))
{
echo $row[1]." ".$row[0];
}
Your query, auto limits it to the last 10, this will then show anything from 0 to 10 which get returned.
PS I added a space between username and message for readability
You need $ symbols on your i variable:
for($i=0;$i<10;$i++)
{
echo $rows[$i][1].$rows[$i][0];
}
A more robust solution would be like this:
$sql = "SELECT messages.text, users.name FROM messages INNER JOIN users ON messages.user_id=users.id ORDER BY messages.ms_id DESC LIMIT 10";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
echo $row[1].$row[0];
}