Answer the question
In order to leave comments, you need to log in
How to display string by php id ?id=1?
Good afternoon, I just started learning the php and mysql language
and I had a question how to display a certain string, say with id 1 or 2
, example site.com/?id=1 or site.com/?id=2
here is my code that I received for 50 minutes of evolution
<?php
include 'config.php'; // получили соединение с бд
$result = mysqli_query($link,"SELECT * FROM `product`") ;
?>
<!DOCTYPE html>
<html dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<table border='1'>
<tr>
<td>Идентификатор</td>
<td>Наименование</td>
<td>Цена</td>
</tr>
<?php
while($prod = mysqli_fetch_assoc($result))
{
?>
<tr><td><?php echo $prod['id']; ?></td><td><?php echo $prod['name']; ?></td><td><?php echo $prod['price']; ?> </td></tr>
<?php
}
?>
</table>
</body>
</html>
Answer the question
In order to leave comments, you need to log in
The question is good, but here we run into the main problem of PHP - ALL tutorials on the Internet, and especially videos - show how to write hellish code from the last century.
1. Getting the value from the address bar
To get the value of the variable that was passed in the query string (this is the one after the question mark), you need to refer to the $_GET variable.
That is, in this case, you can write $id = $_GET['id']. The name of the received variable ($id) can be anything and does not have to match the passed value. But in the $_GET array index, of course, you need to write exactly the name that is in the address bar. That is, if site.com/?id=1, then $_GET['id'] will have the value 1.
2. Data validation
Further, it is very desirable to check that we got what we wanted in the variable, and also that we got at least something at all.
First, you need to check if the $_GET array contains the required key. In this case, this can be done using the isset () operator (although in general it is not recommended for checking the presence of keys in arrays)
. error.
Then, since id can only be an integer greater than zero, it's better to check that too and throw an error too.
3. Connecting to the database.
in "config.php" it should not be written what is there now, but this (with its own connection parameters, of course)
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect($host, $user, $pass, $db_name);
$link->set_charset("utf8mb4");
SELECT * FROM `product` WHERE id=1
$sql = "SELECT * FROM `product` WHERE id=?";
$stmt = $link->prepare($sql);
$stmt->bind_param("s", $id);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question