<?php
session_start();
include 'connection.php';
$user_answer = $_POST['answ'];
$random = rand(1, 20);
if(isset($_POST['btn']))
{if ($user_answer == $_SESSION['answer']) {
echo '<br>RIGHT ANSWER<br>';
} else {
echo '<br>WRONG, THE RIGHT ANSWER IS ' . $_SESSION['answer'] . '<br>';
}
}
$sql = "SELECT Questions,Answers FROM history WHERE questions_id=$random";
$sth = $conn->query($sql);
$sth->execute();
$result = $sth->fetch(PDO::FETCH_ASSOC);
//print_r($result);
echo 'QUESTION: ' . $result['Questions'];
$_SESSION['answer']=$result['Answers'];
?>
Hello. I am new to this php pdo thing. I wanted to make a query that fetches question and checks the answer input by users. But I cannot do this with various codes also. It always fetches the next questions and answer. SO gives wrong answer output.And is there any methods to continue the session cause its redirecting to my homepage
I misunderstood the question:
Please try this:
if(isset($_POST['btn']))
{
if (trim($user_answer) == trim($_SESSION['answer'])) {
echo '<br>RIGHT ANSWER<br>';
} else {
echo '<br>WRONG, THE RIGHT ANSWER IS ' . $_SESSION['answer'] . '<br>';
}
unset($_SESSION['answer']);
}
I have unset the session variable.Please try this.
Related
How it looks:
https://jsfiddle.net/jef2L8m6/
How it should look:
https://jsfiddle.net/jef2L8m6/1/
I know it looks really bad, this is just for testing purposes only.
Some of the Backend Code:
<?php //Selects all of the logged in users messages.
$name = $_SESSION["name"];
$con = mysqli_connect('localhost','root','','chat');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"ajax_demo");
$sql="SELECT * FROM `chat` ORDER BY date";
$result = mysqli_query($con,$sql);
$numrows = mysqli_num_rows($result);
if( $numrows == "0" or !isset($_SESSION["name"])){
echo "<div class='msg'>You are not registered (Or there are no messages to display)</div>";
exit();
}else{
echo "";
}
echo "<div class='msg_container'>";
while($row = mysqli_fetch_array($result)) {
echo "<div class='msg_user'>";
echo "<div class='username_user'><span>" . $row['username'] . "</span></div>";
echo "<div class='message_user'><span>" . $row['message'] . "</span></div>";
echo "</div>";
}
echo "";
mysqli_close($con);
?>
Thank you so much for taking your time to read this.
I am trying to figure out how I would change the div tags of each separate user depending on their name?
Is there any way to do this using PHP, I have tried doing 2 separate query's of one that selects just the users messages and another that selects everyones (excluding the users)
But none of them worked due to it not ordering them correctly.
Could I somehow change the div's using PHP if the username that comes out is not equal to the username in the session?
Thank's so much, if you don't think I explained this very well please give me some feedback and I will change/add what you need, THANK YOU!
Thank you so much "u_mulder", you have been very helpful in making me think of a simple way to solve this problem.
I was thinking way too complex for something so simple!
Here is the final code for anyone who this may help:
while($row = mysqli_fetch_array($result)) {
$class_msg = "msg";
$class_username = "username";
$class_message = "message";
if ($row['username'] == $_SESSION['name']) {
$class_msg = "msg_user";
$class_username = "username_user";
$class_message = "message_user";
}
echo "<div class='$class_msg'>";
echo "<div class='$class_username'><span>" . $row['username'] . "</span></div>";
echo "<div class='$class_message'><span>" . $row['message'] . "</span></div>";
echo "</div>";
}
while($row = mysqli_fetch_array($result)) {
$class = 'msg';
if ($row['username'] == $_SESSION['name']) {
$class = 'msg_user';
}
echo "<div class='" . $class . "'>";
// other codes here
}
so basically I want to make an online dictionary, the word to be searched for is introduced by an input, and I want to make so that if it can't find the word+definition in db to say a message like "We couldn't find any definition" or something like that, in my code because it can't find it , it ways "undefined variable"
<?php
include ("header.php");
$search = $_POST['se'];
include ("connect.php");
$dictionary=mysqli_query($con,"SELECT * FROM `dictionary` WHERE word = '$search'");
while($row = mysqli_fetch_array( $dictionary )) {
$word=$row['word'];
$description=$row['definition'];
}
echo "<div class=\"webResult\">
<h2>$word</h2>
<p>$description</p>
</div>";
include ("footer.php");
?>
P.S.: I know my code is vulnerable to SQLi , but I'll fix that later.
try wrapping the undefined vars in isset
if (isset($word) && isset($description)) {
echo "<div class=\"webResult\">
<h2>$word</h2>
<p>$description</p>
</div>";
}
else {
echo "Nothing found";
}
Same goes for $search = $_POST['se'];
if(!isset($_POST['se'])) {
echo "Nothing found";
exit;
}
if($row = mysqli_fetch_array( $dictionary )) {
$word=$row['word'];
$description=$row['definition'];
echo "<div class=\"webResult\">
<h2>$word</h2>
<p>$description</p>
</div>";
} else {
echo "$search not found";
}
while($row = mysqli_fetch_array( $dictionary )) {
$word=$row['word'];
$description=$row['definition'];
}
if(!empty($word) && !empty($description)){
echo '<div class=\"webResult\">';
echo '<h2>$word</h2>';
echo '<p>$description</p>';
echo '</div>";
}else{
echo 'could not find your word';
}
include ("footer.php");
?>
You have to validate your variables if its have value or not
The variables $word and $description are first created inside the while loop. This means that they do not have any scope outside it. This should be the most probable cause, since you are getting a variable not defined error.
There are a couple of options here.
One, you could create these variables outside the while loop, and then assign them new values as you are doing now. Here is what your code might look like, if you choose to do it this way:
$search = $con->escape_string($_POST['se']);
$dictionary = $con->query("SELECT * FROM `dictionary` WHERE word = '$search'");
$word = "";
$description = "";
while($row = $dictionary->fetch_assoc())
{
$word = $row['word'];
$description = $row['definition'];
}
if (!empty($word) && !empty($description))
{
echo '<div class="webResult"><h2>' . $word . '</h2><p>' . $description . '</p></div>';
}
else
{
echo "We couldn't find any definition";
}
This will work for you if you have multiple results in the returned mysqli_resource, and want to use the last in the list.
Two, if you are likely to get only one result returned, or if you just want to use the first result in the list, you can have the echo statement inside an if statement that checks if a valid result is returned. For example:
$search = $con->escape_string($_POST['se']);
$dictionary = $con->query("SELECT * FROM `dictionary` WHERE word = '$search'");
$word = "";
$description = "";
$row = $dictionary->fetch_assoc();
if($row)
{
$word = $row['word'];
$description = $row['definition'];
if (!empty($word) && !empty($description))
{
echo '<div class="webResult"><h2>' . $word . '</h2><p>' . $description . '</p></div>';
}
else
{
echo "We couldn't find any definition";
}
}
Note:
In the above examples, we use !empty() to check the variables. This is because isset() is pointless here, since we have already created (set) the variables ourselves.
Things to read up:
Scope of variables - http://php.net/manual/en/language.variables.scope.php
empty() function - http://php.net/manual/en/function.empty.php
Object oriented mysqli - http://php.net/manual/en/mysqli.quickstart.dual-interface.php
Try this:
include ("header.php");
$search = $_POST['se'];
include ("connect.php");
$dictionary=mysqli_query($con,"SELECT * FROM `dictionary` WHERE word = '$search'");
while($row = mysqli_fetch_array( $dictionary )) {
$word=$row['word'];
$description=$row['definition'];
}
if(isset($word)){
echo "<div class=\"webResult\">
<h2>$word</h2>
<p>$description</p>
</div>";
}
else{
echo "We couldn't find any definition";
}
include ("footer.php");
I have problem with my code.
I use nested while in my code and the nested while doesn't work, only the outer while is work
I don't know where is the bug of my code.
This is the piece of my code :
$database = new mysqli('127.0.0.1', 'user', 'user', 'mini_email');
$query = 'SELECT * FROM mails';
$query2 = 'SELECT * FROM users';
$result_set = $database->query($query);
$result2 = $database->query($query2);
while ($row2 = $result2->fetch_assoc()) {
if ($row2['username'] == $_SESSION['user']) {
$id_email = $row2['id'];
}
}
if (isset($_SESSION['is_logged_in'])) {
echo('<center><font size="10">Mailing List</font></center><br><br>');
echo('<center><table border="3" bgcolor="#f0cdfa">');
echo('<tr>');
echo ('<td>No</td>');
echo ('<td>ID</td>');
echo ('<td>From</td>');
echo('<td>Subject</td>');
echo ('<td>Message</td>');
echo ('<td>Action</td>');
echo ('</tr>');
$i = 1;
while ($row = $result_set->fetch_assoc()) {
if ($row['to_user_id'] == $id_email) {
echo('<tr>');
echo ('<td>' . $i . '</td>');
echo ('<td>' . $row['id'] . '</td>');
while($row2 = $result2->fetch_assoc()){
if($row2['id']== $row['from_user_id']){
echo ('<td>' . $row2['username'] . '</td>');
}
}
echo ('<td>' . $row['subject'] . '</td>');
echo ('<td>' . $row['message'] . '</td>');
echo ('<td>View</td>');
echo ('</tr>');
$i++;
}
}
Your initial
while ($row2 = $result2->fetch_assoc()) {
is looping through all the records to the end of the set,
so looping a second time won't retrieve any further records because you're already at the end of the resultset
Resultset pointers aren't automatically reset when you initiate a new loop, but you can reset them manually using
$result2->data_seek(0);
before each subsequent loop
But iterating the point made in the comments by #Sirko you'd be better using a JOIN to make a single query
If I may help, I think you shouldn't even perform the queries when your if statement with the session returns false.
In the first lines or your script you should define a function with all this code, and write it like this :
function YourFunction()
{
if (isset($_SESSION['is_logged_in'])) {
return false;
}
// Database connection and queries
// your business
}
This will be more clean.
Next, your query doesn't seem to be correct. You get all the mails of your website, and then in a loop you check if the mail user id is the user id you have in session. Imagine the lack of performance if you have 35 000 mails in your database.
Improve your query with a WHERE statement : http://www.w3schools.com/sql/sql_where.asp
then, are you sure that $_SESSION['user'] contains an id ? I think your second if statement never returns true because of that.
Alright so I have created a blog from scratch and mistakenly started to write it with mysql_ statements so I have gone back and rewritten it with PDO statements. I have now encountered a problem with displaying my blog post from my database.
<?php
include 'includes.php';
echo '<h3>-----------------------------------------------------</h3>';
$blogIndex = 'SELECT * FROM blog_post ORDER BY date_posted DESC';
$blogIndexstmt = $DBH->prepare($blogIndex);
$blogIndexRows = $blogIndexstmt->fetchAll();
if(!$blogIndexRows) {
echo 'No Post Yet.';
}
else {
while($blogIndexRows->nextRowset()) {
echo '<h2>' . $row['title'] . '</h2>';
$datePosted = $row['date_posted'];
echo '<p>' . gmdate('F j, Y, g:i a', $datePosted) . '</p>';
$body = substr($row['post'], 0, 300);
echo nl2br($body) . '...<br/>';
echo 'Read More | ';
echo '<a href="post_view.php?id=' . $row['id'] . '#comments">' .
$row['num_comments'] . ' comments</a>';
echo '<hr/>';
}
}
$DBH = null;
echo <<<HTML
+ New Post
HTML;
?>
It does not display anything, not even an error code. I was able to do it correctly with the mysql_ statement but I really want to learn how to do this correctly. I am just looking for a nudge in the right direction, you do now have to code it for me. Thanks for you help in advance!
Let's start from the beginning.
You don't use a prepared statement if you are not passing any parameters.
What does that mean? Simply issue PDO's query function.
It would be like this:
$query = $DBH->query('SELECT * FROM blog_post ORDER BY date_posted DESC');
If something went wrong, $DBH->query will return FALSE or PDOStatement on success. So next line is to check whether it's false:
if($query === false)
{
echo $DBH->errorCode();
}
else
{
// Everything went fine, let's fetch results
$results = $query->fetchAll(PDO::FETCH_ASSOC);
// If there are any records returned, our array won't be empty.
if(count($results))
{
// $results contains all of your records. You can now loop it with for, foreach and you don't need a while loop anymore
foreach($results as $row)
{
print_r($row);
}
}
else
{
echo "There are no records in the database table :(";
}
}
Updated with suggestion by others but still seem to be stuck.
I'm using this php code here to display info from my database using the ID. I created a link on my main page that looks like this.
<h1><?php echo $row_getDisplay['title']; ?></a></h1>
I have so when they click on the title of the article that it takes them to my php fiel which I named fetch.php and the code below is what is in there. I have built this around someone else's work. For some reason I can't get passed the first "else" statement. so I keep getting "you must select a valid location" I'm fairly new to php so I don't really understand why the code is failing.
<?php require_once('Connections/XXXXXX.php'); ?>
<?php
if (isset($_GET['id']) == false) // check if id has been set
{
echo "You must select a location"; // if not, display this error
exit;
} else {
$id = (int) $_GET['id'];
if (is_numeric($id) == false)
**{
echo "You must select a valid location.";
} else {**
mysql_select_db($database_XXXXXX, $XXXXXX);
$query = MYSQL_QUERY("SELECT * FROM news WHERE post_id ");
if (MYSQL_NUM_ROWS($query) == "1")
{
$fetch = MYSQL_FETCH_ARRAY($query); // set $fetch to have the values from the table
echo "Title: " . $fetch['title'] . "<BR>"; // output the info
echo "Blog: " . $fetch['blog_entry'] . "<BR>"; // etc...
echo "Author: " . $fetch['author'] . "<BR>"; // etc...
} else {
echo "No match in database found."; // if no match is found, display this error
}
}
}
Any help is appreciated. If you are able to find a better solution for me that would be great.
You shouldnt use $HTTP_GET_VARS its deprecated and unless its turned on it wont be populated. use $_GET instead.
if (isset($_GET['id']) == false)
Use $_GET for your if statement:
if (isset($_GET['id']) == false)
Also, you need to convert your $_GET value to an integer, because it is currently a string.
Right after that if statement above, in the else, put this:
$id = (int) $_GET['id'];
That way your is_numeric() will work properly.
Try this;
<?php
require_once('Connections/XXXXXX.php');
if (isset($_GET['id'])) // check if id has been set
{
$id = $_GET['id'];
if (is_numeric($id) == false)
{
echo "You must select a valid location.";
} else {
mysql_select_db($database_XXXXXX, $XXXXXX);
$query = MYSQL_QUERY("SELECT * FROM news WHERE locationid = 'news.post_id' ");
if (MYSQL_NUM_ROWS($query) == "1")
{
$fetch = MYSQL_FETCH_ARRAY($query); // set $fetch to have the values from the table
echo "Title: " . $fetch['title'] . "<BR>"; // output the info
echo "Blog: " . $fetch['blog_entry'] . "<BR>"; // etc...
echo "Author: " . $fetch['author'] . "<BR>"; // etc...
} else {
echo "No match in database found."; // if no match is found, display this error
}
}
}
else{
echo "You must select a location"; // if not, display this error
exit;
}
?>
Also, I need a clarification about news.post_id, from where are you grabbing this?