I'm trying to use checkboxes for multiple sql query with SELECT.
I have 3 tables, one table for groups one for users and one to connect the user to different groups called groupreluser. Based on what groups are checked, I want it to print out the phonenumber of each user that are a member of those groups.
The checkboxes are created based on the content of the table groups
<form method="post">
<?php
$sql = "SELECT * FROM groups WHERE groupname LIKE '%minor%'";
$result = $conn->query($sql);
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
echo '<input type="checkbox" name="checked[]" value="'.$row['group_id'].'">'
. $row['groupname'] . '</br>';
}
}
?>
<input type="submit" name="submit" value="submit">
</form>
Code with the sql query to get the phonenumbers.
if(isset($_POST['submit'])){
$check = $_POST['checked'];
if(!empty($check)){
foreach($check as $sel){
$sel = mysqli_real_escape_string($conn, $sel);
$sql = "
SELECT
groups.group_id,
groups.groupname,
groupreluser.user_id,
groupreluser.group_id,
users.user_id,
users.name,
users.phone
FROM
groupreluser
JOIN
groups
ON
groups.group_id = groupreluser.group_id
JOIN
users
ON
users.user_id = groupreluser.user_id
WHERE
groups.group_id = '$sel'
";
$res = $conn->query($sql);
if($res->num_rows > 0){
while($row = $res->fetch_assoc()){
echo $row['phone'] . '</br>';
}
}
}
}
}
It works fine as long as I dont use the checkboxes but adds the group_id manually in the SELECT statement. Any idea of why this isn't working? Am I missing someting? Dont know if this is the best way to do it though...
Let me know if this is unclear, and I'll try to explain it better
This line probably doesn't work:
$check = mysqli_real_escape_string($conn, $_POST['checked']);
$_POST['checked'] is an array. So you have do the line above for each item in the array.
Your $_POST['submit'] is array so directly passing it to mysqli_real_escape_string won't work. But this approach will do the work:
if(isset($_POST['submit'])){
$check = $_POST['check'];
if(!empty($check)){
foreach($check as $sel) {
$sel = mysqli_real_escape_string($conn, $sel);
$sql = "
SELECT
groups.group_id,
groups.groupname,
groupreluser.user_id,
groupreluser.group_id,
users.user_id,
users.name,
users.phone
FROM
groupreluser
JOIN
groups
ON
groups.group_id = groupreluser.group_id
JOIN
users
ON
users.user_id = groupreluser.user_id
WHERE
groups.group_id = '$sel'
";
$res = $conn->query($sql);
...........
Related
I'm having an issue of retrieving values from two different tables. Here's the code so far:
$result = mysqli_query($conn,"SELECT * FROM articles");
$num = mysqli_num_rows($result);
while ($row = mysqli_fetch_array($result)) {
$uid=$row['_uid'];
$result2 = mysqli_query($conn, "SELECT _username FROM users WHERE _id = '$uid' ";
$num2 = mysqli_num_rows($result2);
while ($row2 = mysqli_fetch_array($result2)) {
$username = $row2['_username'];
}
$divtext='<h3>'.$row['_posttype'].'</h3> <h2>'.$username.' </h2>';
}
I've been reading that I should preform this while inside a while with multiple query, also found on w3 that you could directly assign a value to a variable directly using:
"SELECT _username INTO $username FROM users WHERE _id = '$uid' LIMIT 1";
But this works in SQL inside myadmin, in a php I can't find how to cast it.
I have also replace the fetch_row for fetch_assoc and still nothing, im struggling for two days already with this.
you could select al the value using a single query
SELECT a._uid , a._posttype, u._username
FROM articles a
INNER JOIN users u on a._uid = u._id
..
$result = mysqli_query($conn,
"SELECT a._uid , a._posttype, u._username
FROM articles a
INNER JOIN users u on a._uid = u._id");
$num = mysqli_num_rows($result);
while ($row = mysqli_fetch_array($result)) {
$divtext='<h3>'.$row['_posttype'].'</h3> <h2>'.$username.' </h2>';
}
$echo $divtext;
I am making this post system with like button and count for a social networking site.
My end goal is to loop through these two sets of results together. So that the like counts goes with the individual posts as they loop. The posts and likes are in desc order. Everything matches except I can't get these while fetch results to loop together.
Post loop
<table class="postborder">
<?php
$query1 = "SELECT * FROM tbl_images ORDER BY id DESC";
$result = mysqli_query($connect, $query1);
while($row = mysqli_fetch_array($result)) {
?>
<div id="newpost">
<tr>
<td id="userpost"><?php echo $row['username']; ?> </td>
</tr>
<tr>
<td>
<hr id="hrline">
<img id="newimgpost" src="data:image/jpeg;base64,<?php echo base64_encode($row['name']); ?>" height="500" width="500" class="img-thumnail" />
</td>
<tr>
<td id="textpost">
<?php echo $row['textpost']; ?>
</td>
</tr>
<tr>
<td id="likebutton">
<?php } ?>
</div>
</table>
Like count loop
<?php
//index.php
//session_start();
//SESSION['userid'] = (int)3;
$connect = mysqli_connect("localhost", "root", "", "snazzer");
$query2 = "
SELECT tbl_images.id, tbl_images.textpost,
COUNT(likes.id) as likes,
GROUP_CONCAT(users.name separator '|') as liked
FROM
tbl_images
LEFT JOIN likes
ON likes.postid = tbl_images.id
LEFT JOIN users
ON likes.userid = users.userid
GROUP BY tbl_images.id
ORDER BY id DESC
";
$result2 = mysqli_query($connect, $query2);
if (!$result2) {
printf("Error: %s\n", mysqli_error($connect));
exit();
}
while($row = mysqli_fetch_array($result2))
{
echo '<h3>'.$row["textpost"].'</h3>';
echo '
LIKE';
echo '<p>'.$row["likes"].' People like this</p>';
if(count($row["liked"]))
{
$liked = explode("|", $row["liked"]);
echo '<ul>';
foreach($liked as $like)
{
echo '<li>'.$like.'</li>';
}
echo '</ul>';
}
}
if(isset($_GET["type"], $_GET["id"]))
{
$type = $_GET["type"];
$id = (int)$_GET["id"];
if($type == "postid")
{
$query = "
INSERT INTO likes (userid, postid)
SELECT {$_SESSION['userid']}, {$id} FROM tbl_images
WHERE EXISTS(
SELECT id FROM tbl_images WHERE id = {$id}) AND
NOT EXISTS(
SELECT id FROM likes WHERE userid = {$_SESSION['userid']} AND postid = {$id})
LIMIT 1
";
mysqli_query($connect, $query);
header("location:profile.php");
}
}
?>
I believe you could run two queries together. It's fairly simple; just separate each query with semicolon:
$query = "SELECT * FROM tbl_images ORDER BY id DESC;
SELECT tbl_images.id, tbl_images.textpost, COUNT(likes.id) as likes, GROUP_CONCAT(users.name separator '|') as liked FROM tbl_images LEFT JOIN likes ON likes.postid = tbl_images.id LEFT JOIN users ON likes.userid = users.userid GROUP BY tbl_images.id ORDER BY id DESC";
Or separate the variable by incrementing values, you can read their documentation which explains it here.
$query = "SELECT * FROM tbl_images ORDER BY id DESC";
$query .= "SELECT tbl_images.id, tbl_images.textpost, COUNT(likes.id) as likes, GROUP_CONCAT(users.name separator '|') as liked FROM tbl_images LEFT JOIN likes ON likes.postid = tbl_images.id LEFT JOIN users ON likes.userid = users.userid GROUP BY tbl_images.id ORDER BY id DESC";
Then run your code as you normally would except you change mysqli_query to mysqli_multi_query:
$result = mysqli_multi_query( $connect, $query );
while($row = mysqli_fetch_array( $result )) {
//... code your table here ...//
}
You can also the Object-Oriented method which works pretty well:
$result = $connect->multi_query( $query );
But of course both methods should work fine. Do keep in mind, you may be vulnerable to SQL Injections with mysqli_multi_query. This is PHP's official warning:
Security considerations
The API functions mysqli_query() and mysqli_real_query() do not set a connection flag necessary for activating multi queries in the server. An extra API call is used for multiple statements to reduce the likeliness of accidental SQL injection attacks. An attacker may try to add statements such as ; DROP DATABASE mysql or ; SELECT SLEEP(999). If the attacker succeeds in adding SQL to the statement string but mysqli_multi_query is not used, the server will not execute the second, injected and malicious SQL statement.
Considerations
You could always save both results from your while loop in an array and run them in a foreach loop or have them output individually as $array['key']. Which would be a simple workaround to your queries:
<?php
// first query
$query1 = "SELECT * FROM tbl_images ORDER BY id DESC";
$result = mysqli_query($connect, $query1);
while($row = mysqli_fetch_array($result)) {
$array1[] = $row;
}
// second query
$query2 = "
SELECT tbl_images.id, tbl_images.textpost,
COUNT(likes.id) as likes,
GROUP_CONCAT(users.name separator '|') as liked
FROM
tbl_images
LEFT JOIN likes
ON likes.postid = tbl_images.id
LEFT JOIN users
ON likes.userid = users.userid
GROUP BY tbl_images.id
ORDER BY id DESC
";
$result2 = mysqli_query($connect, $query2);
while($row = mysqli_fetch_array($result2)) {
$array2[] = $row;
}
Once you have those records setup you can now use $array1 and $array2 to setup your table.
To get their keys and setup you can use print_r or var_dump and you will be able to see key => value pairs:
print_r( $array1 );
echo '<br />';
print_r( $array2 );
I have to tables in one database.
users
user_activate
I have to variables in php
$username = foo;
$key = jas823k123ksd34324;
Now I want to select from the table users the attribute user_id where user_username == $username
I do this with this statement
$sql = "SELECT user_id FROM users WHERE user_username = '$username'";
$result = mysqli_query($db, $sql);
while($row = mysqli_fetch_assoc($result)){
$user_id = $row['user_id'];
}
Now I want to select from the table user_activate the attribute user_activate_key where user_activate_key == $key;
For this I use this statement:
$sql2 = "SELECT user_activate_key FROM user_activate WHERE user_activate_key = '$key'";
$result2 = mysqli_query($db, $sql2);
while($row = mysqli_fetch_assoc($result)){
$user_key = row['user_activate_key'];
}
Can I do both statements in one statement?
As you've written it, two seperate queries is the correct way to do it. But I suspect that there's some kind of relationship between users and user_activate that might make what you're asking for make sense. Assuming that a user_activate_key is tied to a specific user_id, you could do something like the following:
select users.user_id, ua.user_activate_key
from users u
left join user_activate ua
on u.user_id = ua.user_id
and ua.user_activate_key = '$key'
where u.username = '$username'
The LEFT JOIN means that the user will be shown even if there isn't a matching user_activate_key record.
I want to retrieve data from multiple tables using dot operator/join where arguments are passed from an HTML/PHP form.
HTML CODE
<input name="rollno" type="text" placeholder="Roll Number" required>
<input name="submit_view_details" type="submit" value="Proceed">
PHP CODE
if(isset($_POST['submit_view_details']))
{
$rollno = (int) $_POST['rollno'];
$query = "select * from table1, table2 where table1.{$rollno}=table2.{$rollno}";
$result=mysqli_query($connection,$query);
}
In the browser if enter the input 1 and echo this query then it looks like follows:
select * from table1, table2 where table1.1=table2.1
and no row is fetched despite of having data in the table(s).
it only works if the query looks like follows:
select * from table1,table2 where table1.rollno=table2.rollno
However, in that case it fetches all the rows but I need only the row of the rollno that user entered in the above mentioned form.
I am just not able to work this out. Help would be much appreciated. Thanks!
Use the AND keyword to specify the rollno.
SELECT * FROM table1, table2 WHERE table1.rollno = table2.rollno
AND table1.rollno = {$rollno};
You could probably use the keyword JOIN instead like this :
SELECT * FROM table1 NATURAL JOIN table2
WHERE rollno = {$rollno};
You need joins
take a reference of joins from here,
i am sure it will help
http://www.tutorialspoint.com/mysql/mysql-using-joins.htm
You should use join like this
$query = "SELECT tbl1.*, tbl2.*
FROM tbl1
INNER JOIN tbl2 ON tbl1.id = tbl2.id
WHERE tbl1.column = value ";
foreach ($pieces_2 AS $value) {
$pieces_3[] ="(CONCAT_WS('|',$presql2) like '%$value%')"; //concat all columns from one table
}
$serch_jyouken = implode(" and ",$pieces_3); // for multiple keywords
$result1 = mysqli_query($connection, "select p.p_no from pfr_data p where (" .$serch_jyouken .")");
$res1 = array();
while($r1 = mysqli_fetch_array($result1){
$res1[] = $r1['p_no'] ; //fetch primary key from table and store it into array
}
foreach ($pieces_2 AS $value) {
$pieces_4[] ="(CONCAT_WS('|',$presql3) like '%$value%')"; // same as above
}
$serch_jyouken1 = implode(" and ",$pieces_4);
$result2 = mysqli_query($connection, "select p2.p_no from pfr_mod_inform p2 where (" .$serch_jyouken1 .")" );
$res2 = array();
while($r2 = mysqli_fetch_array($result2)){
$res2[] = $r2['p_no'];
}
$res_mrg = array_merge($res1 , $res2); //merge array
$result = implode("','",$res_mrg ); // array to sring
$sql5 = $presql ." from pfr_data p where p.p_no in ('$result') order by p.section_p,p.status,p.no";
I need to create a friend system, but my loop always skips the first match and sometimes it prints copies of the same name
$result = mysql_query("SELECT * FROM tbusers INNER JOIN tbfriends ON tbusers.id = tbfriends.username_id");
while($row = mysql_fetch_array($result))
{
if ($row['username_id'] == 1)//the 1 will be a variable, username_id is in friends
$count = $row['friendname'];//friendname is in friends
if ($row['id'] == $count)//id is in users
echo $row['username'];//username is in users
}
Can someone see what my problem is ?
2 things:
if ($row['username_id'] == 1)
you should put that in your sql:
$result = mysql_query("SELECT username, friendname FROM tbusers INNER JOIN tbfriends ON tbusers.id = tbfriends.username_id where tbusers.id = ".$yourVariable);
In your query, user and friend are linked, and can only be equal.
Now, this:
$count = $row['friendname'];//friendname is in friends
if ($row['id'] == $count)//id is in users
is equal to
if ( $row['id'] == $row['friendname'] )
this sounds plain wrong. You compare a numerical id with a name. Moreover, your sql query already retrives all friends from users. In the version I showed here, it retrieves only friends of the user you are interested in.
finally, you print (echo) the name of the user, not of the friend. In my opinion the following code will do what you want:
$result = mysql_query("SELECT friendname FROM tbfriends WHERE username_id = ".$yourUserVariable);
while($row = mysql_fetch_array($result))
{
echo $row['friendname']; // or better: echo $row['friendname'], '<br>';
}
edit: after comment...
so if ( $row['id'] == $row['friendname'] ) means the user is his own friend. can that happen?
this code shall print what you want, friend names.
/*
$result = mysql_query("
SELECT username as friend_name,
friendname as friend_id,
username_id as user_id
FROM tbusers INNER JOIN tbfriends ON tbusers.id = tbfriends.username_id
WHERE tbusers.id = ".$yourVariable);
*/
$result = mysql_query("
SELECT username as friend_name,
friendname as friend_id,
username_id as user_id
FROM tbusers INNER JOIN tbfriends ON tbusers.id = tbfriends.friendname
WHERE tbfriends.username_id = ".$yourVariable);
while($row = mysql_fetch_array($result))
{
echo $row['friend_name']; // or better: echo $row['friend_name'], '<br>';
}