I have a 2-column table which I create like this (each user has a table for himself):
$sql = "CREATE TABLE $user_name (
driver TINYTEXT NOT NULL,
reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)";
I have (manually, using phpMyAdmin) inserted data into one such a table. reg_date was set at current time and some random string (numerical, say 01234) was inserted.
I try accessing the rows like this:
$mysql_qry2 = "SELECT * FROM $username";
$result2 = mysqli_query($conn, $mysql_qry2);
$ans = "";
if(mysqli_num_rows($result2) > 0) {
while ($row = mysqli_fetch_assoc($result2)) {
$ans = $ans . $row["driver"];
$ans = $ans . " ";
$x = $row["driver"];
echo "$x";
echo "a";
}
$ans = $ans . "asd";
echo "$ans";
} else {
echo "b";
}
edit: after fixing my mistaken variable name, the "SELECT *" query is returning zero rows despite 3 rows of data being there.
You checked count of wrong variable mysqli_num_rows($result) > 0.
$mysql_qry2 = "SELECT * FROM $username";
$result2 = mysqli_query($conn, $mysql_qry2);
$ans = "";
if ($result2->num_rows > 0) {
// output data of each row
while($row = $result2->fetch_assoc()) {
$ans = $ans . $row["driver"];
echo "$ans";
echo "a";
}
} else {
echo "b";
}
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.
}
}
}
The below code isn't printing out the lowest number in the database table. There is currently 4 entries - only three print out. The lowest ID number, doesn't print.
Code:
### Run Query
$query = "SELECT * from `Reminders`";
$run = mysqli_query($connection, $query);
$check = mysqli_fetch_array($run);
### Fetch Data
if($check > 0)
{
while($row = mysqli_fetch_assoc($run))
{
$ID = $row['ID'];
$Text = $row['rText'];
$Number = $row['rNumber'];
$Date = $row['rDate'];
$Time = $row['rTime'];
echo "'$Text' to '$Number' on $Date at $Time.<br/>";
}
}
Remove the $check part, and that's where the lowest one gone. For counting number of rows returned, use mysqli_num_rows() function.
### Run Query
$query = "SELECT * from `Reminders`";
$run = mysqli_query($connection, $query);
// Change here... :)
$check = mysqli_num_rows($run);
### Fetch Data
if ($check > 0) {
while ($row = mysqli_fetch_assoc($run)) {
$ID = $row['ID'];
$Text = $row['rText'];
$Number = $row['rNumber'];
$Date = $row['rDate'];
$Time = $row['rTime'];
echo "'$Text' to '$Number' on $Date at $Time.<br/>";
}
}
From php manual :- http://php.net/manual/en/mysqli-result.num-rows.php
mysqli_num_rows() function is used for returning the number of rows
in the result set.
So, Just Replace this of code,
$check = mysqli_fetch_array($run);
with this line,
$check = mysqli_num_rows($run);
I have been trying to compare value in a table with another value in another table but only the else part is executing.
<?php
$sql = "SELECT * FROM user WHERE user_id=$row[user_id]";
$result = $conn -> query ($sql);
if ($result -> num_rows > 0) {
while ($row = $result ->fetch_assoc()) {
$sql1 = "SELECT * FROM jobpost WHERE jobpost_id=$_GET[id] ";
$result1 = $conn -> query ($sql1);
$row_count = mysqli_num_rows($result);
$row1_count = mysqli_num_rows($result1);
$remaining_rows = min($row_count, $row1_count);
$row = mysqli_fetch_assoc($result);
$row1 = mysqli_fetch_assoc($result1);
if($row["experience"] > $row1["experience"])
{
//some code to display something
echo "1";
}
else
{
echo "2";
}
} }
?>
Welcome to SO, it is hard to read your source code. You can use a simple query like this:
SELECT IF(u.experience > j.experience,1,0) FROM
(
(SELECT experience FROM user WHERE user_id = 1) u
JOIN
(SELECT experience FROM jobpost WHERE jobpost_id = 8) j
)
Try this query here: http://sqlfiddle.com/#!9/1742c0
Please check our datasource. Maybe the else case is correct.
I want to display hospital names from database by two ways:
By Selecting city.
By entering the name of hospital in search bar.
I wrote below php script. The 1st part works fine and shows all hospitals from a selected city, but 2nd part doesn't work for me. There is no error displayed. Need help with this. Did i not put the 'if' conditions in the right place? Or I missed something else?
if (isset($_POST['search'])) {
if (isset($_POST['search-by-city'])) {
$city_id = $_POST['search-by-city'];
$query = "SELECT * FROM `hospitals` WHERE `City_ID` LIKE '%$city_id%'";
$result = mysqli_query($con,$query);
if (mysqli_num_rows($result) == 0) {
echo '<h2>No recod Found</h2>' ;
}
}
if (isset($_POST['search-by-name'])) {
$hospital_name = $_POST['search-by-name'];
$query = "SELECT * FROM `hospitals` WHERE `Name` LIKE '%$hospital_name%'";
$result = filterTable($query); {
if (mysqli_num_rows($result) == 0) {
echo '<h2>No recod Found</h2>' ;
}
}
while($row = mysqli_fetch_array($result)){
$city_id = $row[3];
$query = "SELECT `Name` FROM `cities` WHERE `ID` LIKE '$city_id'";
$result2 = mysqli_query($con,$query);
$row2 = mysqli_fetch_row($result2);
$city_name = $row2[0];
echo '
<h3>'.$row[1].'</h3>
<h4>'.$city_name.'</h4>
';
}
}
My code looks like this:
$sql = "SELECT `sw1`, `sw2`, `sw3`, `sw4`, `fb1`, `fb2`, `fb3`, `fb4`, `bew1`, `bew2`, `bew3`, `bew4` FROM `reg` WHERE `id` = ".$id." ORDER BY `id` ASC LIMIT 0, 30 ";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
foreach($row as $x => $x_value) {
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
}
}
There is some data in sw2 but it isn't shown.
When I tryed to UPDATE data the data in the db wasn't changed.
$id is right.
other data from the table could be read.
This code works fine:
$sql = "SELECT * FROM `reg` WHERE `id` = ".$id." ORDER BY `id` ASC LIMIT 0, 30 ";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$row = $result->fetch_assoc();
print_r($row);
}
Try your query with echo.
same trouble follows try changing Where 'id' = "$id"
to Where 'id' like "$id"
You dont need quotes:
$sql = "SELECT sw1, sw2, sw3, sw4, fb1, fb2, fb3, fb4,
bew1, bew2, bew3, bew4
FROM reg WHERE id = $id";