I am creating a webservice where I need to get some data from mysql and retrieve it in a mobile app.
I have been trying all day to do a query with a WHERE statement, but no success.
The normal query, without the WHERE is working perfectly though.
Also I went through all the similar questions on stack overflow and other forums, but none is the same problem as mine.
This is my current code:
<?php
$con=mysqli_connect("Hidden credentials");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if ($stmt = $con->prepare("SELECT
team.id as teamId,
team.team_name as teamName,
user.id as userId,
user.username as username,
team_members.role as role
FROM team_members
inner join user on team_members.user_id = user.id
inner join team on team_members.team_id = team.id
where user.id = ?
")) {
$stmt->bind_param("i", $id);
$stmt->execute();
$result = $stmt->get_result();
$resultArray = array();
$tempArray = array();
while($row = $result->fetch_object())
{
$tempArray = $row;
array_push($resultArray, $tempArray);
}
echo json_encode($resultArray);
$stmt->close();
}
?>
If I remove the line where user.id=?
it gets the data correctly.
Running the query on phpMyAdmin is everything ok, so it’s not any issue on the query.
2
Answers
Your QUERY doesn’t work because your variable
id
doesn’t exists (in code what you showing).Fix: create variable
id
and put some data to this variable.For example:
Or dynamcially:
From URL with GET method:
<a href="index.php?id=5">
. By clicking on thisa
tag you will be redirected to pageindex.php
with parameterid
which equals to5
.From POST method:
for example you have this
FORM
:after submiting this
FORM
values will be saved in$_POST
. You can access them by$_POST["name"]
. In this case$_POST["id"]
.$id = $_POST[“id”];
From SESSION:
$_SESSION["id"]
. You can access this variable ($_SESSION[“id”]) in other pages of your domain.The variable
$id
doesn’t exist (in your code). If you want to set the variable dynamically you can use$id = $_GET['id'];
. This will take the value from the url and put it in the variable!