How to first get different related values from different SQL tables (PHP) - php

I am triig to fill options list. I have 2 tables USERS and STREAMS I vant to get all streams and get names of users assigned to that streams.
Users consists of username and id
Streams consists of id, userID, streamID
I try such code:
<?php
global $connection;
$query = "SELECT *
FROM streams ";
$streams_set = mysql_query($query, $connection);
confirm_query($streams_set);
$streams_count = mysql_num_rows($streams_set);
while ($row = mysql_fetch_array($streams_set)){
$userid = $row['userID'];
global $connection;
$query2 = "SELECT email, username ";
$query2 .= "FROM users ";
$query2 .= "WHERE id = '{$userid}' ";
$qs = mysql_query($query2, $connection);
confirm_query($qs);
$found_user = mysql_fetch_array($qs);
echo ' <option value="'.$row['streamID'].'">'.$row['userID'].$found_user.'</option> ';
}
?>
But it does not return USER names from DB=( So what shall I do to this code to see usernames as "options" text?

You can do this with one query containing a JOIN on streams.userID=users.id
$query = "
SELECT
s.streamId,
s.userId,
u.username
FROM
streams as s
JOIN
users as u
ON
s.userId=u.id
";
$result = mysql_query($query, $connection);
confirm_query($result);
echo '<option value="">Debug: #rows=', mysql_num_rows($row), '"</option>';
while ( false!==($row=mysql_fetch_array($result)) ) {
sprintf('<option value="%s">id:%s name:%s</option>',
$row['streamID'], // you probably should apply htmlspecialchars()
$row['userID'], // on these two, too.
htmlspecialchars($row['username'])
);
}

Related

PHP: use an array in a select where condition [duplicate]

This question already has answers here:
Passing an array to a query using a WHERE clause
(17 answers)
Closed 11 months ago.
I'm trying to query a MySQL database using an array but I'm having trouble!
I have a table called clients, I want to be able to select 'name' from all rows whose 'sector' column is equal to $sectorlink.
I then want to put all the names into an array so I can perform my next query: select all rows from another table whose 'client' column is equal to one of the names returned from the first query. I'm doing something wrong because it returns a fatal SQL error. I'm getting confused with all the variables!
$sectorlink and $connection are the only variables that are defined outside of this code
Any suggestions?
$query1 = "SELECT name FROM clients WHERE sector = '$sectorlink'";
$clientresult = mysql_query($query1, $connection) or trigger_error("SQL", E_USER_ERROR);
while($row = mysql_fetch_array($clientresult)){
foreach($row AS $key => $value){$temp[] = '"'.$value.'"';}
$thelist = implode(",",$temp);
$query = "SELECT count(*) FROM studies WHERE client IN ($row) ORDER BY (date) desc";
$result = mysql_query($query, $connection) or trigger_error("SQL", E_USER_ERROR);
}
The second query should use $thelist not $row, and it should be outside of the while loop. The foreach loop is unnecessary when processing a single row. You can access the name in $row with a simple $row[0]. Something like this (untested):
$query1 = "SELECT name FROM clients WHERE sector = '$sectorlink'";
$clientresult = mysql_query($query1, $connection) or trigger_error("SQL", E_USER_ERROR);
while($row = mysql_fetch_array($clientresult)){
$temp[] = '"'.$row[0].'"';
}
$thelist = implode(",",$temp);
$query = "SELECT count(*) FROM studies WHERE client IN ($thelist) ORDER BY (date) desc";
$result = mysql_query($query, $connection) or trigger_error("SQL", E_USER_ERROR);
Caution: Please be aware that your code is highly vulnerable to SQL injection attacks. It's fine for testing or internal development but if this code is going to be running the Fort Knox web site you're going to want to fix it up quite a bit. Just an FYI. :-)
Try This:
$query1 = "SELECT name FROM clients WHERE sector = '$sectorlink'";
$clientresult = mysql_query($query1, $connection) or trigger_error("SQL", E_USER_ERROR);
while($row = mysql_fetch_array($clientresult)){
$client = $row['name'];
$query = "SELECT * FROM studies WHERE client='$client' ORDER BY date DESC";
$result = mysql_query($query, $connection) or trigger_error("SQL", E_USER_ERROR);
/* echo results here */
}
Couple of things. First you have an unnecessary loop there. Try:
while (list($name) = mysql_fetch_row($clientresult)) {
$temp[] = $name;
}
To build your temporary array.
Second, the parts of the IN clause are strings, so when you implode, you'll need to enclose each value in quotes:
$thelist = "'". implode("','", $temp) . "'";
Lastly, in your query you are passing $row to the IN clause, you should be passing $thelist:
$query = "SELECT count(*) FROM studies WHERE client IN ($thelist) ORDER BY date desc";
$result = mysql_query($query, $connection) or trigger_error("SQL", E_USER_ERROR);
So altogether:
$query1 = "SELECT name FROM clients WHERE sector = '$sectorlink'";
$clientresult = mysql_query($query1, $connection) or trigger_error("SQL", E_USER_ERROR);
while (list($name) = mysql_fetch_row($clientresult)) {
$temp[] = $name;
}
$thelist = "'". implode("','", $temp) . "'";
$query = "SELECT count(*) FROM studies WHERE client IN ($thelist) ORDER BY date desc";
$result = mysql_query($query, $connection) or trigger_error("SQL", E_USER_ERROR);
I expect you'd be better off doing this in one query with a join:
$query = "SELECT COUNT(*) FROM `studies` INNER JOIN `clients` on studies.client = clients.name WHERE clients.sector = '$sectorlink' ORDER BY studies.date DESC";
$result = mysql_query($query, $connection) or trigger_error("SQL", E_USER_ERROR);

Loop through two while arrays

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 );

Displaying based on Results in Mysql Query

I have an orders table in mysql and in that for some orders I set particular order status like 'review'.
I want to setup a way if any order placed by a particular customer(first and last name) for whom i have previously set order status as 'review' to display a warning in the list.
$sql = "select * from order where firstname = ".$firstname." AND lastname = ".$lastname." AND order_status = 'review';";
$SQLresult = mysql_query("$sql", $DBcon_MySQL);
while($row = mysql_fetch_array($SQLresult)) {
foreach($row as $row){
$result = "warning!";
echo $result;
}
}
The above code does not display anything. please let me know how to fix this.
[EDIT After Applying Answer]
This is how i am using it.
<td width="200">
<?
$sql = "select * from cust_order where firstname = '$firstname' AND lastname = '$lastname' AND order_status = 'review'";
$SQLResult = mysql_query("$sql", $DBcon_MySQL);
while($row = mysql_fetch_array($SQLResult )) {
//$result;
foreach($row as $row ){
//$result="";
$result = "Warning!";
}
?>
<p><? echo $result;?></p>
<?} ?>
</td>
How should i insert a check that it should display warning only once No matter how many orders from single customer are marked as review, display warning only once?
try this,
$sql = "SELECT
*
FROM
`order`
WHERE
firstname = '$firstname' AND lastname = '$lastname' AND
order_status = 'review' LIMIT 1";
$SQLresult = mysql_query($sql, $DBcon_MySQL);
while($row = mysql_fetch_array($SQLresult)) {
foreach($row as $row){
$result = "warning!";
echo $result;
}
}
Please be informed that mysql functions are deprecated and not recommended. USE MySQLi or PDO instead. have a reference from following queries.
http://php.net/manual/en/book.mysqli.php
http://php.net/manual/en/book.pdo.php

update table for multiple users

I am looking to count the number of times 'yes' in present for a user in a table, then post the result into anther table for that same user. Both tables have the username. I would like this done for each user. I have the following but it is not working.
$sql = $item_count = "SELECT SUM(if(strike='yes',1,0)) AS strike_total FROM weekpicks WHERE username = 'username'";
// execute SQL query and get result
$sql_result = mysql_query($sql) or die (mysql_error());
if (!$sql_result) {
echo "Something has gone wrong!";
}
else {
//loop through record and get values
while ($row = mysql_fetch_array($sql_result)) {
$item_result = ($row = #mysql_query($item_count)) or die(mysql_error());
$strike_total = ($row = #mysql_result($item_result,"strike_total"));
$strikes = ($row = $strike_total ['strike_total']);
$username = $row["username"];
// the following will insert number of strikes into table for each user.
$sql = "UPDATE authorize SET strikes = '($strikes)' WHERE username='$username'";
//mysql_query(" UPDATE authorize SET " . "strikes = '" . ($strikes) . "' WHERE username='$username' ");
$result = mysql_query($sql) or die (mysql_error());
Just one query should be enough
Update for single user..
UPDATE authorize SET strikes = (select count(*) from weekpicks WHERE username = '$username' and strike='yes') WHERE username='$username';
For bulk update all users
UPDATE authorize as A SET strikes = (select count(*) from weekpicks B WHERE strike='yes' and A.username=B.username group by B.username)
Isn't that simple.

Select after and before Insert results on same in PHP with MySql

Good evening,
I have a problem when i select some data from table. So, first, i call a select that return the last row of the table. After this, i insert new data in that table, and now call that select again and give me the same result of the first select. What i want is, when i insert, the last select returns the data inserted. If i execute another select already give me the last value inserted. My code is written in PHP and i use the interface mysqli.
I already use transactions, refresh, set the cahce of mysqli to 0 in php.ini.
Thanks.
EDITED 2: I make a test:
<?php
include 'conf.php';
$query="INSERT INTO assinante.comentarios (id_cmnt,id_user,comentario,now_data) values (null,4,'coiso',NOW());";
$res= mysqli_query($link,$query);
$query="SELECT * FROM $db_assin.comentarios;";
$res= mysqli_query($link,$query);
$linha = mysqli_fetch_assoc($res);
print_r($linha);
$query="INSERT INTO assinante.comentarios (id_cmnt,id_user,comentario,now_data) values (null,3,'ola',NOW());";
$res= mysqli_query($link,$query);
$query="SELECT * FROM $db_assin.comentarios;";
$res= mysqli_query($link,$query);
$linha = mysqli_fetch_assoc($res);
print_r($linha);
And it return:
Array ( [id_cmnt] => 29 [id_user] => 3 [comentario] => coiso [now_data] => 2014-01-29 02:10:24 ) Array ( [id_cmnt] => 29 [id_user] => 3 [comentario] => coiso [now_data] => 2014-01-29 02:10:24 )
It seems that save in buffer or something like this. If you can help i appreciate.
EDITED: The code
function getComentarios(){
include 'conf.php';
$query =
" SELECT utili.username, cmnt.comentario , cmnt.now_data , cmnt.id_cmnt
FROM ".$db_assin.".comentarios cmnt, ".$db_assin.".utilizadores utili
WHERE utili.id_user = cmnt.id_user
ORDER BY cmnt.id_cmnt DESC
LIMIT 1;";
$resultado = mysqli_query($link,$query);
if($resultado){
$linha = mysqli_fetch_array($resultado);
$json = json_encode($linha);
echo $json;
}
else{
echo mysqli_error($link);
}
mysqli_free_result($resultado);
}
function ins_comment($id_user,$comment){
include 'conf.php';
$data = date('Y-m-d H:i:s');
mysqli_autocommit($link, FALSE);
mysqli_query($link,"BEGIN");
$query_ins = "INSERT INTO ".$db_assin.".comentarios (id_cmnt,id_user,comentario,now_data) "
. "values (null,$id_user,'$comment',NOW());";
if (!$res_ins = mysqli_query($link,$query_ins)){
echo mysqli_error ($link);
mysqli_rollback($link);
}
else{
mysqli_commit($link);
}
mysqli_autocommit($link, TRUE);
mysqli_refresh($link, MYSQLI_REFRESH_HOSTS);
return $res_ins;
}
function comentar(){
include 'conf.php';
$user_c=$_POST['user_c'];
$comment=$_POST['comment'];
$query = "SELECT u.id_user "
. "FROM ".$db_assin.".utilizadores u "
. "WHERE u.username='$user_c';";
if($resultado = mysqli_query($link, $query)){
if (($linha = mysqli_fetch_array($resultado, MYSQLI_ASSOC)) != NULL){
$id_user=$linha['id_user'];
$query = "SELECT c.comentario "
. "FROM ".$db_assin.".utilizadores u, ".$db_assin.".comentarios c "
. "WHERE u.id_user=c.id_user AND u.id_user='$id_user';";
if($resultado = mysqli_query($link, $query)){
if (($linha = mysqli_fetch_array($resultado, MYSQLI_ASSOC)) != NULL){
if(strcmp($linha['comentario'],$comment)!=0){
if($res=ins_comment($id_user, $comment))
echo "Comentário submetido";
}
else{
echo "O mesmo comentário não pode ser submetido duas vezes!";
}
}
else{
if($res=ins_comment($id_user, $comment))
echo "Comentário submetido";
}
}
}
mysqli_free_result($resultado);
}
else echo mysqli_error($link);
}
Your second query doesn't have an order by. Try
SELECT c.comentario
FROM ".$db_assin.".utilizadores u, ".$db_assin.".comentarios c "
WHERE u.id_user=c.id_user AND u.id_user='$id_user'
ORDER BY c.id_cmnt DESC
LIMIT 1;
By the way, you should learn to use explicit join syntax. This query is better written as:
SELECT c.comentario
FROM ".$db_assin.".utilizadores u join
".$db_assin.".comentarios c
on u.id_user = c.id_user
WHERE u.id_user = '$id_user'
ORDER BY c.id_cmnt DESC
LIMIT 1;

Categories