Joining two table and updating the result - php

I am joining two table and I want to update all the rows.
<?php
include("connection/mysqlconnect.php");
$sql=" SELECT course.duration, course.id, students.ID
FROM course, students
where course.id=course_id and course.duration = '2'";
$result = $conn->query($sql);
$count=mysqli_num_rows($result);
if($count>=1)
{
while($row = mysqli_fetch_array($result)) {
$id = $row['ID'];
$stat = 'Active';
$year = '2nd Year';
$Graduated = 'Graduated';
$sql1 = "UPDATE students SET Year='$Graduated', Status='non-Active'
WHERE ID = '$id' and (status='$stat' and Year='$year')";
echo "$id</br>";
}
}
?>
I tried the Select Statement above in "Run SQL query" and it query the result i want. and I want to update all of the query, but I cant. I tried Putting echo under the update and it echo the ID's I need to update, but my update statement is not executing.

Instead of selecting all students then updating one by one, you can actually to this in one shot by joining both tables and updating it.
UPDATE students s
INNER JOIN course c ON c.id = s.course_id
SET s.Year = '$Graduated',
s.Status = 'non-Active'
WHERE c.duration = '2'
AND s.status = '$stat'
AND s.Year = '$year'
It must also be taken into consideration that the query above is vulnerable with sql injection. This article below will guide you how to prevent from it.
How to prevent SQL injection in PHP?

The issue with the first query is that there are two columns with the same name; ID. So referencing the ID from the row generates an error. Use alias to fix it as shown below. For a better performance use an inner join instead. You also forgot to run the update query again your database.
<?php
include("connection/mysqlconnect.php");
$sql=" SELECT course.duration, course.id as cID, students.ID as sID
FROM course JOIN students ON course.id=course_id
where course.duration = '2'";
$result = $conn->query($sql);
$count=mysqli_num_rows($result);
if($count>=1)
{
while($row = mysqli_fetch_array($result)) {
$id = $row['sID'];
$stat = 'Active';
$year = '2nd Year';
$Graduated = 'Graduated';
echo "Student ID to be updated: $id<br/>";
$sql1 = "UPDATE students SET Year='$Graduated', Status='non-Active'
WHERE ID = '$id' and (status='$stat' and Year='$year')";
//you have to execute the query for the update to be done.
if ($conn->query($sql1) === TRUE) {
echo "Record updated successfully ";
} else {
echo "Error updating record: " . $conn->error;
}
}
}
$conn->close();
?>

Related

How to update data using one select in other database table

I have two databases and i have one table "TabelaX" in database "Servidor1" with out data and other database "Servidor2" with one table "TabelaY". And i want do one select in table "TabelaY" and with her data do one Update in table "TabelaX" which is in another database. I already made some code but it is not working correctly.
<?php
$conn= mysqli_connect('localhost','root',null,'Servidor2') or die
(mysqli_connect_error());
if (!$conn) {
die("Falha de conexao: ". mysqli_connect_error());
}
$ID = $_POST['ID'];
$sql = "SELECT * FROM TabelaY WHERE ID = $ID";
$result = mysqli_query($conn, $sql);
mysqli_select_db($conn,"Servidor1");
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$row1 = $row["ID"];
$row2 = $row["Data"];
}
} else {
echo "0 results";
}
$sql = "INSERT INTO Servidor1.TabelaX (ID, Data)
SELECT ID, Data
FROM Servidor3.TabelaW
WHERE ID = $ID;";
$sql = "UPDATE Servidor1.TabelaX SELECT ID, Data FROM
Servidor3.TabelaW SET Data = $row2 WHERE $row1 = $ID;";
if (mysqli_multi_query($conn, $sql)) {
echo "Dados Inseridos";
} if (mysqli_multi_query($conn, $sql)) {
echo "Dados Atualizados";
}
mysqli_close($conn);
I have no idea what your query is trying to do, because you assign to $sql twice without ever executing the first query, but if you're asking how to update a row in tableX based on data from tableY, then:
UPDATE Servidor1.TabelaX as x, Servidor2.TabelaY as y
SET x.Data = y.Data
WHERE x.id = y.id
AND x.id = $someIdForWhichYouWantToUpdate
Also, do not do this:
$ID = $_POST['ID'];
$sql = "SELECT * FROM TabelaY WHERE ID = $ID";
Imagine what happens when the user posts 1; DROP DATABASE Servidor1 into the form. This is called SQL injection and your code is full of vulnerabilities to it.

Mysql Join two tables to check if a user has made a pick

Hi I am attempting to join two MySQL tables. The tables are as follows:
Table 1
Name: mlb_game_feed
Fields: game_feed_game_id, date, home_team, away_team
Table 2
Name: user_picks
Fields: pick_id, game_feed_game_id_fk, user_id_fk
Here is the sql I've attempted to use to join the two tables:
$sql = "
SELECT game_feed_game_id
, home_team
, away_team
, COUNT(1) as cnt
FROM game_feed_mlb
JOIN user_picks
ON user_picks.game_feed_game_id_fk = game_feed_mlb.game_feed_game_id
Where game_feed_mlb.date = '" . $_SESSION['date']."'
AND user_picks.user_id_fk = 1";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$count = $row["cnt"];
$game_id = $row["game_feed_game_id"];
$home_team = $row['home_team'];
$away_team = $row['away_team'];
echo $game_id;
}
}
My intention is to check if the user has picked a winner (either home_team or away_team) from the mlb_game_feed table and if they have, I will change a link from make_pick to change_pick (with an if($count) statement) on the screen.
However, currently I'm not even getting any data back which means my sql is likely incorrect. Any help would be great! Thanks.
Consider the following suggestions:
Use a LEFT JOIN to return ALL records and a conditional aggregate to count matches in cnt field. Later you can use this cnt to run your update hyperlink in PHP. See if block in fetch loop.
As mentioned, your SQL string that concatenates on line breaks does not leave room before the clauses of SQL: FROM, JOIN, ON, and WHERE.
Use a GROUP BY clause for your aggregate query. Non-aggregated columns must appear in this clause else it is a violation of ANSI SQL. Unfortunately, MySQL allows the ONLY_FULL_GROUP_BY mode off whereas every other RDBMS will correctly throw an error.
Use table aliases for more readable code instead of repeating long name tables.
Pass in $SESSION date as a parameter to prepared statement. See ? placeholder in string.
PHP
$sql = "SELECT g.game_feed_game_id, g.home_team, g.away_team, " .
" SUM(CASE WHEN g.game_feed_game_id IS NOT NULL " .
" THEN 1 ELSE 0 END) as cnt " .
"FROM game_feed_mlb g " .
"LEFT JOIN user_picks u " .
" ON u.game_feed_game_id_fk = g.game_feed_game_id " .
"WHERE g.`date` = ? AND u.user_id_fk = 1 " .
"GROUP BY g.game_feed_game_id, g.home_team, g.away_team;"
// CONFIGURE PREPARED STATEMENT AND BIND PARAMETER
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("s", $_SESSION['date']);
// EXECUTE STATEMENT AND RETURN RESULTS
$stmt->execute();
$result = $stmt->get_result();
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$count = $row["cnt"];
$game_id = $row["game_feed_game_id"];
$home_team = $row['home_team'];
$away_team = $row['away_team'];
echo $game_id;
if($row['cnt'] > 1) {
// change links accordingly...
}
}
}

Echo rows via JOIN in MySQL/PHP (?)

I wanna be able to echo out if Groupname and Username are connected correctly, where the current userid (saved in a session) is $uid.
I've been sitting for hours trying all kinds of JOINs and the closest I've gotten is having it output 1/? members for each team, but not all of them.
EDIT:
$uid = $_SESSION['uid'];
$sql = "SELECT * FROM group
INNER JOIN usergroup ON group.groupid=usergroup.groupid
WHERE usergroup.userid=$uid";
$result=$mysqli->query($sql);
if(mysqli_num_rows($result)>0) {
while($row = mysqli_fetch_array($result)) {
$gid = $row['groupid'];
$sql2 = "SELECT * FROM user
INNER JOIN usergroup ON user.userid=usergroup.userid
WHERE usergroup.groupid=$gid";
$result2=$mysqli->query($sql2);
$row2 = mysqli_fetch_array($result2);
echo "<td>".$row['groupname']."</td>";
echo "<td>".$row2['username']."</td>";
echo "<td>".$row['groupid']."</td>";
}
}
Thing is, that it kinda works well, except that it doesn't print all the groupmembers names out, it prints out just one. Which one seems to depend on the order in the table.
You did not have a loop on the second query's resultset. However, it is not needed to have a second SQL query. Just do it in one go; SQL was designed for that.
Also, you'll have much simpler code:
$uid = $_SESSION['uid'];
// Select everything you need in one go (join user table as well)
$sql = "SELECT group.group_id, group.groupname, user.username
FROM group
INNER JOIN usergroup ON group.groupid=usergroup.groupid
INNER JOIN user ON user.userid=usergroup.userid
WHERE usergroup.userid=$uid";
$result=$mysqli->query($sql);
// Don't need to call mysqli_num_rows if you continue like this:
while($row = mysqli_fetch_array($result)) {
echo "<td>".$row['groupname']."</td>";
echo "<td>".$row['username']."</td>";
echo "<td>".$row['groupid']."</td>";
}
Maybe you want to echo some <tr> and </tr> tags, or you"ll have everything in one row, like:
echo "<tr><td>".$row['groupname']."</td>"
."<td>".$row['username']."</td>"
."<td>".$row['groupid']."</td></tr>";
There you go: (you were missing nested while loop)
if(mysqli_num_rows($result)>0) {
while($row = mysqli_fetch_array($result)) {
$gid = $row['groupid'];
$sql2 = "SELECT * FROM user INNER JOIN usergroup ON user.userid=usergroup.userid WHERE usergroup.groupid=$gid";
$result2=$mysqli->query($sql2);
if(mysqli_num_rows($result2)>0) {
while($row2 = mysqli_fetch_array($result2)) {
echo "<td>".$row['groupname']."</td>";
echo "<td>".$row2['username']."</td>";
echo "<td>".$row['groupid']."</td>";
}
}
}
}
Side note: You could achieve the same results with just one SQL query, something like:
SELECT
*
FROM
usergroup ug
INNER JOIN
user u ON ug.userid = u.userid
GROUP BY
ug.id
and then in PHP (pseudo code just, do not copy-n-paste)
while($row => mysqli_fetch_array($result)) {
if (!isset($groupsWithUsers[$row['groupid']['users'])) {
$groupsWithUsers[$row['groupid']['users'] = array()
}
$groupsWithUsers[$row['groupid']['users'][$row['userid']] = $row;
}

Display more than one row from SQL SELECT

I want to display all of the rows shown in the picture where CID = 1.
Here is my PHP code with SQL:
`
$contractCount = 1;
$sql = "SELECT categories.categoryID
FROM categories
LEFT JOIN link
ON categories.categoryID = link.categoryID
WHERE link.CID = '$contractCount'";
$res = $con->query($sql);
if (!$res) {
echo 'Could not run query: ' . mysql_error();
exit;
}
while ($row = mysqli_fetch_array($res)) {
echo $row['categoryID'];
}
Here is an image showing the table in PHPMyAdmin called categories.
So I need output as ITSM, Mar and HrAd but I am only getting ITSM and not the rest.
EDIT 1: The LEFT JOIN makes no difference here, the link table has no bearing on the SELECT statement
EDIT 2: I have solved the problem, my mistake was that I had the table names the wrong way round in the SQL query.
You need to use the function mysql_fetch_row, this will fetch a row and move the pointer to the next one.
while ($row = mysqli_fetch_row($res)) {
echo $row['categoryID'];
}

Get result of mysql_query inside while of mysql_fetch_array

I am using a code something like below to get data from the second table by matching the id of first table. Code is working well, but I know it slow down the performance, I am a new bee. Please help me to do the same by an easy and correct way.
<?php
$result1 = mysql_query("SELECT * FROM table1 ") or die(mysql_error());
while($row1 = mysql_fetch_array( $result1 ))
{
$tab1_id = $row1['tab1_id'];
echo $row['tab1_col1'] . "-";
$result2 = mysql_query("SELECT * FROM table2 WHERE tab2_col1='$tab1_id' ") or die(mysql_error());
while( $row2 = mysql_fetch_array( $result2 ))
{
echo $row2['tab2_col2'] . "-";
echo $row2['tab2_col3'] . "</br>";
}
}
?>
You can join the two tables and process the result in a single loop. You will need some extra logic to check if the id of table1 changes, because you'll only want to output this value when there's a different id:
<?php
// Join the tables and make sure to order by the id of table1.
$result1 = mysql_query("
SELECT
*
FROM
table1 t1
LEFT JOIN table2 t2 ON t2.col1 = t1.id
ORDER BY
t1.id") or die(mysql_error());
// A variable to remember the previous id on each iteration.
$previous_tab1_id = null;
while($row = mysql_fetch_array( $result1 ))
{
$tab1_id = $row['tab1_id'];
// Only output the 'header' if there is a different id for table1.
if ($tab1_id !== $previous_tab1_id)
{
$previous_tab1_id = $tab1_id;
echo $row['tab1_col1'] . "-";
}
// Only output details if there are details. There will still be a record
// for table1 if there are no details in table2, because of the LEFT JOIN
// If you don't want that, you can use INNER JOIN instead, and you won't need
// the 'if' below.
if ($row['tab2_col1'] !== null) {
echo $row['tab2_col2'] . "-";
echo $row['tab2_col3'] . "</br>";
}
}
Instead of having 2 while loops, what you can do is join the 2 tables and then iterate over the result.
If you're not sure what join is look here: https://dev.mysql.com/doc/refman/5.1/de/join.html
Also here is a fairly simple query written using join: Join Query Example
You can use this. One relation with two tables:
<?php
$result1 = mysql_query("SELECT tab2_col2, tab2_col3 FROM table1, table2 where tab2_col1 = tab1_id ") or die(mysql_error());
while($row1 = mysql_fetch_array( $result1 ),)
{
echo $row2['tab2_col2'] . "-";
echo $row2['tab2_col3'] . "</br>";
}
?>
Like Sushant said, it would be better to use one JOIN or simpler something like that:
SELECT * FROM table1, table2 WHERE `table1`.`id` = `table2`.`id

Categories