This question already has answers here:
Split a comma-delimited string into an array?
(8 answers)
Closed 3 years ago.
Extracting Values from Nested JSON Data !
$response = array();
$result = mysqli_query($conn, "
SELECT id, GROUP_CONCAT(CONCAT_WS(':', Name) SEPARATOR ',') AS Result
FROM mytbl GROUP BY id
");
mysqli_num_rows($result);
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_assoc($result)){
$char = array("id"=>$row["id"], "char"=>[$row["Result"]]);
array_push($response,array('Attr'=>$char));
}
}
echo json_encode($response);
i added photo for what i need
Just Explode it with PHP
$response = array();
$result =mysqli_query($conn, "
SELECT id, GROUP_CONCAT(CONCAT_WS(':', Name) SEPARATOR ',') AS Result
FROM mytbl GROUP BY id ");
mysqli_num_rows($result);
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_assoc($result)){
$char = array("id"=>$row["id"],"char"=>explode(',', $row["Result"]));
array_push($response,array('Attr'=>$char));
}
}
Related
This question already has answers here:
How to transform array to comma separated words string? [duplicate]
(4 answers)
Closed 10 months ago.
$get_top10 = mysqli_query($con, "SELECT name, daily_points, daily_win FROM players WHERE daily_points > 0 ORDER BY daily_points DESC LIMIT 10");
I am needing a string like:
name, daily_points, daily_win, name, daily_points, daily_win (etc up to 10 records)
php 7.4.27
mysql 5.6.51-cll-lve
This did the trick, let me know if there is a better or preferred method.
$sql = ("SELECT name, daily_points, daily_win FROM players WHERE daily_points > 0 ORDER BY daily_points DESC LIMIT 10");
$result = mysqli_query($con, $sql);
if (mysqli_num_rows($result)) {
while ($row = mysqli_fetch_assoc($result)) {
echo "{$row['name']},{$row['daily_points']},{$row['daily_win']},";
}
}
you can try this code it will concatenate your php variable to html ','
and it's a preferred method
$sql = ("SELECT name, daily_points, daily_win FROM players WHERE daily_points > 0 ORDER BY daily_points DESC LIMIT 10");
$result = mysqli_query($con, $sql);
if (mysqli_num_rows($result)) {
while ($row = mysqli_fetch_assoc($result)) {
echo $row['name'].','.$row['daily_points'].','.$row['daily_win'];
}
}
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.
}
}
}
This question already has answers here:
Array in SQL Query? [duplicate]
(4 answers)
Closed 5 years ago.
I'm trying to create a tag function in my webpage and I'm using an array of tags to query the database.
array[tag1, tag2, tag3];
The tags are created in a field
what I'm trying to archive is something like
$query = "SELECT * FROM TABLE WHERE `Tags` = '$tag1' AND '$tag2' AND '$tag3'";
Except with an array, so
$query = "SELECT * FROM TABLE WHERE `Tags` = $array[]";
Thanks
$tag = $_POST['tag'];
$query = "SELECT * FROM ComicStripTags WHERE `Tag` = '$tag'";
$result = mysqli_query($link, $query);
while ($row = mysqli_fetch_array($result)){
$ID[] = $row['ImageID'];
print_r ($ID);
}
BTW I want to use $ID[] to use in another query
Try using implode to convert array to string, and use "IN" operator instead of equal:
$query = "SELECT * FROM TABLE WHERE `Tags` in (". implode(", ",$array) .")";
This question already has answers here:
Get the single value of a sql result set
(3 answers)
Closed 9 years ago.
I have this query:
$result = "SELECT MAX(N) as maxid FROM (
SELECT SUBSTRING(id_f, 2,len(id_f) -1) as N
From formas WHERE id_f LIKE '%D%'
) t" ;
$res = odbc_exec($connection, $result) or die(odbc_error());
Now, if i put the query in SQL SERVER i get the correct result.
What i need is to save the maxid as a variable.. how to do it?
Thanks
What you need is the function odbc_fetch_array.
$result = "SELECT MAX(N) as maxid FROM (
SELECT SUBSTRING(id_f, 2,len(id_f) -1) as N
From formas WHERE id_f LIKE '%D%'
) t" ;
$res = odbc_exec($connection, $result) or die(odbc_error());
$info = odbc_fetch_array($res);
$content[] = $info;
$maxN = $content[0]
For a multiple rows query, you need to encapsulate the function in a while loop :
while($row = odbc_fetch_array($res))
{
print_r($row);
}
This question already has answers here:
SELECT COUNT(*) AS count - How to use this count
(5 answers)
Closed 1 year ago.
$query = "select count(*)
from relationships
where leader = 'user_id'";
$result = mysql_query($query);
how can i display the count? thanks
$count = mysql_fetch_array($result);
echo $count[0];
$query = "SELECT COUNT(*) AS total FROM table";
$result = mysql_query($query);
$values = mysql_fetch_assoc($result);
$num_rows = $values['total'];
echo $num_rows;
use $row = mysql_fetch_array($result) and access it by index 0: $row[0]
use an alias in your query ("select count(*) as cnt from ...") and $row = mysql_fetch_assoc($result) and access it by name: $row['cnt']
$abc="SELECT count(*) as c FROM output WHERE question1=4";
$result=mysqli_query($conn,$abc);
if($result)
{
while($row=mysqli_fetch_assoc($result))
{
echo $row['c'];
}
}
Its work completely in this it count the number of occurrences of 4 in the column