This question already has answers here:
SET a variable in SELECT statement - MySQL
(2 answers)
Closed 4 years ago.
i want to rank my users by score from my 'scores' table with php using mysql . i wrote this query that is actually working in SQL Tab of phpMyAdmin :
SET #rank=0;
SELECT #rank:=#rank+1 AS rank, name, score
FROM scores
ORDER BY score DESC;
but i cant figure it out , how to use it in my php Code . i tried:
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row["score"]. $E ." ". $row["name"]. $N ;
echo PHP_EOL;
echo PHP_EOL;
}
} else {
echo "0 results";
}
i think my problem is with my while loop . but i dont know what should i do :(
PleaseHelp(); :(
guys problem was solved . Our Dear Friend #mallik1055 noticed that the problem was with query and im sending multiple request . then i noticed That phpMyAdmin automatically runs multiple query unlike PHP , so i tried mysqli_multi_query and it worked , thank you a lot <3
That should work.
$rank = 0;
$rank = $rank+1;
$sql = "SELECT rank, name, score FROM scores ORDER BY score DESC";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
if ($row > 0) {
while($row > 0) {
echo $row["score"].$E." ".$row["name"].$N.;
echo PHP_EOL;
echo PHP_EOL;
}
} else {
echo "0 results";
}
$row["rank"] is an element in your fetched rows, just like "score" and "name"
Related
This question already has answers here:
MySQL select 10 random rows from 600K rows fast
(28 answers)
Closed 4 years ago.
i have a table named quiz ,it have six columns like id,question,option1,option2,option3,answer.i want to loop through all the values by using the following query
$sql = "SELECT id, option1, option2,option3,answer,question FROM quiz";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - question: " . $row["question"]. " " .
$row["option1"]. "<br>";
}
How can i get random values from mysql table everytime i want only 4 values.I am new to development .
welcome to Stackoverflow!
Use this;
$sql = "SELECT id, option1, option2,option3,answer,question FROM quiz ORDER BY RAND() LIMIT 4";
This will get rows 100% randomly! But, it can get you duplicates..
This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 4 years ago.
The below query works fine whenever I try it in phpmyadmin:
SELECT CAST(DATETIME AS DATE), Provider, COUNT(Provider)
FROM purchases
GROUP BY CAST(DATETIME AS DATE), Provider
ORDER BY CAST(DATETIME AS DATE) DESC
Nevertheless I always received a boolean when I placed it inside my PHP script:
$sql="SELECT CAST(DATETIME AS DATE), Provider, COUNT(Provider)
FROM purchases
GROUP BY CAST(DATETIME AS DATE), Provider
ORDER BY CAST(DATETIME AS DATE) DESC";
if (mysqli_query($con,$sql))
{
$result = mysql_query($sql);
while($row = mysql_fetch_assoc($result)) {
echo $row['CAST(DATETIME AS DATE)'];
echo $row['Provider'];
echo $row['COUNT(Provider)'];
}
}
else
{
echo "Error creating table: " . mysqli_error($con);
}
mysqli_close($con)
;
I really would appreciate some advice about how to tackle this issue.
this code write like below so its work fine
you use mysqli in all query and check if $result has value than print record otherwise error message was print
$result = mysqli_query($con,$sql);
if($result)
{
while($row = mysqli_fetch_assoc($result)){
echo $row['CAST(DATETIME AS DATE)'];
echo $row['Provider'];
echo $row['COUNT(Provider)'];
}
}
else
{
echo "Error creating table: " . mysqli_error($con);
}
mysqli_close($con)
$req = $conn->prepare('SELECT SUM(VoteValue) AS FinalScore FROM votes WHERE URL="TCeLkdTOWM"');
$req->execute();
$data = $req->fetch();
$total = $data['FinalScore'];
echo "Score is ".$total." <br>";
So I have theoretically that should theoricaly do a total of all values that are in the column VoteValue and that has TCeLkdTOWM in the column URL of my mysql table (See my Mysql Table below)
URL VoteIP VoteValue
TCeLkdTOWM 10.0.0.1 6
TCeLkdTOWM 10.0.0.2 -1
eoirjgo 10.0.0.8 450
It should do 6+(-1) in the background and I should get "Score is 5" on my page but
The thing is, it's not working, there is no error code, nothing I'm just getting "Score is" with nothing else
mysqli_stmt->fetch() doesn't return the results of your query. That simply isn't how this function works.
Either use (with bind_result and fetch)
$req->execute();
$req->bind_result($finalScore);
if ($req->fetch()) {
echo "Score is " . $finalScore;
}
or (with get_result and fetch_assoc)
$req->execute();
$result = $stmt->get_result();
if ($data = $result->fetch_assoc()) {
echo "Score is " . $data['FinalScore'];
}
I can simply not figure this out. I am quite sure I am doing it the wrong way, but I am fairly new to PHP and SQL.
What I am doing is generating these HTML 'question blocks' in a while loop, these contain a little query information, including a voting button. What I want to do is to remove that voting button if the user has already voted.
I am using a query to check if the User has already voted using the QuestionID and the user's IP address.
I am able to stop the user from voting, (the button does nothing), but I can't for the life of me, remove the button for the questions the user has already voted on.
Below is a code I have tried to write to accomplish this (IP address is gotten elsewhere)
//Query for selecting the information I want in the blocks.
$stmt = $conn->prepare("SELECT * FROM question_answers
INNER JOIN question
ON question_answers.QuestionID=question.QuestionID
INNER JOIN answers
ON question_answers.AnswerID=answers.AnswerID
WHERE HasBeenTray = 0 OR HasBeenTray = 1 AND QuestionVotes > 2000
ORDER BY QuestionVotes DESC LIMIT 8");
$stmt->execute();
$result = $stmt->get_result();
//Checking to see if Query has generated any result (rows)
if ($result->num_rows > 0) {
//Counter for generating HTML at the right place
$counter = 0;
echo "<div class=\"row tabs\">";
echo "<h2>Top 8 over stillede spørgsmål:</h2>";
//Use results from first query to generate HTML
while($row = $result->fetch_assoc()) {
//Save QuestionAnswerID - Id of the question block clicked
$id = $row["QuestionAnswerID"];
//Second query to check if QuestionAnswerID and UserID (IP Address) has already been paired
$stmt = $conn->prepare("SELECT * FROM user_votes where UserID = ? and QuestionAnswerID = ?");
$stmt->bind_param('ss', $ip_long, $id);
$stmt->execute();
$result = $stmt->get_result();
//Second while loop to generate 'question blocks' without vote button
while($row = $result->fetch_assoc()) {
$counter++;
echo "<div class=\"col-md-3\"><h3>". $row["Answer1Text"]. " vs. ". $row["Answer2Text"]. " </h3><p>". $row["QuestionText"]. "</p></div>";
if($counter % 4 == 0) {
echo "</div><div class=\"row tabs\">";
}
}
//Generate rest of 'question blocks' with voting buttons
$counter++;
echo "<div class=\"col-md-3\"><h3>". $row["Answer1Text"]. " vs. ". $row["Answer2Text"]. " </h3><p>". $row["QuestionText"]. "</p><p><a data-ks-load-selector=\"#change\" href=\"index.php?id=". $row["QuestionAnswerID"]. "\" class=\"btn btn-success\"> " . $row["QuestionVotes"] . "</a></p></div>";
if($counter % 4 == 0) {
echo "</div><div class=\"row tabs\">";
}
}echo "</div>";
Tables with elements of importance:
question - QuestionID(PK), QuestionText
answers - AnswerID(PK), Answer1Text, Answer2Text
question_answers - QuestionAnswerID(PK), AnswerID(FK), QuestionID(FK), QuestionVotes
user_votes - QuestionAnswerID(FK), UserID
At first, I changed $stmt and $result inside the loop to $stmt2 and $result2 so as not to overwrite the original resultset, and used an if to generate the vote button if the user hasn't voted.
However, I don't like running queries in a loop, so we can rather use a left join and check whether we got a matching UserID or not. Additionally, I modified your query to select fields explicitly. This can prevent field name conflicts and it helps performance to limit the size of your result.
//Query for selecting the information I want in the blocks.
$stmt = $conn->prepare("SELECT qa.QuestionAnswerID, a.Answer1Text, a.Answer2Text, q.QuestionText, uv.UserID, qa.QuestionVotes
FROM question_answers qa
INNER JOIN question q
ON qa.QuestionID=q.QuestionID
INNER JOIN answers a
ON qa.AnswerID=a.AnswerID
LEFT JOIN user_votes uv
ON uv.UserID = ? AND uv.QuestionAnswerID = qa.QuestionAnswerID
WHERE HasBeenTray = 0 OR HasBeenTray = 1 AND qa.QuestionVotes > 2000
ORDER BY qa.QuestionVotes DESC LIMIT 8");
$stmt->bind_param('s', $ip_long);
$stmt->execute();
$result = $stmt->get_result();
//Checking to see if Query has generated any result (rows)
if ($result->num_rows > 0) {
//Counter for generating HTML at the right place
$counter = 0;
echo "<div class=\"row tabs\">";
echo "<h2>Top 8 over stillede spørgsmål:</h2>";
//Use results from first query to generate HTML
while($row = $result->fetch_assoc()) {
//Save QuestionAnswerID - Id of the question block clicked
$id = $row["QuestionAnswerID"];
$counter++;
echo "<div class=\"col-md-3\"><h3>". $row["Answer1Text"]. " vs. ". $row["Answer2Text"]. " </h3><p>". $row["QuestionText"]. "</p>";
//If user hasn't voted, generate vote button
if (is_null($row['UserID']) {
echo "<p><a data-ks-load-selector=\"#change\" href=\"index.php?id=". $row["QuestionAnswerID"]. "\" class=\"btn btn-success\"> " . $row["QuestionVotes"] . "</a></p>";
}
echo "</div>";
if($counter % 4 == 0) {
echo "</div><div class=\"row tabs\">";
}
}echo "</div>";
I feel like I'm missing something really simple here. Here's my sql query:
$getpages = "SELECT id FROM pages WHERE account = 2 ORDER BY page_order";
$showpages = #mysqli_query ($dbc, $getpages);
$row = mysqli_fetch_array($showpages, MYSQLI_NUM);
I then print the first result:
echo $row[0];
And get a correct value, the id of the first page (by page order):
10
So I submit a form which simply turns that $row[0] into $row[1].
And nothing prints. I don't understand.
You have to do this:
while ($row = mysqli_fetch_array($showpages, MYSQLI_NUM)) {
$id = $row[id];
// do something with the id
echo $id . "<br/>"; // Echo every id
}
This will iterate through all of the results
mysqli_fetch_array is a special function as each time you call it, it outputs the NEXT row.
So:
while ($row = mysqli_fetch_array(stuff)){
$var = $row['sql column'];
// In your case "$var = $row[0];" to get the id for the first row found.
}
is how you use it.
This will keep running the function until mysqli_fetch_array() eventually returns false. These each time it will output a new row. And the $row array is the array of one row in the sql table.
Use :
print_r($row);
in the while loop to see exactly what's being returned for use.
$getpages = "SELECT id FROM pages WHERE account = 2 ORDER BY page_order";
$showpages = #mysqli_query ($dbc, $getpages);
$row = mysqli_fetch_array($showpages, MYSQLI_NUM);
Question how many rows are fetched in this query in this case id, So MYSQL will result to 1 row affected, But since you are using
$row = mysqli_fetch_array($showpages, MYSQLI_NUM);
This code you used will not output anything try
$row[n] as n-1
$result->fetch_assoc() or mysqli_fetch_assoc($result)
catch one line at a time, from a mysqli_result:
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
source: http://www.w3schools.com/php/php_mysql_select.asp