I am trying to pull a random question from one of my tables and display it in HTML. The point is to have the user put in their info in a form, answer the random question that appears, and submit the form that will store the users info along with the question they were asked and their answer. I can't seem to get the question to show up in my HTML and I'm not sure how to fix this. Still new to mySQL.
Code:
<?php
define('DB_NAME', 'db');
define('DB_USER', 'admin');
define('DB_PASSWORD', 'password');
define('DB_HOST', 'localhost');
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('db', $link);
$db_selected = mysql_query("SELECT Question FROM QuestionDB ORDER BY RAND() LIMIT 1");
if (!$db_selected) {
die('Cant use ' . DB_NAME . ': ' . mysql_error());
}
if(isSet($_POST['submit'])) {
$fname = $row['f_name'];
$lname = $row['l_name'];
$email = $row['email'];
$question = $row['question'];
$answer = $row['answer'];
$sql = "INSERT INTO StudentDB VALUE ( NULL,'$fname','$lname','$email','$question','$answer')";
if (!mysql_query($sql)) {
die('Error: ' . mysql_error());
}
echo 'Thank you, your information has been sent';
}
else{
echo'
<!DOCTYPE HTML>
<html lang="en">
<head>
</head>
<body>
<form id = "myForm" method="POST">
<div class="col-sm-6" >
<h5><b>First Name: </b><br/><input type="text" name="f_name" size="70" required></h5> <br/>
<h5><b> Last Name: </b><br/><input type="text" name="l_name" size="70" required></h5> <br/>
</div>
<div class="col-sm-6" >
<h5><b>Email: </b><br/><input type="text" name="email" required></h5><br/>
</div>
<div class="col-sm-12" >
<br/><br/> Question: ' .$row["Question"]. '
</div>
<div class="col-sm-12" >
<br/><br/>
<h3><b>Answer:</b></h3>
<textarea maxlength="500" name="comment" id="comment"></textarea><br/>
</div>
<div class="col-sm-6" >
<input type="submit" name="submit" value="Submit">
</div>
</form>
</body>
</html>';
}
?>
On a side note running ORDER BY RAND() is not a good idea. It works to generate a random result, but it adds a lot of overhead which translates into long load times. If you start getting past 100 records you can see this really slow down MySQL queries and lead to long time to first byte wait times by the server. See here: http://www.titov.net/2005/09/21/do-not-use-order-by-rand-or-how-to-get-random-rows-from-table/
Related
I'm trying to access data from local wamp server from a Wordpress site using a Search box. I created the search box using the function get_search_form(), and I am unable to write a query in php to access using the same.
I have used Wamp server (localhost) and a Wordpress site.
I have tried writing an html code for the search box and tried to access the data using it. But it didn't work. I felt it's easy to run a single php script rather than a separate html and php scripts.
Code to fetch data from db:
$connect = mysqli_connect("localhost", "root", "", "mydb");
$output = '';
if(isset($_POST["query"]))
{
$search = mysqli_real_escape_string($connect, $_POST["query"]);
$query = "
SELECT * FROM clients;
WHERE Name LIKE '%".$search."%'
OR Aadhar LIKE '%".$search."%'
OR Mobile LIKE '%".$search."%'
OR Company LIKE '%".$search."%'
OR Description LIKE '%".$search."%'
";
}
else
{
$query = "SELECT * FROM clients ORDER BY Name";
}
$result = mysqli_query($connect, $query);
if(mysqli_num_rows($result) > 0)
{
$output .= '
<div class="table-responsive">
<table class="table table bordered">
<tr>
<th>Name</th>
<th>Aadhar</th>
<th>Mobile</th>
<th>Company</th>
<th>Description</th>
</tr>
';
while($row = mysqli_fetch_array($result)
{
$output .= '
<tr>
<td>'.$row["Name"].'</td>
<td>'.$row["Aadhar"].'</td>
<td>'.$row["Mobile"].'</td>
<td>'.$row["Company"].'</td>
<td>'.$row["Description"].'</td>
</tr>
';
}
echo $output;
}
else
{
echo 'Data Not Found';
}
I am successfully able to access all the data using this code.
First of all the function get_search_form(); will create a Search Box and a Submit button with a wrapper form. Form method is GET so $_POST in your code is completely wrong. Next is the search box created using this function have the name "s". The below code will be generated through the function :
<form role="search" method="get" class="search-form" action="">
<label>
<span class="screen-reader-text">Search for:</span>
<input type="search" class="search-field" placeholder="Search …" value="" name="s">
</label>
<input type="submit" class="search-submit" value="Search">
</form>
So change your code $_POST['query'] with $_GET['s']. Hope it will work for you.
I have query that gets data from a form, when the submit button is pressed the data should be stored in a database. When the form's action is action="#" the data is inputted into the database. But when the action is action="otherPage.php" the data is not inserted into the database. Any help ?
Side Note: I know the queries need to be changed to counter SQL injection this is just for testing
Code:
if(isset($_POST['submit']))
{
$name = $_POST['fullName'];
$idNumber = $_POST['idNo'];
$cardNo = $_POST['cardNo'];
$_SESSION['fullName'] = $name;
$_SESSION['id'] = $idNumber;
$checkExists = "SELECT * FROM system.table WHERE idNumber = '$idNumber' ";
$resExists = mysqli_query($connection,$checkExists)
or die("Error in query: ". mysqli_error($connection));
if(mysqli_fetch_assoc($resExists) > 0)
{
$updateCard = "UPDATE system.table SET cardNo = '$cardNo' WHERE idNumber=$idNumber";
$resUpdate= mysqli_query($connection,$updateCard)
or die("Error in query: ". mysqli_error($connection));
}
if(mysqli_fetch_assoc($resExists) < 1)
{
$company = $_POST['company'];
$name = trim($name);
$last_name = (strpos($name, ' ') === false) ? '' : preg_replace('#.*\s([\w-]*)$#', '$1', $name);
$first_name = trim(preg_replace('#'.$last_name.'#', '', $name));
$insert = "INSERT INTO system.table (idNumber,name,surname,company,cardNo) VALUES
('$idNumber','$first_name','$last_name','$company','$cardNo')";
$resInsert = mysqli_query($connection,$insert)
or die("Error in query: ". mysqli_error($connection));
}
$connection->close();
}
I do not know if this is the corrext way to go around it, but it works. I included ob_start(); at the beginning of my code, left the action as
<form role="form" method="POST" action="#">
Then included
header('Location:otherPage.php');
so that the page automatically redirects to otherPage.php
If you have two files in the same folder, it should be working:
myFolder
- testForm.php
- testUpload.php
testForm.php:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form method="post" action="testUpload.php">
<fieldset>
<legend>Form</legend>
<label>Name: </label>
<input type="text" name="name">
<input type="submit">
</fieldset>
</form>
</body>
</html>
testUpload.php:
<?php
print($_POST['name']);
exit;
Do you have any Redirection Statements in the config of your Web Server (e.g. Apache httpd.conf)?
So, from what I have been learning for these past few weeks I believe I have sufficient knowledge on how to perform PHP, and SQL related queries to create a good and dynamic website that could support something like a forum. I've not been able to do that yet, and am having quite a bit of trouble with it as well. So far, I've made a PHP file, that was simply to see if I could use PHP well. It did not work out, and I've been getting plenty of errors, and I've been unable to fix them, whatsoever. And so, I'd like to come here to ask, if anyone out there could possibly analyze my code that I've written, and see what is wrong with it, if possible. Along with that, I'd like to know what would be the "Proper" way of
A. Connecting to SQL
B. Selecting Data
C. Displaying/Utilizing Data
And thank you, for reading and/or possibly replying to this.
Here, is the code I've written but have been unable to work.
<?php
include 'header.php';
include 'connect.php';
?>
<body>
<form>
Input First name:<br>
<input type="text" name="FN">
<br>
Input Last name:<br>
<input type="text" name="LN">
<br>
Input Email:<br>
<input type="text" name="Email">
<br>
<input type="submit" method="post">
<?php
if (isset($_POST['FN'], $_POST['LN'], $_POST['Email']))
$sql = 'INSERT INTO `info` ("USERID", "FN", "LN", "Email") VALUES (\'$_POST[FN]\', '$_POST["LN"]', '$_POST["Email"]')';
?>
</form>
<?php
$sql = "SELECT FN, LN, Email
FROM
info"
$result = "mysql_query($sql)"
while($row_list = mysql_fetch_assoc( $result )) {
ECHO <div>The Names are:</div><br>
ECHO $FN . "," . $LN . "," . $Email;
}
?>
</body>
</html>
Your PHP code is wrong in so many ways even in your query. What I did is clean your codes.
<?php
include 'header.php';
include 'connect.php';
?>
<body>
<form action="" method="POST">
Input First name:<br>
<input type="text" name="FN">
<br>
Input Last name:<br>
<input type="text" name="LN">
<br>
Input Email:<br>
<input type="text" name="Email">
<br>
<input type="submit" name="submit-btn" value="submit">
</form>
<?php
if (isset($_POST['submit-btn'])){
$sql = 'INSERT INTO info ( "FN", "LN", "Email") VALUES ('$_POST[FN]', '$_POST["LN"]', '$_POST["Email"]')';
if (mysql_query($sql)) {
echo "New record created successfully";
}
}
$sql = "SELECT FN, LN, Email FROM info";
$result = mysql_query($sql)
while($row_list = mysql_fetch_assoc( $result )) {
ECHO '<div>The Names are:</div><br>';
ECHO $FN . "," . $LN . "," . $Email;
}
?>
</body>
</html>
try to indent your code to make it more readable for yourself.
as already answered by user3814670, your insert query was wrong, with 4 elements (id,fn,ln,email) and only 3 data (fn,ln,email)
your query was't being executed also cleaned by user3814670 by adding the lines
if (mysql_query($sql)) {
echo "New record created successfully";
}
try to print your query to the screen and executing it in you database to see if your query fails or print the error to screen
mysql_error()
add this on top of your file after
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
Here's how you display data from the database using while loop
while($row=mysql_fetch_array($result)) {
echo $row['FN'] . " " . $row['LN'] . " " . $row['Email'];
}
I hate to submit this question but I have been unable to find a solution for almost a week now.
<div class="scanform">
<form action="scanform.php" method="post" id="scanform">
<p> <label for="Order Number">Order Number:</label>
<input name="OrderNumber" id="OrderNumber" autofocus="" type="text"><span class="error">*<?php echo $ONErr;?>
</span></p>
<input name="submit" value="Submit" type="submit"></form>
</div>
The form works well when I click on the submit button but if I type in the text field and hit enter, the form just reloads.
I cannot figure out what I am doing wrong.
The PHP code:
<?php date_default_timezone_set('America/Toronto');
$ONErr = "";
if (isset($_POST['submit']))
{
$link = mysqli_connect("localhost", "username", "password", "ordertracking");
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Escape user inputs for security
if (empty($_POST['OrderNumber'])) {
$ONErr = "OrderNumber is required";
} else {
$OrderNumber = mysqli_real_escape_string($link, $_POST['OrderNumber']);
// Attempt insert query execution
$query = "SELECT * FROM Orders WHERE OrderNumber LIKE '%$OrderNumber' ORDER BY TimeStamp DESC LIMIT 1";
$result = mysqli_query($link, $query) or trigger_error("Query Failed! SQL: $query - Error: ". mysqli_error($mysqli), E_USER_ERROR);
}
// Close connection
mysqli_close($link);
}
?>
My homepage pulls in content from my MySQL database to create a blog. I've got it so that it only displays an extract from the posts. For some reason it displays HTML tags as well rather than formatting it using the tags (See picture below).
Any help is appreciated.
Homepage:
<html>
<head>
<title>Ultan Casey | Homepage</title>
<link rel="stylesheet" href="css/style.css" type="text/css" />
</head>
<body>
<div class="wrapper">
<div id="upperbar">
Home
About Me
Contact Me
Twitter
<form id="search-form" action="/search" method="get">
<input type="text" id="textarea" size="33" name="q" value=""/>
<input type="submit" id="submit" value="Search"/>
</form>
</div>
<div id="banner">
<img src="images/banner.jpg">
</div>
<div class="sidebar"></div>
<div class="posts">
<?php
mysql_connect ('localhost', 'root', 'root') ;
mysql_select_db ('tmlblog');
$sql = "SELECT * FROM php_blog ORDER BY timestamp DESC LIMIT 5";
$result = mysql_query($sql) or print ("Can't select entries from table php_blog.<br />" . $sql . "<br />" . mysql_error());
while($row = mysql_fetch_array($result)) {
$date = date("l F d Y", $row['timestamp']);
$title = stripslashes($row['title']);
$entry = stripslashes($row['entry']);
$id = $row['id'];
?>
<?php echo "<p id='title'><strong>" . $title . "</strong></p>"; ?><br />
<div class="post-thumb"><img src="thumbs/<?php echo $id ?>.png"></div>
<?php echo htmlspecialchars(substr($entry, 0, 1050)) ?>...
<br>
<hr><br />
Posted on <?php echo $date; ?>
</p>
</div>
</div>
</p
<?php
}
?>
</div>
</div>
</div>
</body>
</html>
Image:
You're passing your post through htmlspecialchars, which encodes < as < and > as >, among other things. This means they display as < and > instead of being parsed as html tags.
The whole point of htmlspecialchars is to produce text that's inert in HTML... to make it display as-is.
A better way to do this is to NOT store <br /> (or any other html) in your post. Instead, use regular line breaks, and echo nl2br(htmlspecialchars($text)) into your page.
If you absolutely need to allow html, you might consider something like HTML Purifier to handle escaping nasty stuff, in which case you'd skip the htmlspecialchars call. Just beware: It's not a good idea to write your own filter to stop malicious code when displaying user-supplied HTML.
echo substr($entry, 0, 1050)