Through this PHP code I obtain the id
numeric of the product identifier obtaining the following result from the url producto/pintura/
4
if (isset($_GET['id'])){
$id = $_GET['id'];
$sql = "SELECT * FROM productos WHERE url='".$id."'";
$result = mysqli_query($con, $sql);
if(mysqli_num_rows($result) > 0){
while ($row = mysqli_fetch_array($result)) {
$id = $row['id_productos'];
}
}
}
If I add an function dato(){}
Example to a query:
function dato(){
$get_imagenes = "SELECT * FROM imagenes WHERE id_imagen='".$id."'"; //Error 24
$run_imagenes = mysqli_query($con, $get_imagenes); //Error 25
if(mysqli_num_rows($run_imagenes) >0){ //Error 26
while ($row_imagenes = mysqli_fetch_array($run_imagenes)) {
echo '<div>'.$row_imagenes['multimedia'].'<div>';
}
}
}
<?php dato();?>
It shows me the following error messages
Notice : Undefined variable: id in C:\xampp\htdocs\images\detail.php on line 24
Notice : Undefined variable: con in C:\xampp\htdocs\images\detail.php on line 25
Warning : mysqli_query() expects parameter 1 to be mysqli, null given in C:\xampp\htdocs\images\details.php on line 25
Warning : mysqli_num_rows() expects parameter 1 to be mysqli_result, null given in C:\xampp\htdocs\images\details. php online 26
If I remove the function
from the query, the query executes without any errors.
When creating a function
to the query this acts as a barrier, it prevents the value of from $id
reaching the query of thefunction
How can I create a global identifier, by means of a function obtaining the id of the Url in order to be able to add it to my queries with function
?
function IdGlobal(){}
In order to prevent my queries from
fucntion
showing error messages.
Global variables are generally bad practice. On why, you can consult: Why is it considered a bad practice to use global variables? , there are several interesting answers on that question.
I think what you want to do would resolve:
Adding parameters to your function:
When you call the function you pass the parameters:
That way,
$id
and$con
will be within the scope of the function and you avoid using globals.Looking at the error messages, you have more problems in your code that you will have to solve.
Security-wise, avoid passing queries to the database like so:
since you can be a victim of SQL Injection.
To avoid it:
a. Write a prepared query, in which external data is replaced by question marks
b. You pass the data separately
c. you execute
d. you get the results
Here is a complete example of a prepared query using MySQLi .
An example of how to get the value of
$id
is to use one of the PHP reserved words withglobal
I have added a value to
$id
and withglobal
we get the value globally inside thefunction
we add as follows:Example:
As a result we will obtain: 1
You can test the operation here