Hi i'm quite newbie in php language and i need to find same values in DESCRIPTION column in my database table.
id-------DESCRIPTION
1-------Final
2-------Exam
3-------Test
4-------Test
5-------Mid
6-------Quiz
7-------Quiz
As output it needs to be like:
Final
Exam
Test
Test
Mid
Quiz
Quiz
If a value repating just change them style is enough but i'm really don't know how to do it.
<?php
$check = mysqli_query($connection,"SELECT * FROM EXAMS");
while($test=mysqli_fetch_array($check))
{
echo $test["DESCRIPTION"];
}
?>
Use an EXISTS subquery to look if the same value exists for another id:
$result = $connection->query("
SELECT e.id, e.DESCRIPTION, EXISTS(
SELECT *
FROM EXAMS e2
WHERE e2.DESCRIPTION = e.DESCRIPTION
AND e2.id <> e.id
) as is_duplicate
FROM EXAMS e
ORDER BY e.id
");
Then check in PHP if it is a duplicate (if ($row['is_duplicate'] == 1)) and mark it bold:
while($row = $result->fetch_assoc())
{
if ($row['is_duplicate'] == 1) {
echo "<strong>$row['DESCRIPTION']</strong><br>";
} else {
echo "$row['DESCRIPTION']<br>";
}
}
PHP solution
$result = $connection->query("SELECT * FROM EXAMS");
$data = $result->fetch_all(MYSQLI_ASSOC);
$counts = array_count_values(array_column($data, 'DESCRIPTION'));
foreach($data as $row)
{
if ($counts[$row['DESCRIPTION']] > 1) {
echo "<strong>$row['DESCRIPTION']</strong><br>";
} else {
echo "$row['DESCRIPTION']<br>";
}
}
Related
I am creating a webGL game on Unity but want to get my php correct first.
I have 2 tables questions and answers. Each question has 4 potential answers and need to pull these from my db.
The answer table matches with the question table through questionId.
Questions:
Should I better use a table join or should I separate them?
Should I simply have a select statement just for the question table then a
join table for answers and submit separately?
Should I have created
the answer table with 4 columns for different answers?
Current code:
<?php
$query = ("select questiontable.questionId, questiontable.question, answertable.answerId,answertable.answer, answertable.questionId, questiontable.scoreValue
FROM questiontable
inner join answertable on questiontable.questionId=answertable.questionId ORDER BY RAND () LIMIT 1 ");
$result =mysqli_query($conn, $query) or die(mysqli_error($conn));
while ($row = mysqli_fetch_assoc($result)){
$row_cnt = mysqli_num_rows($result);
echo $row_cnt;
echo $row ['question'];
echo $row ['answer'] ;
echo $row ['answer'] ;
echo $row ['answer'];
echo $row ['answer'];
}
?>
Here are my tables:
CREATE TABLE `braingain`.`questionTable`
( `questionId` INT NOT NULL AUTO_INCREMENT , `question` VARCHAR(600) NOT NULL , `scoreValue` INT NOT NULL , `subject` VARCHAR(50) NOT NULL , PRIMARY KEY (`questionId`));
CREATE TABLE `braingain`.`answerTable`
( `answerId` INT NOT NULL , `answer` VARCHAR(600) NOT NULL , 'questionId', isCorrect;
The query should pull questions and 4 associated answers into an array.
Desired result
The created array should look like this:
| question | answerA | answerB | answerC | answerD |
| WHICH IS THE CORRECT SPELLING? | APPLE | APEL | APPUL | APPAL |
Run two nested queries,
$output = array();
$answer_array = array('answerA','answerB','answerC','answerD');
$query = ("select * from questiontable ORDER BY RAND () LIMIT 1 ");
$result =mysqli_query($conn, $query) or die(mysqli_error($conn));
while ($row = mysqli_fetch_assoc($result)){
$row_cnt = mysqli_num_rows($result);
$output['question']=$row['question'];
$query2 = ("select * from answerTable where questionId = ". $row ['questionId'] order by answerId);
$result2 =mysqli_query($conn, $query2) or die(mysqli_error($conn));
$i=0;
while ($row2 = mysqli_fetch_assoc($result2)){
$output[answer_array[$i]]=$row2['answer'];
$i++;
}
}
print_r($output);
?>
Please have a look at indentation, makes code much more plesant :)
<?php
$query = ("
SELECT
questiontable.questionId,
questiontable.question,
answertable.answerId,
answertable.answer,
answertable.questionId,
questiontable.scoreValue
FROM
questiontable
INNER JOIN
answertable on questiontable.questionId = answertable.questionId
ORDER BY RAND()
LIMIT 1
");
$result = mysqli_query($conn, $query) or die(mysqli_error($conn));
$data = [];
$data[] = null;
$keys = [
'question',
'answerA',
'answerB',
'answerC',
'answerD',
];
$return = [];
while ($row = mysqli_fetch_assoc($result)){
if ($data[0] !== $row['question']) {
$data = [];
$data[] = $row['question'];
}
$data[] = $row['answer'];
if (count($data) === 5) {
$dataAssociative = array_combine($keys, $data);
$return[] = $dataAssociative;
}
}
var_dump($return);
?>
ok, so i have everything working with my php etc. i have it echoing the result as i want heres the code...
<?php
session_start();
include 'dbconnect.php';
$output = array();
$answer_array = array('answerA','answerB','answerC','answerD'); //loads answers into array
$query = ("select * from questiontable ORDER BY RAND () LIMIT 1 ");//sql query to get questions
$result =mysqli_query($conn, $query) or die(mysqli_error($conn));
while ($row = mysqli_fetch_assoc($result)){
$row_cnt = mysqli_num_rows($result);
$output['question']=$row['question'];
$query2 = ("select * from answerTable where questionId = '". ($row ['questionId'])."' order by rand()");//sql query to get answers for questions by questionId
$result2 =mysqli_query($conn, $query2) or die(mysqli_error($conn));
$i=0;
$question=$row ['question'];
while ($row2 = mysqli_fetch_assoc($result2)){
$output[$answer_array[$i]]=$row2['answer'];
$i++;
$_POST = $output;
}
}
echo "</br> ";
echo $_POST ['question'];
echo "</br> ";
echo $_POST['answerA'];
echo "</br>";
echo $_POST['answerB'];
echo "</br>";
echo $_POST['answerC'];
echo "</br> ";
echo $_POST['answerD'];
?>
now i need to store the results in unity so i can assign them to buttons etc.
i have it pulling the details but unsure how to assign for example $_POST['answerA]; to a variable in c#.
this is my c# code...
public class qNaDisplay : MonoBehaviour {
public Text questionDisplayText, answerAText, answerBText, answerCText, answerDText;
public Text questMessage, answerMessage;
private string question, a, b, c, d;
// Use this for initialization
void Start ()
{
WWW questionURL = new WWW("http://localhost:8080/Project/PHP/questionRequest.php");
question = questionDisplayText.text;
a = answerAText.text;
b = answerBText.text;
c = answerCText.text;
d = answerDText.text;
StartCoroutine(qNaget(questionURL));
}
// Update is called once per frame
void Update () {
}
private IEnumerator qNaget (WWW questionURL)
{
yield return questionURL;
Debug.Log(questionURL.text);
if (questionURL.error != null)
{
print("There was an error getting the question " + questionURL.error);
}
else
{
Debug.Log (questionURL.text); // this is a GUIText that will display the scores in game.
}
}
}
// Fetching Name Of Exam
$sql = "SELECT distinct(`nameofexam`) FROM `marks` WHERE `OrgId`=$schoolid AND `Admno`=$Admno";
$result = $objcon->query($sql);
if ($result->num_rows > 0) {
$row1 = array();
// output data of each row
$array1 = array();
$json = array();
while ($row = $result->fetch_assoc()) {
$exam = $row["nameofexam"];
$json[] = $exam;
header('Content-type: application/json');
// Fetching Exam details
$sql1 = "SELECT distinct Admno,Class,subject,`markobtained`,Position
FROM ( SELECT #r:= CASE WHEN #e = nameofexam THEN #r + CASE WHEN #p = `markobtained` THEN 0 ELSE #i END ELSE 1 END Position,
#i:= CASE WHEN #p = `markobtained` THEN #i + 1 ELSE 1 END incr,
#e:= nameofexam,
#p:= `markobtained`,
Admno,
Class,
nameofexam,
subject,
`markobtained`
FROM marks,
(SELECT #e:= '') e,
(SELECT #r:= 0) r,
(SELECT #p:= 0) p,
(SELECT #i:= 0) i
ORDER BY nameofexam, `markobtained` desc
) T
WHERE `Admno`=$Admno AND `nameofexam`='$exam'
ORDER BY `subject`,position";
$result1 = $objcon->query($sql1);
if ($result1->num_rows > 0) {
while ($row1 = $result1->fetch_assoc()) {
array_push($json, $row1);
}
}
}
header('Content-type: application/json');
echo json_encode($array1, $response_array);
} else {
echo "No Exam Details Avalable";
}
I expect an output like this. The program logic is simple. First pick the exam name from the table1 and then fetch the corresponding mark sheet of that exam from another table and encode it. I need to encode multiple rows from mysql into json using php .Please help me...
Expected Output :
{"Onam Exam":[{"Admno": "3123","Class": "LKG-A","subject": "english
","markobtained": "50","Position": "1" }] }
At last got output. Here is the working code
<?php
$sql = "SELECT distinct(`nameofexam`) FROM `marks` WHERE `OrgId`=$schoolid AND `Admno`=$Admno";
$result = $objcon->query($sql);
if ($result->num_rows > 0) {
$row1 = array();
// output data of each row
$array1 = array();
$json = array();
$j=0;
while ($row = $result->fetch_assoc()) {
$exam = $row["nameofexam"];
header('Content-type: application/json');
// Fetching Exam details
$sql1 = "SELECT distinct Admno,Class,subject,`markobtained`,Position
FROM ( SELECT #r:= CASE WHEN #e = nameofexam THEN #r + CASE WHEN #p = `markobtained` THEN 0 ELSE #i END ELSE 1 END Position,
#i:= CASE WHEN #p = `markobtained` THEN #i + 1 ELSE 1 END incr,
#e:= nameofexam,
#p:= `markobtained`,
Admno,
Class,
nameofexam,
subject,
`markobtained`
FROM marks,
(SELECT #e:= '') e,
(SELECT #r:= 0) r,
(SELECT #p:= 0) p,
(SELECT #i:= 0) i
ORDER BY nameofexam, `markobtained` desc
) T
WHERE `Admno`=$Admno AND `nameofexam`='$exam'
ORDER BY `subject`,position";
$result1 = $objcon->query($sql1);
$test_array=array();
if ($result1->num_rows > 0) {
$i=0;
while ($row1 = $result1->fetch_assoc()) {
$test_array[$i]["Admno"]=$row1["Admno"];
$test_array[$i]["Class"]=$row1["Class"];
$test_array[$i]["subject"]=$row1["subject"];
$test_array[$i]["markobtained"]=$row1["markobtained"];
$test_array[$i]["Position"]=$row1["Position"];
$i++;
}
$response[$j]=array(
$exam=> $test_array
);
$j++;
}
}
header('Content-type: application/json');
echo json_encode($response);
} else {
echo "No Exam Details Avalable";
}
}
?>
Output
[{"Onam Exam":[{"Admno":"3123","Class":"LKG-A","subject":"english
","markobtained":"50","Position":"1"},{"Admno":"3123","Class":"LKG-A","subject":"Physics","markobtained":"10","Position":"18"}]},{"Xmas
Exam":[{"Admno":"3123","Class":"LKG-A","subject":"Chemistry","markobtained":"9","Position":"2"},{"Admno":"3123","Class":"LKG-A","subject":"Hindi","markobtained":"100","Position":"21"},{"Admno":"3123","Class":"LKG-A","subject":"Physics","markobtained":"99","Position":"1"}]}]
I have a db with columns like the following:
id options
1 Website,Website,Newspaper,Newspaper,TV,TV,Radio,Radio
2 Website,Website,Newspaper,Newspaper
3 Website,Website,TV,TV
The goal is to remove the duplicate entries and normalize the options column to:
id options
1 Website,Newspaper,TV,Radio
2 Website,Newspaper
3 Website,TV
I have developed the following PHP code:
$sql = "SELECT id, options FROM table";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$id = $row['id'];
$values_array = explode( ',' , $row['options'] );
if(count($values_array) != count(array_unique($values_array)))
{
$likes = array_unique($values_array);
$new = implode(',', $likes);
$sql = "UPDATE table SET options=".$new." WHERE id = '$id'";
}
}
} else {
echo "0 results";
}
$conn->close();
This doesn't get the job done. Everything seems to work but the attempt to update the options columns with the new array data.
This doesn't seem too difficult, just looking for a little guidance on how to make it work.
Thanks in advance!
You can do it directly in mysql
UPDATE T
JOIN
(SELECT id,GROUP_CONCAT(DISTINCT SUBSTRING_INDEX(SUBSTRING_INDEX(t.options, ',', sub0.aNum), ',', -1)) AS ids
FROM t
INNER JOIN
(
SELECT 1 + units.i + tens.i * 10 AS aNum, units.i + tens.i * 10 AS aSubscript
FROM (SELECT 0 AS i UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) units
CROSS JOIN (SELECT 0 AS i UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) tens
) sub0
ON (1 + LENGTH(t.options) - LENGTH(REPLACE(t.options, ',', ''))) >= sub0.aNum
GROUP BY id)x
ON x.id=t.id
SET t.options=x.ids
FIDDLE
Inspired by this answer
Try This:
$sql = "SELECT id, options FROM table";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while ($row = $result->fetch_assoc()) {
$id = $row['id'];
$values_array = explode(',', $row['options']);
if (count($values_array) != count(array_unique($values_array))) {
$likes = array_unique($values_array);
$new = implode(',', $likes);
$sql = "UPDATE table SET options=" . $new . " WHERE id = '$id'";
/* seems you missed this */
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
/* you declared sql query but not executed it */
}
}
} else {
echo "0 results";
}
$conn->close();
hope it was helpful :)
As stated in other answers, your quotes are wrong and you didn't execute the UPDATE query, there's another thing you need to know.
table is a reserved keyword in MySQL, so you can't use it like that in your query. Use backticks to escape it.
So your code should be like this:
$sql = "SELECT id, options FROM `table`";
$result = $conn->query($sql);
if ($result->num_rows > 0){
// output data of each row
while($row = $result->fetch_assoc()) {
$id = $row['id'];
$values_array = explode( ',' , $row['options'] );
if(count($values_array) != count(array_unique($values_array))){
$likes = array_unique($values_array);
$new = implode(',', $likes);
$sql = "UPDATE `table` SET options='".$new."' WHERE id = '$id'";
$conn->query($sql);
if($conn->affected_rows){
echo "success<br />";
}else{
echo "error<br />";
}
}
}
}else{
echo "0 results";
}
$conn->close();
Here's the reference:
Keywords and Reserved Words
I added the following code to my PHP as showcased by Ajjay Aroraa --
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
The final code for my entire application:
$sql = "SELECT id, options FROM tdata";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$id = $row['id'];
$values_array = explode( ',' , $row['options'] );
if(count($values_array) != count(array_unique($values_array)))
{
// find duplicate values in the array
$likes = array_unique($values_array);
$new = implode(',', $likes);
$sql = "UPDATE tdata SET options='".$new."' WHERE id = '$id'";
// execute update query
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
}
}
} else {
echo "0 results";
}
$conn->close();
Thanks to all who replied -- this is a quick fix as I work to normalize the tables.
I would like to know what the fastest way is to make the following SQL call using PHP. I am using procedural mySQLi.
$dcount = "SELECT max(id) FROM deposits";
$result = mysqli_query($conn,$dcount);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$count = $row["max(id)"];
echo $count;
echo ",";
}
} else {
echo '0';
}
//second query
$ucount = "SELECT max(int) FROM anothertable";
$result2 = mysqli_query($conn,$ucount);
if (mysqli_num_rows($result2) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$count = $row["max(int)"];
echo $count;
echo ",";
}
} else {
echo '0';
}
Is there a way to make the execution faster than like this, maybe to echo the results from both queries after the first if statement?
It just seems rather long to me.
Thanks in advance.
SELECT max(id) as max_id, (SELECT max(int) as max_int FROM anothertable) as max_int
FROM deposits
Not tested, but something like it should work
$dcount = "
SELECT max(id) as max,'deposit' as table_name FROM deposits
UNION
SELECT max(id) as max,'another' as table_name FROM anothertable
";
$result = mysqli_query($conn,$dcount);
if (mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_assoc($result)){
echo $row["table_name"].":".$row["max"]."\n";
}
} else {
echo '0';
}
SELECT d.max(id) as d_max_id, a.max(int) as a_max_int FROM deposits as d JOIN anothertable as a ON d.id = a.id;
is what you need for multiple tables
$row['d_max_id']
will give you deposits.max(id) now
You have to edit the d.id = a.id accordingly to what you want the two tables to match on
If you cant join try this:
SELECT max(id) as max_id, (SELECT max(int) FROM anothertable) as max_int FROM deposits;
SELECT max(id) as max_id, max(int) as max_int FROM deposits ,anothertable
i have a table with staff_id and subjects, i want to display all staffs according to their subjects.
my table
result i want
Physics
-001
-004
-006
Chemistry
-002
-009
Biology
-003
-008
Mathematics
-005
My code
$q = mysql_query("Select staff_id from my_table");
while($row = mysql_fetch_array($q)){
echo $subject .'</br>';
echo $staff_id.'</br>';
}
but this doesn't give the result i want.
any help?
What you need is ORDER BY.
Change your query to:
SELECT STAFF_ID, SUBJECT FROM my_table ORDER BY SUBJECT, STAFF_ID
So you get the records in the right order to work with them.
Something like this?
$q = mysql_query("SELECT `staff_id`, `subject` FROM `my_table`;");
$data = array();
while($row = mysql_fetch_array($q)){
$data[$row['subject']][] = '-'.$row['staff_id'];
}
print_r($data);
Or to echo out the rows
foreach($data as $heading => $rows){
echo $heading.'<br>';
foreach($rows as $row){
echo $row.'<br>';
}
}
You can write your code like this below:
$q = mysql_query("SELECT * FROM my_table ORDER BY SUBJECT, STAFF_ID");
while($row = mysql_fetch_array($q)){
//Do staff
}
The following code should help. You should split each subject into a separate array within your query. Once your query is complete, you should iterate through the subject array, and then within each staff id.
$subjects = array();
$q = mysql_query("Select staff_id from my_table");
while($row = mysql_fetch_array($q)){
if ($subjects[$row['SUBJECT']] == nil) {
$subjects[$row['SUBJECT']] = array();
}
array_push($subjects[$row['SUBJECT']], $row['STAFF_ID']);
}
foreach ($subjects as $key=>$value) {
echo $key . '<br>;
foreach ($vaue as &$staff) {
echo $staff . '<br>';
}
}
$result=mysql_query("SELECT * from table GROUP BY subject");
while($ext=mysql_fetch_object($result)) {
$query=mysql_query(" SELECT * from table WHERE subject='".$ext->subject."'");
echo $ext->subject;
while($res=mysql_fetch_object($query)) {
echo $res->staff_id;
}
}