So, I have a database called teams, and it currently looks like this:
team_id | leader_id | student_id
1 | 123456 | 1234
2 | 1234 | 123456, 1234567890
3 | 1234 | 123456
4 | 0 | 12345, 1234, 1234567890
5 | 0 |
6 | 0 |
My students database looks like this
student_id | first_name | last_name
123456 | qwer | qwer
0 | asd | zxc
1234567890 | mmm |nnn
The user inputs a leader_id, and the user can input up to 7 student_id. The problem is that if the user inputs 1 student_id, everything is normal, but when the user inputs more than 1 student_id, than it stores the data more than once.
Example:
If the user enters 1234 as the leader_id, and enters 123456 and 1234567890 as the student_id, than it should store the data in one row, not separate the data into 2 rows.
Another thing is that in the last 3 rows, the user inputs 3 student_id, and the data gets stored in 1 row, but it adds 2 extra rows with nothing for the student_id
My PHP
<?php
error_reporting(0);
require '../../connect.php';
$leader_id = $_POST['leader_id'];
$student_id = array(
$_POST['student_id_1'],
$_POST['student_id_2'],
$_POST['student_id_3'],
$_POST['student_id_4'],
$_POST['student_id_5'],
$_POST['student_id_6']
);
$students_save = array();
if(!empty($leader_id)) {
foreach ($student_id as $id) {
if(!empty($id)) {
array_push($students_save, $id);
}
}
foreach ($students_save as $save) {
$check_id = mysqli_query($link, "SELECT student_id FROM students WHERE student_id = $save");
if(mysqli_num_rows($check_id)>0) {
$students_save = implode(", ", $students_save);
$result = mysqli_query($link, "INSERT INTO teams (leader_id, student_id)
VALUES ('$leader_id', '$students_save');");
if($result) {
header("Location: ../../../admin.php?message=Success!");
} else {
header("Location: ../../../admin.php?message=Sorry we ran into an error");
}
} else {
header("Location: ../../../admin.php?message=A Student ID Doesn't Exist");
}
}
} else if(empty($leader_id)){
header("Location: ../../../admin.php?Please add you're input values");
}
?>
As you edited your question,
all you need is to break out of your foreach loop, if you $result is
successfull so add break in if($result) rest of the code will remain
the same
See the code below
<?php
foreach ($students_save as $save) {
$check_id = mysqli_query($link, "SELECT student_id FROM students WHERE student_id = $save");
if(mysqli_num_rows($check_id)>0) {
$students_save = implode(", ", $students_save);
$result = mysqli_query($link, "INSERT INTO teams (leader_id, student_id)
VALUES ('$leader_id', '$students_save');");
if($result) {
header("Location: ../../../admin.php?message=Success!");
break; // add break here, as if your condition
} else {
header("Location: ../../../admin.php?message=Sorry we ran into an error");
}
} else {
header("Location: ../../../admin.php?message=A Student ID Doesn't Exist");
}
}
Try the below code if it helps,
<?php
error_reporting(0);
require '../../connect.php';
$leader_id = $_POST['leader_id'];
$student_id = array();
if(isset($_POST['student_id_1'])) $student_id[] = $_POST['student_id_1'];
if(isset($_POST['student_id_2'])) $student_id[] = $_POST['student_id_2'];
if(isset($_POST['student_id_3'])) $student_id[] = $_POST['student_id_3'];
if(isset($_POST['student_id_4'])) $student_id[] = $_POST['student_id_4'];
if(isset($_POST['student_id_5'])) $student_id[] = $_POST['student_id_5'];
if(isset($_POST['student_id_6'])) $student_id[] = $_POST['student_id_6'];
if(!empty($leader_id)) {
$students_save = implode(", ", $student_id);
$check_id = mysqli_query($link, "SELECT student_id FROM students WHERE student_id IN ($students_save)");
if(mysqli_num_rows($check_id)>0) {
//$student_ids = array();
//while($row = $check_id->fetch_array(MYSQLI_ASSOC)) $student_ids[] = $row['student_id'];
//$students_save = implode(", ", $student_ids);
$result = mysqli_query($link, "INSERT INTO teams (leader_id, student_id) VALUES ('$leader_id', '$students_save');");
if($result) {
header("Location: ../../../admin.php?message=Success!");
} else {
header("Location: ../../../admin.php?message=Sorry we ran into an error");
}
} else {
header("Location: ../../../admin.php?message=A Student ID Doesn't Exist");
}
} else if(empty($leader_id)) {
header("Location: ../../../admin.php?Please add you're input values");
}
?>
This code should help you.
Note: I have added comment to a part of the code. If you remove the commenting, then it will only insert the student_id which exists in the students table.
Related
I am creating two users conversation view script in PHP mysqli. My problem when I sent message as a last message my username display on the URL, therefore I want to display when I discussed other username on the URL. And also I want to display profile picture which I discussed of user profile picture, from user table.
Database pm table
id from_id from_name to_id to_name msg sent_date
1 2 john 3 master hi how are you? 2019-12-05 04:14:20
2 3 master 2 john fine 2019-12-05 05:15:58
3 2 john 3 master hi 2019-12-05 03:20:34
4 5 previn 2 john hi 2019-12-05 08:30:40
users table
userid | username | profile_pic
Here is my URL
Replay
Here is source code
<?php
if (isset($_SESSION['userid'])) {
$session_id = $_SESSION['userid'];
}
if ($stmt = $con->prepare("SELECT * FROM pm WHERE from_id = ? OR to_id = ? ORDER BY sent_time DESC")) {
$stmt->bind_param('ii', $session_id, $session_id);
$stmt->execute();
}
$tempArray = array();
$result = $stmt->get_result();
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
if (!in_array($row['to_id'].$row['from_id'], $tempArray)) {
echo "<br>";
echo $row['from_id']." - " . $row['to_id']." ". $row['msg']. " - " .$row['sent_time'];
$guaranteed_from_id = str_replace($session_id, null, $row['to_id'].$row['from_id']);
?>
<img src="images/<?php echo $row['profile_pic'];?>" height="20px" width="20px"/>
Replay
<?php
}
array_push($tempArray, $row['from_id'].$row['to_id']);
array_push($tempArray, $row['to_id'].$row['from_id']);
}
} else {
echo "NO MESSAGES";
}
?>
So first of all you don't need to have the username in the pm table at all. So remove these columns from the "pm" table. This is because you can use the id in users table to link with the "from_id" and "to_id".
PM table:
id from_id to_id msg sent_date
1 2 3 hi how are you? 2019-12-05 04:14:20
2 3 2 fine 2019-12-05 05:15:58
3 2 3 hi 2019-12-05 03:20:34
4 5 2 hi 2019-12-05 08:30:40
Users table:
id username profile_pic
1 john <link to profile picture>
2 master <link to profile picture>
3 john <link to profile picture>
4 previn <link to profile picture>
4 robin <link to profile picture>
So I was thinking of using a JOIN in the SQL. But didn't really get it to work when have to select with both the to_id and the from_id. So came up with some really wierd shit. I think you have to this in some other way because this gets really wierd. But I finally did get it to work. But this is not a great solution just A solution.
The code to the solution:
if (isset($_SESSION['userid'])) {
$session_id = $_SESSION['userid'];
}
$sql = "SELECT *,
(SELECT username FROM users WHERE userid=from_id) AS from_username,
(SELECT username FROM users WHERE userid=to_id) AS to_username,
(SELECT username FROM users WHERE userid=?) AS my_username,
(SELECT profile_pic FROM users WHERE userid=from_id) AS from_profile_pic,
(SELECT profile_pic FROM users WHERE userid=to_id) AS to_profile_pic,
(SELECT profile_pic FROM users WHERE userid=?) AS my_profile_pic
FROM pm WHERE from_id = ? OR to_id = ? ORDER BY id DESC";
if ($stmt = $con->prepare($sql)) {
$stmt->bind_param('iiii', $session_id, $session_id, $session_id, $session_id);
$stmt->execute();
}
$tempArray = array();
$result = $stmt->get_result();
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
if (!in_array($row['to_id'].$row['from_id'], $tempArray)) {
$friend_id = str_replace($session_id, null, $row['to_id'].$row['from_id']);
$title = $row['from_username'].$row['to_username'];
$num = strlen($title) ;
$num = $num/2;
$first_half = substr($title,0, $num);
$second_half = substr($title, $num);
if ($first_half == $second_half) {
$friend_username = $row['from_username'];
} else {
$friend_username = str_replace($row['my_username'], null, $row['from_username'].$row['to_username']);
}
$friend_profile_pic = str_replace($row['my_profile_pic'], null, $row['from_profile_pic'].$row['to_profile_pic']);
echo "<br>";
echo $row['from_username'] . " - " . $row['to_username']." ". $row['msg']. " - " .$row['sent_time'];
?>
<img src="images/<?php echo $friend_profile_pic;?>" height="20px" width="20px"/>
Reply
<?php
}
array_push($tempArray, $row['from_id'].$row['to_id']);
array_push($tempArray, $row['to_id'].$row['from_id']);
}
} else {
echo "NO MESSAGES";
}
Im currently using the json_encode in converting array to strings
which outputs data in a straight pattern in my table
user
-----------
id | name
-------------------------------------------
1 |"name1","name2","name3","name4","name5"
But i want to have an output where the table data will look like this.
user
-----------
id | name
-----------
1 | name1
2 | name2
3 | name3
4 | name4
5 | name5
My PHP code
<?php
$connect = mysqli_connect("localhost", "root", "", "dbsample");
if(isset($_POST["check_val"])){
$check_val = htmlspecialchars(strip_tags("check_val"));
$number = json_encode($_POST["name"]);
for ($i = 0; $i < count($number); $i++) {
if ($number[$i] != "") {
$query = "INSERT INTO tbl_name(name) VALUES (?)";
$stmt = $connect->prepare($query);
$number[$i] = htmlspecialchars(strip_tags($number[$i]));
$stmt->bind_param("s", $number);
if($stmt->execute()) {
echo "SUCCESS";
# code...
}else
{
echo "ERROR";
}
}
else{
echo "Please Enter Name";
}
}
}
?>
I need somewhere in the code to say "if there is nothing found after the current id, start searching from id 1". I'm running into the problem where (for example) I'm querying for any id > 4 where status == 1. Because id 5 doesn't have the right status, the code doesn't execute. I need it to go back to id #1.
mysql table example
-----------------------------------------
| id | page | status | referral |
-----------------------------------------
| 1 | new | 1 | new.php |
| 2 | used | 0 | used.php |
| 3 | lease | 1 | lease.php |
| 4 | video | 0 | video.php |
| 5 | serv | 0 | serv.php
-----------------------------------------
php code
<?php
$referral = $_SERVER['HTTP_REFERER'];
$sql = "SELECT * FROM allpages
WHERE status = '1' && referral != '$referral' && id > '4'";
$result = mysqli_query($conn, $sql);
$num = mysqli_num_rows($result);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
if ($row['status'] == 1){
echo "<script>
setTimeout(function() {
window.location.href = '" . $row['url'] . "';
}, 10000);
</script>";
break;
}else { echo "no page to display"; }
}
}
mysqli_close($conn);
?>
You want to find the first id greater than 4 and otherwise return the first id in the table. You can do this by ordering by (id > 4) DESC and then by id ASC. This will ensure all id's > 4 will appear before id 1. Also remove the id>4 from your where clause. Example:
SELECT * FROM allpages WHERE status = '1' ORDER BY (id > '4') DESC, id ASC LIMIT 1
Apart from the security reason regarding SQL Injectons, you have to understand, if there are no rows given, you have to an other sql request to get data from the beginning
In this case you would need an SQL Like
SELECT * FROM allpages WHERE status = '1' && referral != '$referral' ORDER BY id ASC LIMIT 1;
This will do the job. Keep in mind, the code could be a lot nicer and less, if you use a function to get the sql result.
<?php
$referral = mysqli_real_escape_string($conn, $_SERVER['HTTP_REFERER']);
$sql = "SELECT * FROM allpages WHERE status = '1' && referral != '$referral' && id > '4' LIMIT 1";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result));
if (!empty($row) && is_array($row)) {
// result found
echo "<script>
setTimeout(function() {
window.location.href = '" . $row['url'] . "';
}, 10000);
</script>";
} else {
// no result yet, start search from beginning
$sql2 = "SELECT * FROM allpages WHERE status = '1' && referral != '$referral' ORDER BY id ASC LIMIT 1";
$result2 = mysqli_query($conn, $sql2);
$row2 = mysqli_fetch_assoc($result2));
if (!empty($row2) && is_array($row2)) {
// result found by start from beginning
$row2 = mysqli_fetch_assoc($result2));
echo "<script>
setTimeout(function() {
window.location.href = '" . $row2['url'] . "';
}, 10000);
</script>";
} else {
// noting found from start
echo "no page to display";
}
}
mysqli_close($conn);
?>
I want to find a value from a column which has multiple values like (23,24,25), Using php mysqli query.
Table:
+-----------------+
id | tag_ids |
+-----------------+
1 | 3,4,5 |
2 | 3,7,8,9 |
3 | 4,5,10 |
Curent query:
$value = '3';
$query = "SELECT tag_ids FROM table WHERE FIND_IN_SET($value, tag_ids)";
$result = mysqli_query($query);
$count = mysqli_num_rows($result);
echo count;
Result will be: YES/NO or 1/0, if the Given value is match any value with tag_ids.
I found the result my self and here is code:
function statusvalues() {
$query = "SELECT tag_ids FROM tblname WHERE tag_ids !=''";
$result = mysqli_query($query, DBCONN);
$idarray = array();
while($row = mysqli_fetch_array($result)) {
array_push($idarray, $row['tag_ids']);
}
return $idarray;
}
function status($ID) { //Passing tag id
$set_of_numbers = statusvalues();
$reset_numbers = implode(", ", $set_of_numbers);
$values = explode(", ", $reset_numbers);
if (in_array($ID, $values)){
return "disabled";
}
}
I am looking for some help to build a generic PHP function that will take in the output of SQL query
SELECT DISTINCT categoryID, StatusID, COUNT( * ) FROM tableA GROUP BY categoryID
Sample result:
categoryID StatusID COUNT( * )
CategoryB On Hold 1
CategoryA On Hold 4
CategoryC On Hold 3
CategoryB Draft 1
There can be any number of CategoryIDs and Statuses in the database...
and return a TABULAR table format:
My desired outcome goes something like this:
Status Summary Table by Category:
---------------------------------------------------------
| CategoryA | CategoryB | CategoryC | ... | TOTAL
Completed | 0 | 1 | 0 | ... | 1
On Hold | 4 | 0 | 3 | ... | 7
Draft | 0 | 1 | 1 | ... | 2
---------------------------------------------------------
TOTAL: | 4 | 2 | 4 | ... | 10
I figure it out! -- I am hoping this helps someone else in the future..
It is not pretty code, but it works and it is pretty genetic so it can be used as needed..
Who it is called:
$sql="SELECT DISTINCT categoryID, statusID, COUNT( * ) as Count1 FROM entries GROUP BY categoryID" ;
$results = mysql_query($sql, $con);
// Now that we have both Status and Category, lets place the counts in the right cells:
echo displayTabularSum ($myarray,"status","category",1) ;
Now the functions I used:
function displayTabularSum($myarray, $table1,$table2,$includeTotals)
{
// First get all data from $table1 into an array
$sql = "SELECT * FROM $table1 WHERE 1";
$results= mysql_query($sql);
$statusCodes= getsqlresultintoarray ($results) ;
// Second: get all data from $table2 into an array
$sql = "SELECT * FROM $table2 WHERE 1";
$results= mysql_query($sql);
$categoryCodes= getsqlresultintoarray ($results) ;
// Now create the results table with appropriate values in columns
$statusTable=array();
$out = '';
$first = true;
$cT=array();
for ($x=0; $x';
for ($y=0; $y'.$categoryCodes[$y][1].'';
}
if ($includeTotals) $out.= 'Total';
$out.= '';
$first = false;
}
$out .="";
$out .="".$statusCodes[$x][1]."";
$rT=0;
for ($y=0; $y";
$c1=searchForId($categoryCodes[$y][0], $myarray, "categoryID");
$c2=searchForId($statusCodes[$x][0], $myarray, "statusID");
$count1=0;
$same=($c1==$c2);
If ( $same ) {
If ($c1==99999 OR $c2==99999) {
// do nothing... These are NULLs
} else {
$count1=$count1+$myarray[$c1]['Count1'];
}
}
$out .= $count1;
$rT=$count1+$rT;
$cT[$y]=$cT[$y]+$count1; // Collecting column Totals
$out .="";
}
if ($includeTotals) $out.= ''.$rT.''; // display rowTotal
$out .="";
}
if ($includeTotals) { // Display the column Total before closing table.
$cT1=0;
$out .="";
$out.= 'Total:';
for ($x=0; $x'.$cT[$x].'';
$cT1=$cT1+$cT[$x];
}
$out.= ''.$cT1.'';
$out .="";
}
$out .="";
return $out;
}
Function getresultsintoarray1 ($results)
{ // Function to get all results from a SQL QUery into an Array.
$num_rows = mysql_num_rows($results);
$myarray=array();
if ($num_rows>0) {
while($row = mysql_fetch_assoc($results))
{
$myarray[] = $row;
}
}else
{
echo " No data found on database... " ;
unset($myarray);
$myarray=array();
}
return $myarray;
}
function getsqlresultintoarray ($get) // YES
{
$num_rows = mysql_num_rows($get);
$returnArray=array();
$i=0;
while($row1 = mysql_fetch_array($get)) {
$returnArray[$i][0]=$row1[0]; // This is the ID
$returnArray[$i][1]=$row1[1]; // This is the name
$i++;
}
return $returnArray;
}
function searchForId($id, $array, $field)
{
If (count($array)>0) {
foreach ($array as $key => $val) {
if ($val[$field] === $id) {
return $key;
}
}
}
return 99999;
}
If anyone has ideas as to how to improve, I would appreciate it!