How to echo data from id - php

I assume this must be simple, but I'm just stuck on a solution here. How would I echo data from the id in the database? I cannot edit the css div where I display this data so need to find out a way to cut down the PHP, for example:
<? $query = "SELECT * FROM example WHERE id='1'";
$result_1 = mysql_query("SELECT * FROM example WHERE id=1");
$result_2 = mysql_query("SELECT * FROM example WHERE id=2");
$result_3 = mysql_query("SELECT * FROM example WHERE id=3");
while($row_1 = mysql_fetch_array($result_1))
while($row_2 = mysql_fetch_array($result_2))
while($row_3 = mysql_fetch_array($result_3))
{ ?>
From here I echo the data in a div:
<? echo $row_1['name'] ?>
What I am trying to do is something like this: echo $row_1['name']['1']. I want to somewhat use the WHERE id=1 inside my echo. Sorry if this is not clear.
Thanks

You can easily do:
$result = mysql_query("SELECT * FROM example WHERE id IN (1, 2, 3)");
while ($row = mysql_fetch_assoc($result)) {
echo ($row['id'] == 1) ? $row['id'] : ''; // print id only when id == 1
}
Notice: This extension (mysql_*) is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used.

Try something like this:
<?
$result = mysql_query("SELECT * FROM `example`"); // Select all columns and rows from the example table
while($row = mysql_fetch_assoc($result)) { // For each row returned
print($row['id'] . " - " . $row['name'] . "<br />\n"); // Print the row's ID and name
}
?>

You can try to do an if() just before the echo, like below:
<? if($row_1['id'] == 1) echo $row_1['name']; ?>
Or from what we know, your results in $row_1 will always have id == 1, since you specified it in the query.
Hope this helps, good luck :)

Try this:
$result = mysql_query("SELECT * FROM example WHERE id IN (1, 2, 3)");
while ($row = mysql_fetch_assoc($result)) {
echo ($row['id'] == 1) ? $row['id'] : ''; // print id only when id == 1
}

Related

how do include multiple pieces of data on one page?

I cant figure out how to get multiple entries of data from my database. You can see below that I have newsID = 1, which allows me to get that to show on my database, but how should I change the code to be able to access other entries like newsID = 2 as well?
<?php
$queryAffinity = "SELECT * FROM affnews WHERE newsID = 1";
$stmt = $pdo->query($queryAffinity);
$row = $stmt->fetchObject();
?>
<?php if($row->newsID == 1) echo "<p>{$row->newsDescription}</p>"; ?>
this is the code im trying to use to echo the id 1
Edit your WHERE-Clause and put it in a loop. For example:
$queryAffinity = "SELECT * FROM affnews WHERE newsID = 1 OR newsID = 2";
$stmt = $pdo->query($queryAffinity);
while($row = $stmt->fetchObject())
{
//do something with $row
}
You Can use the following code:
$queryAffinity = "SELECT * FROM affnews WHERE newsID IN (1, 2)";
$stmt = $pdo->query($queryAffinity);
while($row = $stmt->fetchObject())
{
echo $row->id;
}

Pass value in php

hi I have modules as a links in student page so after click on any one of these links i want to pass the id of the Specific module to the next page,so how can i pass the id value and this is my code, please help.
$sql = "SELECT * FROM MODULE,USER where user_access_level = module_level AND '$user_id' = user_login ";
$result = $db->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo '<li>'.$row["module_id"].' '.$row["module_name"].' '.$row["module_points"].'</li> ';
}
}
Here is your code with all of the quotes, concatenations, backticks and backward logic corrected:
$sql = "SELECT * FROM `MODULE`, `USER` WHERE `user_access_level` = 'module_level' AND `user_login` = '". $user_id."' ";
$result = $db->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo '<li>'.$row["module_id"].' '.$row['module_name'].' '.$row['module_points'].'</li> ';
}
}
I would bet that module_level is also supposed to be a variable. $G looks problematic, what sets the array $G? You should replace the $G with $row if I am reading this correctly.
...AND user_id = '".mysqli_real_escape_string ($user_login)."'";
I assume?
Anyway, DB_field = $param. And maybe mysql_, not mysqli_, but hope you check the user input before you pass it to the query...
Check the syntax error:
echo '<li>' . $row["module_id"] . ' ' . $row["module_name"] . ' ' . $row["module_points"] . '</li>';

max(id) and limit 10, but use them in different places

I have two tables, posts and sections. I want to get the last 10 posts WHERE section = 1,
but use the 10 results in different places. I make a function:
function sectionposts($section_id){
mysql_set_charset('utf8');
$maxpost1 ="SELECT max(id) from posts WHERE section_id = $section_id ORDER BY ID DESC LIMIT 20";
$maxpost12 =mysql_query($maxpost1);
while ($maxpost_rows = mysql_fetch_array($maxpost12 ,MYSQL_BOTH)){
$maxpost2 = $maxpost_rows[0];
}
$query = "SELECT * FROM posts WHERE id = $maxpost2";
$query2 = mysql_query($query);
return $query2;
}
$query2 = sectionposts(6);
while ($rows = mysql_fetch_array($query2)){
echo $rows['title'] . "<br/>" . "<br/>";
echo $rows['id'] . "<br/>" . "<br/>";
echo $rows['image_section'] . "<br/>";
echo $rows['subject'] . "<br/>";
echo $rows['image_post'] . "<br/>";
}
How can it take these ten results but use them in different places, and keep them arranged from one to ten.
this was the old case and i solve it but i found another problem, that, if the client had deleted a post as id = 800 "so there aren't id = 800 in DB" so when i get the max id minus $NUM from it, and this operation must be equal id = 800, so i have a programing mistake here, how can i take care of something like that.
function getmax_id_with_minus ($minus){
mysql_set_charset('utf8');
$maxid ="SELECT max(id) FROM posts";
$maxid1 =mysql_query($maxid);
while ($maxid_row = mysql_fetch_array($maxid1)){
$maxid_id = $maxid_row['0'];
$maxid_minus = $maxid_id - $minus;
}
$selectedpost1 = "SELECT * FROM posts WHERE id = $maxid_minus";
$query_selectedpost =mysql_query($selectedpost1);
return ($query_selectedpost);
}
<?php
$ss = getmax_id_with_minus (8);
while ($rows = mysql_fetch_assoc($ss)){
$main_post_1 = $rows;
?>
anyway "really" thanks again :) !
A few thoughts regarding posted code:
First and foremost, you should stop using mysql_ functions as they are being deprecated and are vulnerable to SQL injection.
$maxpost1 ="SELECT max(id) from posts WHERE section_id = $section_id ORDER BY ID DESC LIMIT 20";
When you SELECT MAX, MIN, COUNT, AVG ... functions that only return a single row, you do not need an ORDER BY or a LIMIT.
Given that you are only asking for the MAX(id), you can save work by combining your queries like so:
SELECT * FROM posts
WHERE id = (SELECT MAX(id) from posts WHERE section_id = $section_id)
If I'm understanding what you're trying to do (please correct me if I'm wrong), your function would look something like:
function sectionposts($section_id) {
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
$stmt = mysqli_prepare($link, "SELECT title, id, image_section, subject, image_post FROM posts "
. "WHERE section_id = ? ORDER BY id DESC LIMIT 10");
mysqli_stmt_bind_param($stmt, $section_id);
return mysqli_query($link, $stmt)
}
$result = sectionposts(6);
while ($row = mysqli_fetch_assoc($result)) {
echo $rows['title'] . "<br /><br />";
echo $rows['id'] . "<br /><br />";
echo $rows['image_section'] . "<br />";
echo $rows['subject'] . "<br />";
echo $rows['image_post'] . "<br />";
}
Try this instead, to save yourself a lot of pointless code:
$sql = "SELECT * FROM posts WHERE section_id=$section_id HAVING bar=MAX(bar);"
$result = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_assoc($result);
echo ...;
echo ...;
The having clause lets you find the max record in a single operation, without the inherent raciness of your two-query version. And unless you allow multiple records with the same IDs to pollute your tables, removing the while() loops also makes things far more legible.
Seems like you want to store them in an array.
$posts = array(); //put this before the while loop.
$posts[] = $row; //put this in the while loop

While loop not printing all answers

This might be really simple, but i cannot figure out the problem with this code:
$sql = mysql_query("select * from Temporary_Stock_Transfer where Emp_ID = '$emp_id' and Company_ID = '$company_id'");
if(mysql_num_rows($sql) == 0) {
echo "<tr><td colspan='3'><i>You currenty have no items</i></td></tr>";
}else {
while($row = mysql_fetch_array($sql)) {
echo mysql_num_rows($sql);
echo 'reached';
$book_id = $row[1];
$sql = mysql_fetch_row(mysql_query("select title from Book where Book_ID = '$book_id'"));
echo "<tr><td>".$sql[0]."</td><td>".$row[2]."</td><td><span class='label label-important'>Remove</span></td></tr>";
}
}
Now based on my database the query is returning 2 results, the echo mysql_num_rows($sql) also gives out 2. However the reached is echoed only once. Does anyone see a potential problem with the code?
P.S: My bad, $sql is being repeated, that was a silly mistake
It will only echo once because of this line :
$sql = mysql_fetch_row(mysql_query("select title from Book where Book_ID = '$book_id'"));
your overwriting the $sql variable.
Why not just run a single query and join the data you require ?
try ($sql2 instead of $sql and $sql[0] to $sql2[0]):
$sql = mysql_query("select * from Temporary_Stock_Transfer where Emp_ID = '$emp_id' and Company_ID = '$company_id'");
if(mysql_num_rows($sql) == 0) {
echo "<tr><td colspan='3'><i>You currenty have no items</i></td></tr>";
}else {
while($row = mysql_fetch_array($sql)) {
echo mysql_num_rows($sql);
echo 'reached';
$book_id = $row[1];
$sql2 = mysql_fetch_row(mysql_query("select title from Book where Book_ID = '$book_id'"));
echo "<tr><td>".$sql2[0]."</td><td>".$row[2]."</td><td><span class='label label-important'>Remove</span></td></tr>";
}
}
I think it'll be because you are ressetting the sql variable
$sql = mysql_fetch_row(mysql_query("select title from Book where Book_ID = '$book_id'"));
when you are still using it in the while loop. :P
It's probably this line:
$sql = mysql_fetch_row(mysql_query("select title from Book where Book_ID = '$book_id'"));
Try using a different variable name.
You are changing the $sql variable inside the loop, therefore the next time you run $row = mysql_fetch_array($sql), the value will be different (probably won't be any based on your code).
Inside the while loop you are re-using the same variable: $sql. This is used to control the terminating condition of the loop.
Using a different variable name, e.g. $sql2 should leave the original variable intact and the loop should proceed as expected.

Display only queried ID+row PHP/MySQL

I have my data stored in a MySQL table, which includes an auto_increment ID number (unique) for each new row.
I'd like users to be able to get a certain ID number, using the $_GET function.
eg. User loads http://mysite.com/id.php?id=123
Page displays ID number 123 along with the row.
echo $row['id'];
echo "<table>";
echo "<tr> <th>Unit</th> <th>Message</th> <th>Date</th> </tr>";
while($row = mysql_fetch_array( $result )) {
echo "<tr><td>";
echo $row['title'];
echo "</td><td>";
echo $row['description'];
echo "</td><td>";
echo $row['pubDate'];
echo "</td></tr>";
}
echo "</table>";
echo "</center>";
I'm stuck as to where I put the $_GET bit.
Thanks :)
You should append it to your query (using intval to avoid SQL injection) like this:
// use the id in your WHERE clause, convert it to an integer to avoid sql injections
$query = 'SELECT fields FROM table WHERE id = ' . intval($_GET['id']);
$result = mysql_query($query);
$row = mysql_fetch_row($result);
... do stuff with $row ...
Firstly, your code does not make much sense, since you use $row before it was defined.
Secondly, $result isn't defined at all, and it should be, for example like this:
$id = intval($_GET['id']);
$result = mysql_query("SELECT FROM table WHERE id = '$id'");
And now you know how and where to use $_GET['id'].
Dont waste your time doing the comparison afterwards, you'll save yourself alot of time by adding it to the original query
$id = intval($_GET['id']);
$query = "SELECT whatever FROM table WHERE id=$id";
$id = $_GET['id'];
$id = mysql_real_escape_string($id);
$query = "SELECT * FROM `Table` WHERE `id`='" . $id . "'";
$res = mysql_query ($query);
$exist = mysql_num_rows($res);
if ($exist) {
$row = mysqlfetch_assoc($res);
...
}

Categories