I have a very simple table that contains a list of 'victims' and the corresponding number of that type destroyed. I'm trying to make an output page of this information, using this code:
foreach( $victims as $vic )
{
$hits = mysql_query("SELECT amount
FROM victims
WHERE victim = ".$vic );
echo $hits;
print "$vic: $hits <br /><hr>";
}
However, hits comes out empty. What's wrong with my SQL query?
foreach($victims as $vic)
{
$hits = mysql_query('SELECT amount
FROM victims
WHERE victim = "' . mysql_real_escape_string($vic) . '"');
if($hits && mysql_num_rows($hits)>0) {
while($row = mysql_fetch_array($hits)) {
echo '<p>' . $row['amount'] . ' hits</p>';
}
} else {
echo '<p>' . mysql_error() . '</p>';
}
}
mysql_query() doesn't return the actual result of your query, but rather a resource with which you can then access the results.
This is a typical pattern:
$result = mysql_query(...);
$row = mysql_fetch_assoc($result);
print($row['amount']);
Each call to mysql_fetch_assoc returns the next row of the result set. If you were expecting multiple rows to be returned, you can call this in a while loop:
$result = mysql_query(...);
while ($row = mysql_fetch_assoc($result)) {
print($row['amount']);
}
Since there's no sane error checking in any of the answers, I'll put the whole thing in here:
foreach( $victims as $vic )
{
$sql = "SELECT amount
FROM victims
WHERE victim = '".mysql_real_escape_string($vic)."'";
$result = mysql_query($sql);
$result or die('Query Error: '.mysql_error() . ' - ' . $sql);
$hitsarray = mysql_fetch_assoc($result);
if ($hitsarray) {
$hits = $hitsarray['amount'];
} else {
// No row was found
$hits = 0;
}
echo $hits;
print "$vic: $hits <br /><hr>";
}
Oh, and this fixes the query error that caused the issue in the first place. Note the quotes wrapping the $vic variable in the string, as well as the proper escaping of the string...
Related
I'm trying to loop through every row in a table, and remove 5 characters from the end of one column. I have written the following code but it seems to remove 2 characters for some reason.
<?php
$connection = new mysqli('localhost', 'nawd_test', 'password', 'nawd_test');
if ($connection->connect_errno > 0) {
die ('Unable to connect to database [' . $connection->connect_error . ']');
}
$sql = "SELECT *
FROM test";
if (!$result = $connection->query($sql)) {
die ('There was an error running query[' . $connection->error . ']');
}
//Create an array to hold the values of id's already changed
$ids = [];
$newVals = [];
echo '<p>Fetching rows...</p>';
while ($row = $result->fetch_assoc()) {
//Check / Add the id
if (in_array($row['id'], $ids)) {
echo '<p style="red"><strong>Error: Script has repeated itself!</strong></p>';
break;
}
$ids[] = $row['id'];
$rowName = $row['name'];
$newName = substr($rowName, -1);
$newName = rtrim($rowName,$newName);
$newVals[] = $newName;
}
//Now loop and update
$newValID = 0;
foreach ($ids as &$id) {
echo '<p>Updating row with ID ' . $id . '</p>';
mysqli_query($connection, "UPDATE test SET name ='" . $newVals[$newValID] . "' WHERE id=" . $id);
echo '<p>Column successfully changed "<em>' . $newVals[$newValID] . '</em>"</p>';
$newValID++;
}
echo '<p style="color: green;"><strong>Script complete!</strong></p>';
?>
Dont do this in php, you can do it with a single sql query:
UPDATE test SET name = LEFT(name, LENGTH(name) - 5)
Change
$newName = substr($rowName, -1);
$newName = rtrim($rowName,$newName);
into
$newName = substr($rowName, 0, strlen($rowName) - 5);
With the way you're working, you could never predict how many characters that would have removed at the end.
Minimum 1, maximum the whole word.
Please read the documentation about rtrim and substr.
try this if you wanna doit inside the query:
update table1 set name=substr(name,-5,length(name))
So I have this PHP code:
Note: I do use mysqli_connect() further up.
$result = mysqli_query($con,"SELECT * FROM `smf_messages` WHERE `id_board` = 18");
if(!$result) {
echo "<center><p>Couldn't fetch news posts. Error code 2.</p></center>";
mysqli_close($con);
} else {
$posts = array();
$topicbdy = array();
while($row = mysqli_fetch_array($result,MYSQLI_ASSOC))
{
$posts[$row['id_topic']] = $row['id_topic'];
$topicbdy[$row['id_msg']] = $row['id_msg'];
}
$display = max($posts);
$display2 = min($topicbdy);
$qry = "SELECT * FROM `smf_messages` WHERE `id_board` = 18 AND `id_topic` = " . $display . " AND `id_msg` = " . $display2;
$result2 = mysqli_query($con,$qry);
//echo $qry;
if(!$result2) {
echo "<center><p>Couldn't fetch news posts. Error code 3.</p></center>";
} else {
while($show = mysqli_fetch_array($result,MYSQLI_ASSOC))
{
echo "<center><h1>" . $show['subject'] . "</h1></center><br /><br />";
echo "<center>" . $show['body'] . "</center><br />";
}
}
mysqli_free_result($result);
mysqli_free_result($result2);
mysqli_close($con);
It's supposed to get the latest topic out of the database for my SMF-based forum from the news board, by getting the highest topic id, but the lowest post id. It seems to be doing the query just fine, as I don't get any errors, but it doesn't show the subject or body. What should I do?
Your $result variable is wrong for second query fetch. For your second query
while($show = mysqli_fetch_array($result,MYSQLI_ASSOC))
Should be
while($show = mysqli_fetch_array($result2,MYSQLI_ASSOC))
^
I have used urldecode to receive a member ID from a previous site. The correct ID is being displayed in the URL but I can't fetch information from the database.
members.php:
<?php
$query = "SELECT name, memberID FROM members";
if(!$result = $db->query($query)){
die('There was an error running your query[' . $db->error . ']');
}
while($row = $result->fetch_assoc()){
printf ('<li>' . $row['name'] . '</li>');
}
?>
profiles.php:
<?php
$id = isset($_GET['memberID']);
$query = "SELECT * FROM members WHERE memberID = '".$id."'";
if ($result = $db->query($query)) {
while ($row = $result->fetch_assoc()){
printf("%s (%s)\n", $row["memberID"], $row['name']);
}
}
var_dump($query);
?>
All I get is a blank screen.
I found couple of problems in the code:
members.php
while($row = $result->fetch_assoc()){
printf ('<li>' . $row['name'] . '</li>');
}
Here you are using printf function which have 1st argument for format of string.
Correct that with echo statement as below:
while($row = $result->fetch_assoc()){
echo '<li>' . $row['name'] . '</li>';
}
profiles.php
$id = isset($_GET['memberID']);
Here you are setting the $id with isset() function return value.
You should instead set the value from GET parameter as below:
if(isset($_GET['memberID'])) $id = $_GET['memberID'];
See now if it's working.
Make sure that you use the correct capitalization of memberId vs. memberID. This is very important.
Do not pass values retrieved from GET/POST through urldecode. They already are.
Please try the following based on your code and let us know the results:
<?php
$id = isset($_GET['memberID']) ? $_GET['memberID'] : 0;
if($id > 0){
$query = "SELECT * FROM members WHERE memberID = '".$id."'";
$result = $db->query($query);
if($result){
echo "Rows found: " + $result->num_rows;
} else {
echo "No rows found";
}
} else {
echo "memberID is 0";
}
?>
Is memberID an int field in the database or a string field? If it is an int field then remove the single quotes in your query on profiles.php.
I am wanting to not echo out the comma at the end of the echo after the last row. How can I do that? Here is my code:
<?php
header("Content-type: application/json");
echo '{"points":[';
mysql_connect("localhost", "user", "password");
mysql_select_db("database");
$q = "SELECT venues.id, venues.lat, venues.lon, heat_indexes.temperature FROM venues, heat_indexes WHERE venues.id = heat_indexes.venue_id";
$res = mysql_query($q) or die(mysql_error());
while ($point = mysql_fetch_assoc($res)) {
echo $point['lat'] . "," . $point['lon'] . "," . $point['temperature'] . ",";
}
mysql_free_result($res);
echo ']}';
?>
Could you not use json_encode() instead, rather than hand-crafting the JSON?
$result = array();
//snip
while ($point = mysql_fetch_assoc($res)) {
$result[] = $point['lat'];
$result[] = $point['lon'];
$result[] = $point['temperature'];
}
//snip
header("Content-type: application/json");
echo json_encode( array('points' => $result) );
Use a count query to get the number of rows to begin with.
$query= "SELECT COUNT(*) FROM venues";
$count= mysql_query($q);
Then introduce a conditional and a count decrease each time through...
while ($point = mysql_fetch_assoc($res)) {
$count = $count - 1;
if ($count == 1) {
echo $point['lat'] . "," . $point['lon'] . "," . $point['temperature'];
} else {
echo $point['lat'] . "," . $point['lon'] . "," . $point['temperature'] . ",";
}
Json encode would probably be your best bet, but you could also use trim();
Rather than echoing in the while loop, append to a variable. Once outside the while loop, use $output = trim($output, ',') to remove trailing commas.
About the comma problem, I always target the first item instead of the last:
$first = true;
while ($point = mysql_fetch_assoc($res)) {
if ($first)
{
$first = false;
}
else
{
echo ",";
}
echo $point['lat'] . "," . $point['lon'] . "," . $point['temperature'];
}
You can use mysql_num_rows() to find out how many rows are in the result set passed back from your last query.
...
$res = mysql_query($q) or die(mysql_error());
$num_rows = mysql_num_rows($res);
Then combine that with Scotts answer and you should be set.
i'm trying to run this php code which should display a quote from mysql, but can't figure out where is it going wrong. the result variable is null or empty. can someone help me out. thanks!
<?php
include 'config.php';
// 'text' is the name of your table that contains
// the information you want to pull from
$rowcount = mysql_query("select count(*) as rows from quotes");
// Gets the total number of items pulled from database.
while ($row = mysql_fetch_assoc($rowcount))
{
$max = $row["rows"];
//print_r ($max);
}
// Selects an item's index at random
$rand = rand(1,$max)-1;
print_r ($rand);
$result = mysql_query("select * from quotes limit $rand, 1") or die ('Error: '.mysql_error());
if (!$result or mysql_num_rows($result))
{
echo "Empty";
}
else{
while ($row = mysql_fetch_array($result)) {
$randomOutput = $row['cQuotes'];
echo '<p>' . $randomOutput . '</p>';
}
}
$result = mysql_query("SELECT * FROM quotes ORDER BY rand() LIMIT 1") or die ('Error: '.mysql_error());
if (!$result || mysql_num_rows($result) == 0)
echo "Empty";
else {
while ($row = mysql_fetch_array($result)) {
$randomOutput = $row['cQuotes'];
echo '<p>' . $randomOutput . '</p>';
}
}
// your script probably can't go on without this file?
require 'config.php';
// I prefer to always pass the connection resource to mysql_query/mysql_real_escape_string
// assume $mysql = mysql_connect....
$result = mysql_query("SELECT Count(*) AS rows FROM quotes", $mysql)
or die(mysql_error());
// there's only one row with only one column, so mysql_result() is fine
$rowcount = mysql_result($result, 0, 0);
$rand = rand(0,$rowcount-1);
$result = mysql_query("SELECT cQuotes FROM quotes LIMIT $rand, 1", $mysql)
or die ('Error: '.mysql_error());
// there's either one or zero records. Again, no need for a while loop
$row = mysql_fetch_array($result, MYSQL_ASSOC);
if ( !$row ) {
echo "Empty";
}
else{
// do you have to treat $row['cQuotes'] with htmlspecialchars()?
echo '<p>', $row['cQuotes'], '</p>';
}
if ($result && mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_array($result)) {
$randomOutput = $row['cQuotes'];
echo '<p>' . $randomOutput . '</p>';
}
} else {
echo "Empty";
}