Reputation: 91
Here's the layout of my table (content
):
id, shortcode, message
1, blinds01, Random Message
2, shutters88, Random Message
3, windows12, Random Message
Here's the PHP I'm using to get all of the rows:
<?php
$host = "removed";
$user = "removed";
$pass = "removed";
$database = "removed";
$mysqli = new mysqli($host, $user, $pass, $database);
$query = "SELECT * FROM `content`";
$mysqli->close();
?>
What I'm having issues with is not understanding how to echo data.
For example, what PHP code what I use to echo the message
column where id = 2
?
I know that I could just update my query to get that specific information, but I need to get a lot of different message
fields on the same page and don't want to be querying the database 100 times per page load (which is why I'm querying all rows in the table).
Any help would be appreciated.
Upvotes: 0
Views: 9878
Reputation: 371
PHP documentation gives a good example similar to what you want to do: http://php.net/manual/en/mysql.examples-basic.php. In your case, it would be something like:
$mysqli = new mysqli($host, $user, $pass, $database);
$query = "SELECT * FROM `content`";
$result = $mysqli->query($sql);
while($row = $result->fetch_assoc()) {
if ($row["id"] == 2) {
echo $row["message"];
}
$mysqli->close();
Upvotes: 1
Reputation: 402
Try this code to fetch message where id= 1
$result = mysqli_query($mysqli,"SELECT message FROM content WHERE id='1' LIMIT 1");
$data = mysqli_fetch_row($result);
echo $data["message"];
Upvotes: 0
Reputation: 715
This is a example from this and for "MyGuests" table and his columns you need a code like this (How a person mentioned above, you need to fetch then result and loop through them):
`$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row THIS IS WHERE YOU PRINT EACH ROW FROM THE QUERY
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();`
You only have to use your own table, columns, variables, etc.
Upvotes: 0