inserting array into query then looping through results into new query - php

basically this is on the end of a dynamic form where the user can add multiple users of however many they want to a group, so i storte all the inputs in an array user[].
I want to query the array values and gain the userid for each then run another query with the user ids, inserting the userids into another table.
I am a beginner so I am getting lost in this. I looked at trying to use a for each method but couldnt get that working so now im trying a while.
here is my code ive been playing around with, i imagine its completely wrong :(
$query = 'SELECT * FROM users_tb WHERE student_number IN('.implode(',', $array).')';
mysql_query($query) or die(mysql_error());
$result=mysql_query($query);
while($row = mysql_fetch_assoc($result))
{
$sql = "INSERT INTO group_assocation_tb (group_id, user_id) VALUES('$group','$row['user_id']')";
mysql_query($sql) or die(mysql_error());
mysql_close();
}
please help? :D
regards

You want to use INSERT SELECT:
INSERT INTO group_association (group_id, user_id)
SELECT ' . $group_id . ', user_id
FROM users_tb WHERE student_number IN('.implode(',', $array).')

You have some extra quotes in the INSERT query, it should look like this:
$sql = "INSERT INTO group_assocation_tb (group_id, user_id) ".
"VALUES('$group','$row[user_id]')";
Other than that, it looks like it should work if $group is a group id.

Related

Can you do a "INSERT SELECT WHERE" between two tables?

So I've been trying to create a simple friend system. When you register, you get randomized numbers and chars of 8 in length. I save this number in a column to the user. I have been trying to insert the currently sessioned user(PHP), $SessionUser together with the friends' username, uidUsers using an "INSERT SELECT WHERE" statement, but something goes wrong. Heres something I have tried:
$sql = mysqli_query($conn, "INSERT into friends (uid1, uid2)
values($sessionUser, (SELECT uidUsers FROM users WHERE idFriendCode = $idFriendCode)");
Inside the table, friends, I have two columns, uid1 (the sessioned user/sender) and uid2 (the reciever, name of specified $idFriendCode). I want to insert the $sessionUser to the uid1 and whatever username (uidUsers) that matches with the $idFriendCode to the uid2. This does not seem to work and I don't know why. I imagine the problem is that I can't use a PHP variable like this.
I know that I don't use prepared statements. I have tried to implement it, but I think it's much harder than just using a basic mysqli_query().
You may phrase your insert as an INSERT INTO ... SELECT:
INSERT into friends (uid1, uid2)
SELECT $sessionUser, uidUsers
FROM users
WHERE idFriendCode = $idFriendCode;
Note that you should ideally be using a prepared statement here, so the above should look like:
INSERT into friends (uid1, uid2)
SELECT ?, uidUsers
FROM users
WHERE idFriendCode = ?;
Try having a new variable for select and use it in the insert query
example:
$select_qr='SELECT uidUsers FROM users WHERE idFriendCode = $idFriendCode'
$sql = mysqli_query($conn, "INSERT into friends (uid1, uid2)
values($sessionUser, $select_qr)");

Not all rows are inserted to table after performing select query on while loop - PHP / MYSQL

I'm new here on stackoverflow.
I'm performing a select query to populate the output I need. While it is fetching rows from query, every rows that has been fetched is I'm inserting them into a specific table. But however, the exact amount of rows that I need to achieve is 1,767 rows but after performing the query, 1759 was the output. I have 8 rows missing.
What's the problem with my code?
Here's my code:
$query2 = "SELECT trihadjustmentitems.AdjID AS `adjid1`, trihadjustment.Adj_ID AS `adjid2`,
trihadjustment.AdjToUnitID AS `adjtounitid`, trihadjustment.AdjDate AS `adjdate`, trihadjustmentitems.InvItemsID AS `invitemid`,
trihadjustmentitems.SlsItemsID AS `slsitemid`, trihadjustmentitems.RecipeID AS `recipeid`, trihadjustmentitems.Remark AS `remark`,
trihadjustmentitems.AdjQty AS `adjqty`,
trihadjustment.StockCenter_ID AS `stockcenterid1`, trihadjustmentitems.StockCenter_ID AS `stockcenterid2`
FROM trihadjustmentitems
INNER JOIN trihadjustment ON trihadjustmentitems.AdjID = trihadjustment.Adj_ID";
$result2 = mysqli_query($connection, $query2);
while($row2 = mysqli_fetch_array($result2))
{
$query3 = "INSERT INTO adjustments (adjid1, adjid2, adjtounitid, adjdate, invitemid, slsitemid, recipeid, remark, adjqty, stockcenterid1, stockcenterid2) VALUES ('$row2[adjid1]', '$row2[adjid2]', '$row2[adjtounitid]', '$row2[adjdate]', '$row2[invitemid]', '$row2[slsitemid]', '$row2[recipeid]', '$row2[remark]', '$row2[adjqty]', '$row2[stockcenterid1]', '$row2[stockcenterid2]')";
$result3 = mysqli_query($connection, $query3);
}
There's not enough information to determine that anything goes wrong at all. Your code, although dated, doesn't contain anything that can help anyone determine what's wrong, if anything is wrong. We can only trust you when it comes to numbers and that's not how IT works.
Your query is not needed at all. You can do what you're after without the while loop. Simply use INSERT INTO ... SELECT syntax.
I'll use your code to illustrate
$query = <<<EOF
INSERT INTO adjustments
(adjid1, adjid2, adjtounitid, adjdate, invitemid, slsitemid, recipeid, remark, adjqty, stockcenterid1, stockcenterid2)
SELECT
trihadjustmentitems.AdjID AS `adjid1`,
trihadjustment.Adj_ID AS `adjid2`,
trihadjustment.AdjToUnitID AS `adjtounitid`,
trihadjustment.AdjDate AS `adjdate`,
trihadjustmentitems.InvItemsID AS `invitemid`,
trihadjustmentitems.SlsItemsID AS `slsitemid`,
trihadjustmentitems.RecipeID AS `recipeid`,
trihadjustmentitems.Remark AS `remark`,
trihadjustmentitems.AdjQty AS `adjqty`,
trihadjustment.StockCenter_ID AS `stockcenterid1`,
trihadjustmentitems.StockCenter_ID AS `stockcenterid2`
FROM trihadjustmentitems
INNER JOIN trihadjustment ON trihadjustmentitems.AdjID = trihadjustment.Adj_ID
EOF;
$result = mysqli_query($query);
if(!result) {
echo 'An error occurred';
}
INSERT INTO tbl_name
(a,b,c)
VALUES
(1,2,3),
(4,5,6),
(7,8,9);
there is no need to run query in loop you can try this after loop complete
It don't seem to be a PHP problem.
The problem could be the INNER JOIN, you could use instead LEFT JOIN in order to extract all the record from trihadjustmentitems table.
I hope this help.
First, why $result1, $result2, $result3?... And the same with all vars.
Instead of while, you could use foreach() loop.
foreach($resultQuery as $result){
$insertQuery = "INSERT INTO adjustments...
}
use var_dump($result); if you don't know what its $result.
Make sure all the results have the same structure. Maybe you can't insert something in adjustment because the value is NULL. Check it.

MySQL selecting from two tables in the same query

I am trying to select everything from two different mysql tables. I imploded an array called friends so that I can select everything about the user's friends from both tables. Originally I wanted to perform one query on one table and then in a while loop a query on the other. But that didn't work. If you know I way I can nest while loops then please be sure to comment/answer this question.
Here's my code:
$friends = implode("','", $friends);
//implode the friends array for sql query
$sql = mysqli_query($con, "SELECT * FROM users, text_post WHERE username IN ('$friends')") or die(mysqli_error($con));
while ($row = mysqli_fetch_assoc($sql)) {
echo $row['last_name']. ' ' . $row['body'];
echo '<br><br>';
}
Note: $row['last_name'] is from the users table and $row['body'] is from the text_post table. I am receiving this error whenever I run my code Column 'username' in where clause is ambiguous
Please help me.
UPDATE:
I changed my query to: $sql = mysqli_query($con, "SELECT * FROM users, text_post WHERE users.username IN ('$friends')") or die(mysqli_error($con)); but now it echo's every match twice:
parker hello
parker hello
simms what is up
simms what is up
simms it's raining
simms it's raining
jorge potato
jorge potato
Why is it doing that?
The only thing that is the same in both tables is the username.
Thanks for your question. The issue here is the error that you are receiving of:
Column 'username' in where clause is ambiguous.
What this means is that the statement that you are running is too obscure.
What you need to do to avoid this is to explicitly define the tables and columns that you are attempting to access and thus be implicit in your statements.
As a rule of thumb try and always define your columns in the following format:
{table_name}.{column_name}
With that being said the following should work:
$friends = implode("','", $friends);
/* implode the friends array for sql query. */
$sql = mysqli_query($con, "SELECT * FROM users, text_post WHERE users.username IN ('$friends') AND text_post.username IN ('$friends')") or die(mysqli_error($con));
while ($row = mysqli_fetch_assoc($sql)) {
echo $row['last_name']. ' ' . $row['body'];
}
Also I would also recommend that you use PHP's PDO Object as appose to the mysqli_query method.
I trust this helps.
both tables have a username. specify it using table.username
apparently both tables have the same column, and you are not prefixing the username column with either table name.
Maybe what you want is a union?
Use table prefix users in where block i.e. users.username
$sql = mysqli_query($con, "SELECT * FROM users, text_post WHERE users.username IN ('$friends')") or die(mysqli_error($con));
Try this:
$friends = implode("','", $friends);
//implode the friends array for sql query
$sql = mysqli_query($con, "SELECT users.last_name,text_post.body FROM users, text_post WHERE username IN ('$friends')") or die(mysqli_error($con));
while ($row = mysqli_fetch_assoc($sql)) {
echo $row['last_name']. ' ' . $row['body'];
}
Your logic would work were it not for username being present in both tables. Because it is, you need to alias your table names so that you can uniquely identify which column you're trying to use in the where clause:
SELECT * from users AS u, text_post as tp
WHERE u.username IN(....)
or shorter:
SELECT * from users u, text_post tp
WHERE u.username IN(....)
As a side note, it's bad practice to SELECT *, you should always explicitly select the columns you want, otherwise your code may crash if you add a column to a table later and forget to update your for loop to include/ignore any changed columns.

Need help sql "LIKE" operator

Users on my site get to add their friends. The way i am trying to do it is when they add a new friend It updates the "friends" column so.. if the user "bobby" had friends named tom and Joe already and they want to add another friend "bob" it will update the column so it would now look like " tom, joe, bob, ect.." so.. my issue is each one of these friends has data in a table called items with their information age, city etc.. when bobby hits the button "show()" I need it to retrieve each friend that is in "bobby's" friend column with their info. So this is where I am at.
$show = mysql_query("SELECT `friends` FROM `Friends` WHERE`Username`='".$_SESSION['Username']."' ") or die(mysql_error());
$showw = mysql_fetch_object($show) or die(mysql_error());
$yup = mysql_query("SELECT * FROM `items` WHERE Username LIKE '%".($showw->friends)."%' ") or die(mysql_error());
It won't return any data because i can't figure out a way for it to sort through then names. Can I tell it to get each name after each comma?
First off, you should have a separate table to map the friends to a particular user. You will face a lot of complications if you continue it the way you have now.
Anyway, even though this is not recommended, in your case,
$show = mysql_query("SELECT `friends` FROM `Friends` WHERE`Username`='".$_SESSION['Username']."' ") or die(mysql_error());
$showw = mysql_fetch_object($show) or die(mysql_error());
$friends = "'" . str_replace(", ", "', '", $showw->friends) . "'";
$yup = mysql_query("SELECT * FROM `items` WHERE Username IN (". $friends .") ") or die(mysql_error());
IN will filter match all the comma separated values.
PS: Please consider using PDO or any other database library as mysql_* functions are getting deprecated over the next release :)

how to return array for mysql_query?

// make empty array
$sqlArray=array();
$jsonArray=array();
// START NEED FAST WORKING ALTERNATİVES -----------------------------------------------------
// first 20 vistors
$query = "SELECT user_id FROM vistors LIMIT 20";
$result = mysql_query ($query) or die ($query);
// make vistors user query array
while ($vstr_line = mysql_fetch_array($result)){
array_push($sqlArray, $vstr_line['user_id']);
}
// implode vistors user array
$sqlArray_impl = implode("', '", $sqlArray);
// END NEED FAST WORKING ALTERNATİVES -----------------------------------------------------
// Get vistors information
$query = "SELECT id, username, picture FROM users WHERE id IN ('$sqlArray_impl')";
$qry_result = mysql_query($query) or die($query);
while ($usr_line = mysql_fetch_array($qry_result)){
array_push($jsonArray, $usr_line['id'].' - '.$usr_line['username'].' - '.$usr_line['picture']);
}
print_r($sqlArray);
echo '<br><br>';
print_r($jsonArray);
see this my functions..
i need a replacement for fast working alternatives..
function within the range specified above, to me, running faster than the alternative.
the query will return back array ?
thx for all helpers !
Can you use a JOIN or SUB SELECT to reduce the query count from 2 to 1? Might not give much of a boost but worth a shot and a cleaner implementation.
Where is the bottleneck? Most likely the db and not the php code.
Are the tables/columns properly indexed? Run EXPLAIN on both queries.
Easiest would be to include first query as subquery eliminating one turn to the DB and a lot of code:
// Get vistors information
$query = "SELECT id, username, picture FROM users WHERE id IN (SELECT user_id FROM vistors LIMIT 20)";
$qry_result = mysql_query($query) or die($query);
Unless there is more reason to have the first one seperate, but that is not visible in your code example.
If you use PDO (recommended anyway...), you can return the result array all at once using fetchAll().
For your second query, you can use string concatenation in MySQL to directly return the result you want.

Categories