PHP MySQLi get columns from foreign key - php

I have the following tables:
'auktionen'
id|uid|typ(FK)|min|max|menge|...
'typen'
id|typ
1|Hack
2|Schredder
where typ in typen is just a textutal representation, which I would like to get.
$prep_stmt = "SELECT anzeigentyp, typ, holzart,
qualitaet, rinde, min, max, menge FROM auktionen WHERE uid = ?";
$stmt = $mysqli->prepare($prep_stmt);
$stmt->bind_param('i', $user_id);
$stmt->execute();
$stmt->bind_result($anzeigentyp, $typ, $holzart, $qualitaet, $rinde, $min, $max, $menge);
$stmt->store_result();
So when fetching all my results I want to get "Hack" instead of the referencing id (in case it is 1). I guess it needs some JOIN to be achieved and I tried it like this without success:
$prep_stmt = "SELECT anzeigentyp, typen.typ, holzart,
qualitaet, rinde, min, max, menge FROM auktionen WHERE uid = ?
JOIN typen ON auktionen.typ = typen.typ";
What is the proper way to do it?

You must move the where clause to the end and join the corresponding columns typen.id and auktionen.typ
select a.anzeigentyp, t.typ, a.holzart, a.qualitaet, a.rinde, a.`min`, a.`max`, a.menge
from auktionen a
join typen t on t.id = a.typ
where ...

Related

PHP PDO: Can't bind value to multiple variables?

I am trying to execute a query that joins several tables using the same foreign key via the below query but it returns false.
$question_id = 11406;
$query = $db->prepare("SELECT q.question_attempts_permitted, q.question_range, a.answer_text, r.attempt_count
FROM checkup_questions q, checkup_answers a, user_responses r
WHERE a.question_id=:question_id AND q.question_id=:question_id AND r.question_id=:question_id");
$query->bindValue(':question_id', $question_id, PDO::PARAM_INT);
$query->execute();
However, if I inject the question_id directly the query returns the desired result.
$query = $db->prepare("SELECT q.question_attempts_permitted, q.question_range, a.answer_text, r.attempt_count
FROM checkup_questions q, checkup_answers a, user_responses r
WHERE a.question_id=11406 AND q.question_id=11406 AND r.question_id=11406");
$query->execute();
Is there some limitation with the bindValue interface that causes the first query to fail while the second one returns as expected?
Query text should be rewritten using JOIN:
$query = $db->prepare("
SELECT q.question_attempts_permitted, q.question_range, a.answer_text, r.attempt_count
FROM checkup_questions q
JOIN checkup_answers a ON a.question_id = q.question_id
JOIN user_responses r ON r.question_id = q.question_id
WHERE q.question_id=:question_id
");
// you can provide placeholder without `:`
$query->bindValue('question_id', $question_id, PDO::PARAM_INT);
$query->execute();
Here you have only one placeholder.

How to fetch results from two tables? (MySQLi)

How do I retrieve results from two tables in MySQLi using the object oriented way?
I am trying to fetch user information for $stmt2 from $stmt. $stmt loads perfectly but $stmt2 doesn't because it isn't getting the results.
Here's the code for it:
<?php
if ($stmt = $conn->prepare('SELECT `id`, `kills` FROM `rp_stats` ORDER BY `kills` DESC LIMIT 6'))
{
$stmt->execute();
$stmt->bind_result($id, $kills);
while($stmt->fetch())
{
if ($stmt2 = $conn->prepare("SELECT `id`, `username`, `look`, `online` FROM `users` WHERE `id` = ?"))
{
$stmt2->bind_param("i", $id);
$stmt2->execute();
$stmt2->bind_result($id, $username, $look, $online);
$user = $stmt2->get_result();
}
global $stmt2;
echo '<div class="leaderboardWrap">
<div class="userAvatar" style="float: left;width: 50px;display: inline-block;height: 50px;background-image: url(\'https://www.habbo.nl/habbo-imaging/avatarimage?figure='. $look . '&size=m&headonly=1\');"></div>
<div class="leaderboardContainer">
<p style="padding-top: 6px;"><span class="username-rainbow"><a ng-click="progress()" href="/user/' . $username . '">' . $username . '</a></span></p>
<p style="margin-top: -9px;"><i>$' . formatWithSuffix($credits) . ' cash</i></p>
</div>
</div>';
}
$stmt->close();
}
?>
I want it to show 6 different users based on the user stat as the left image shows, but instead, I am getting the right image.
Try to use inner join in database to minimize fetch process of data:
SELECT `id`, `kills` FROM `rp_stats`
INNER JOIN users ON rp_stats.id = user.id
ORDER BY `kills` DESC LIMIT 6
You're using same column names in different tables, so a join conflicts by default. That's why you must use aliases, like so:
SELECT s.id, s.kills, u.username
FROM rp_stats s
INNER JOIN users u ON s.user_id = u.id
ORDER BY s.kills DESC LIMIT 6
Note! that I use user_id. This is the foreign key (reference) from rp_stats to users. I mean it's not correct to compare users.id with rp_stats.id. Using this construction, a user can always have max. 1 stat. You generate more flexibility to user a user_id column, which references to the user table.
"SELECT RS.`id`, RS.`kills`, US.`id`, US.`username`, US.`look`, US.`online` FROM rp_stats RS, users US WHERE US.`id`=RS.`id` ORDER BY RS.`kills` DESC LIMIT 6";
A normalized query could help out.

php mysql select something and get columns from other tables

I'm using prepared statements and I need to "select" other table, apart from these two, to get data but I get this:
Fatal error: Call to a member function bind_param() on a non-object in C:\xampp\htdocs\views\user\referral.php on line 16
If I add in SELECT table1.* , table.* , "theothertable.*"
$stmt = $mysqli->prepare("SELECT friends.*, rc_usuario.* // or just *
FROM friends
INNER JOIN rc_usuario ON rc_usuario.id = friends.friendID
WHERE friends.userID = ?");
$stmt->bind_param('s', $connectedUserID);
This is working fine, I get what i need, but I also need to get data from another table and I can't make other select because i need it all in a while to print all the data together.
The question is, can I SELECT something like that from 2 tables and also get data from other table/s?
Thank YOU!
EDIT: Add the new statement:
if ($stmt = $mysqli->prepare("SELECT friends.*, members.*, account_type.*
FROM friends
INNER JOIN members ON members.id = friends.friendID
INNER JOIN account_type ON account_type.name = members.acc_type
WHERE friends.userID = ? AND members.acc_type = ?")) {
$stmt->bind_param('is', $connectedUserID, $connectedAcc_type);
$stmt->execute();
} else echo $mysqli->error;
You can join more tables by using another INNER JOIN, like as follows;
INNER JOIN rc_usuario ON rc_usuario.id = friends.friendID
INNER JOIN rc_another ON rc_another.col = friends.coljoin
Just make sure you select all the columns you want in the joined table.
It might also help to run your prepare statement in an if, like this;
if($stmt = $mysqli->prepare("SELECT ...")) { // ... where the rest of your query is
$stmt->bind_param('s', $connectedUserID);
$stmt->execute();
}
else {
echo $mysqli->error;
}
which will give you an idea of any problems with the SQL syntax.
Hope this helps.

MySQLi , declare variable and using math to count a median

I am trying to do some math in this SQL query. I'm not used to this syntax. Trying to count a median for line 3 in the query.
-?- = Can I put a variable here?
-??- = Can I make this line a variable some how?
This is the code I have done:
if(!isset($_SESSION["username"])):
$sql_art_sum = "SELECT (SELECT count(*) FROM post WHERE user_id = ?), **-?-**
(SELECT count(*) FROM comment),
(SELECT count(*)/ **-??-** FROM comment)";
if($stmt = $mysqli->prepare($sql_art_sum)) {
$stmt->bind_param('i', $_SESSION['id']);
$stmt->execute();
$stmt->bind_result($art_sum, $comment_sum, $comment_median);
$stmt->fetch();
$stmt->close();
}
When creating new variables in mysql you need to use 'AS' so for example:
SELECT x, y,
(SELECT SUM(x) - sum(y)
FROM tablename
WHERE b <= c
) as z
FROM tablename
Hope this is the answer you are searching for

PHP: output count()

How do i work with the COUNT()
$sql = $connect->prepare("SELECT COUNT() FROM discos_events e INNER JOIN discos_events_guests eg ON (e.ID = eg.eID) INNER JOIN users u ON (eg.uID = u.id) WHERE e.dID =:id");
$sql->bindValue(":id", $cID);
$sql->execute();
...then what? echo $sql["count"]; ? to output the count?
You need an alias name for your COUNT() column:
$sql = $connect->prepare("SELECT COUNT() AS num_events FROM discos_events e INNER JOIN discos_events_guests eg ON (e.ID = eg.eID) INNER JOIN users u ON (eg.uID = u.id) WHERE e.dID =:id");
$sql->bindValue(":id", $cID);
// Fetch the results and then access the alias
$sql->execute();
$result = $sql->fetch();
echo $result['num_events'];
you need to execute() the query, so:
$result = $sql->execute(array('id' => $cId)); // just to illustrate that you can use this instead of bindParam
if ($result) {
$row = $sql->fetch();
}
after execute, you have to store_result() and fetch()
As #Michael suggests, you may alias the count(), to get it in more reatable form.
Your query needs to assign the count value to a name, like so:
SELECT COUNT() n FROM discos_events ...
Then you can reference the name n in your PHP array:
echo $sql["n"];
You can, of course, call it 'count' or any other name you prefer, but be careful of using names which are reserved words in SQL (such as 'count'). If you want to give it a reserved name, you need to enclose it in backtick characters so that SQL recognises that it's a name you want to use rather than its own reserved word.

Categories