This question already has answers here:
How can I get an unknown username given an ID?
(2 answers)
Closed 12 months ago.
I have a search function on my site which displays results from a MySQL db. Each search result is linked to a dynamic php page with the URL, i.e. /details.php?id=123.
I need the details.php page to get the ID (e.g 123) from the URL and then fetch all rows from the database with this ID, storing them in a variable for use later. I then need to be able to echo the rows at various points throughout the page to populate the content.
The code I have so far is:
<?php
$db = mysql_connect("","","") or die("Database Error");
mysql_select_db("items",$db);
$id = $_GET['id'];
$id = mysql_real_escape_string($id);
$query = "SELECT * FROM `items- table` WHERE `id`='" . $id . "'";
$result = mysql_query($query);
?>
I’m fairly new to PHP so not sure if the code above will get all rows based on the ID, and then how to echo the rows within divs on the page?
You can use mysql_fetch_array() OR mysql_fetch_assoc() function with while loop (if multiple rows there) OR without while loop if there is only one row.
$query = "SELECT * FROM `items- table` WHERE `id`='" . $id . "'";
$result = mysql_query($query);
while($fetch = mysql_fetch_array($result))
{
echo "<div>".$fetch['column_name']."</div>";
}
Almost correct. Just add something like this:
while ($row = mysql_fetch_assoc($result)) {
echo '<div>';
foreach ($row as $key => $val) {
echo $key.' = '.$value.'<br/>';
}
echo '</div>';
}
Related
I'm trying to create an image gallery with a for loop iterated by a counter of database rows.
To make it more clear: for each row in the table, get only the id(primary index) number and the image link from the server (not all the info in the row). With that information, echo an HTML image tag with the link inside the 'src=' and the id inside the 'alt='.
Two problems here:
1- the id number of the first row isn't zero.
2- I don't have a clue on how to get the total number of rows and to fetch only those two informations (id and img source).
That way, I could subtract the total number of rows minus the id number of the first row and using it to put an end on the loop.
So how to echo this dynamic html snippet based on my databse with PHP?
My code:
<?php
$link = mysqli_connect('localhost','user','pass','db');
$result = mysqli_query($link, "SELECT * FROM `table`");
$rows = mysqli_num_rows($result);
/* free result set */
mysqli_free_result($result);
$caption = mysqli_query($link, "SELECT ");
for($i=0; $i < $rows; $i++) {
echo "<img src='$imageURL' alt='$idNumber'>";
}
?>
You need to use sql functions to iterate through the dataset results. Replace your for loop... replacing 'image_url_column' and 'id_number_column' with the name of your actual columns in your db:
while ($row = while ($row = mysqli_fetch_assoc($caption)){){
echo "<img src='".$row['image_url_column']."' alt='".$row['id_number_column']."'>";
}
This is a really easy task.
First we fetch the data from the database using mysqli_query to do the query.
Then we use mysqli_fetch_array to get an array so then we can loop through it and echo each item.
After that, we mysqli_num_rows to get the total number of rows returned and increment it by 1 so it is not zero.
NOTE: Since you are going to increment the id to avoid getting a '0', don't to forget to minus '1' if you intend to use that id for some server-side purpose.
$result = mysqli_query($link, "SELECT * FROM `table`"); //query sql
$result_array=mysqli_fetch_array($result, MYSQLI_ASSOC);//return array from the query
$count = mysqli_num_rows($result); //get numbers of rows received
foreach($result as $row){ //do a foreach loop which is really simple
echo "<img src='". $row['img_column_name_from_db'] . "' alt='" .$row['id_column_name_from_db'] + 1 . "'>"; //echo data from the array, + 1 to "$row['id_column_name_from_db']" so that 'alt=' doesn't start from '0'.
}
echo $count;
You can use the count function of MySql to achieve the total number of rows.
also you can do this via mysqli_num_rows() function of mysql.
Code:
<?php
$link = mysqli_connect('localhost','user','pass','db');
$caption = mysqli_query($link, "SELECT id, img, count(id) as total from table");
echo
//$rows = mysqli_num_rows($result);
while($rows = mysqli_fetch_assoc($caption)){
echo "<img src='$rows[img]' alt='$rows[id]'>";
echo "Total Rows: ".$rows[total];
}
?>
hi i am trying to write a php to grab a specific category of post in a wordpress database, this is what i got so far:
$q = "select * from table1 where column like 'condition'";
$r = mysql_query($q);
$id = array();
if($r){
while ($row = mysql_fetch_array($r)) {
$link = $row["object_id"];
$id[] = array(
"postid"=>$link,
);
}
}
else{
echo mysql_error();
}
now i am trying to use the result i got from pervious code to search another table to get something else. i am new to php so i am hoping to get some help
thanks in advance
I am a novice when it comes to PHP but I don't understand if my syntax is wrong in this statement, or how would I grab an int from my MySQL server.
I know that my server credentials are working fine. How would I fix this statement to give me a returned integer of the number of reviews in the userinfo table?
$numberofpreviousreviews = mysql_query("SELECT `number_of_reviews` FROM `userinfo`") or die(mysql_error()); //Check to see how many reviews user has previously created
$amountofreviews = $numberofpreviousreviews + 1;
$query2 = mysql_query("ALTER TABLE userinfo ADD `amountofreviews` VARCHAR(10000)") or die(mysql_error()); //Make another column in database for the new review
You need to fetch your results after you run your query. There are several ways to do this but using mysql_fetch_assoc() will work for you.
$numberofpreviousreviews = mysql_query("SELECT `number_of_reviews` FROM `userinfo`") or die(mysql_error()); //Check to see how many reviews user has previously created
$row = mysql_fetch_assoc($numberofpreviousreviews);
$amountofreviews = $row['number_of_reviews'] + 1;
FYI, you shouldn't be using mysql_* functions anymore. They are deprecated and going away. You should use mysqli or PDO.
Assume you have a table userinfo which has the following structure and data :
Scenario #1 :
If you want to retrieve the all number_of_reviews, then do like this,
$query = "SELECT `number_of_reviews` FROM `userinfo`";
$result = mysqli_query($db,$query);
while ($row = mysqli_fetch_assoc($result)) {
echo "Number of reviews : " . $row['number_of_reviews'] . "<br/>";
}
It will give you,
Number of reviews : 20
Number of reviews : 40
Since, the result has many rows, it will display like above.
Scenario #2:
If you want to retrieve only the specific number_of_reviews for some user id (which is unique). I take id as 1 as a example here. Then do like,
$query2 = "SELECT `number_of_reviews` FROM `userinfo` WHERE `id` = 1";
$result2 = mysqli_query($db,$query2);
while ($row2 = mysqli_fetch_assoc($result2)) {
echo $row2['number_of_reviews'] . "<br/>";
}
This will print,
20.
Because, number_of_reviews is 20 for id 1.
I have a html page that posts to mysql database through a php script. How do I get the information that was entered in the html page to display after 1 record created?
<?php
$link = mysqli_connect('****', '****', '****', 'orders');
$sequence = $_POST['sequence'];
$items_count = $_POST['items_count'];
$total = $_POST['total'];
$payment_type = $_POST['payment_type'];
$sql="INSERT INTO orders (sequence,items_count,total,payment_type)
VALUES
('$sequence','$items_count','$total','$payment_type')";
if (!mysqli_query($link,$sql)) {
die('Error: ' . mysqli_error($link));
}
echo '1 record created';
mysqli_close($link);
?>
In the page that is supposed to display the posts, have another query
$sql = "SELECT sequence,items_count,total,payment_type FROM orders";
and I'm not sure if it's the right mysqli function, but after you retrieve the data from mysql as an array (mysqli_fetch_array ?) - you have to iterate through the returned results.
foreach($fetched_row as $row){
echo "<pre>"; print_r($row); echo "</pre>"
}
Which, you'll obviously want to use your own HTML - and the $row will be an associative array with the column names as the keys --
You need to add this code on the page where your fields will be displayed.
<?php
$last_record_id = mysql_insert_id();
$query = "SELECT * FROM <tablename> WHERE <$table_primary_key_id> = '$last_record_id'";
$result = mysqli_query($dbcon, $query);
$row = mysqli_fetch_array($result)
?>
Then fetch each field in separate variable like $price = $row['price'] and display them. You don't need looping because there is only one record to fetch and display.
I've been writing a script to display the names of users based on whether they are assigned an even or odd comment id. It calls up data from 2 different tables in the same database. Here is the table information:
Table 'comments' has the columns commentid, tutorialid, name, date: Table 'winners' has the columns pool, pool2, pool3, pool4, pool5, pool6, pool7. Table 'comments' has multiple rows that are updated through user input. Table 'winners' has only 1 row with numbers that are randomly generated daily.
The first part of the script that displays "Result 1" and "Result 2" is working properly. The part that isn't working is the part that calls up the usernames. I only want to display the usernames that corralate with the result that is displayed IE if Result 1 is chosen then I only want the usernames with even 'commentid's displayed.
<?php
$db = mysql_connect('localhost', 'username', 'pass') or die("Database error");
mysql_select_db('dbname', $db);
$query = "SELECT pool FROM winners";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result))
if ($row['pool'] % 2) {
echo "<h4>Result 1</h4>";
$names = get_names(1);
foreach($names as $name) {
echo $name . "<br/>";
}
} else {
echo "<h4>Result 2</h4>";
$names = get_names(0);
foreach($names as $name) {
echo $name . "<br/>";
}
}
function get_names($pool_result)
{
$name_array = array();
$query = "SELECT * FROM comments where mod('commentid',2) = $pool_result";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
array_push($name_array, $row['name']);
}
return $name_array;
}
?>
Can anyone figure out why this isn't working?
The SELECT statement with the mod is not referencing the field. Should be backticks instead of single quotes. Single quotes indicate a string constant, which would result in a constant result set (mod('commentid',2) appears to have a result of 0). It should be something like this:
$query = "SELECT * FROM comments where mod(`commentid`,2) = $pool_result";
Adding quotes around commentid treats it as a string, and you can't mod a string by an integer. Try the following instead:
$query = "SELECT * FROM comments WHERE commentid % 2 = $pool_result";
This was taken from the following Stack question: select row if the "value" % 2 = 1. MOD()