Getting PHP and SQL scripting to work properly - html

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'];
}

Related

How to write the query to accept the input from the search box and search from MySql db (Wordpress)

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.

Pull Random Data from mySQL

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/

Why won't my comment system work? [HTML]

I am a beginner in html, and I am beginning to develop my first website. I watched a video to learn to code a commentary system, here is the link:
https://www.youtube.com/watch?v=O4BkHj7Ws9U
My page does resemble what is shown in the video, but there is some errors, take a look at my webpage after watching the video, as you can see, there are errors:
Here is my code:
<HTML>
<form action="" method="post">
<label> Name: <br><input type="text" name="name"><br></label>
<label> Message: <br><textarea cols="35" rows="5" name="mes"></textarea></label><br>
<input type="submit" name="post" value="Post">
</form>
</HTML>
<?php
$name = $_POST["name"];
$text = $_POST["mes"];
$post = $_POST["post"];
if ($post){
#WRITE DOWN COMMENTS#
$write = fopen("com.txt", "a+");
fwrite($write, "<u><b> $name</b></u><br>$text<br></br>");
fclose($write);
#DISPLAY COMMENTS#
$read = fopen("com.txt", "r+t");
echo "All comments:";
while(!feof($read)){
echo fread($read, 1024);
}
fclose($read);
}
else{
#DISPLAY COMMENTS#
$read = fopen("com.txt", "r+t");
echo "All comments:<br>";
while(!feof($read)){
echo fread($read, 1024);
}
fclose($read);
}
?>
Thank you for your help, sorry, I'm sort of a newbie at this.
You should use something like MAMP to run php code.
Or upload everything to a webserver.
You have to save your file as a PHP file.

PHP getting data from HTML fields

I'm having some problems with getting data from HTML fields. This is how it looks in HTML
<form action="getInfo.php">
<span>Series</span>
<input class="searchFieldAlign" type="text" name="seriesName" /><Br>
<span>Volume</span>
<input class="searchFieldAlign" type="text" name="volumeName" /><Br>
<span>Nr</span>
<input class="searchFieldALign" type="text" name="issueNR" /><Br>
<p input class="searchFieldALign" type=submit></p>
</form>
This is my php script:
<?php
$seriesName = mysqli_real_escape_string($conn, $_POST['seriesName']);
$volumeName = mysqli_real_escape_string($conn, $_POST['volumeName']);
$issueNR = mysqli_real_escape_string($conn, $_POST['issueNR']);
$con=mysqli_connect("localhost","user","psswd","db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$qryIssueInfo = mysqli_query($con,"select issueNR, issueVolume, issueName, issueImageURL from issue, series where (seriesName='$seriesName') and (issueVolume='$volumeName') and (issueNR=$issueNR)");
$rowIssueInfo = mysqli_fetch_array($qryIssueInfo);
The problem is I don't get output from my query. There are no problems if i change it to this:
$qryIssueInfo = mysqli_query($con,"select issueNR, issueVolume, issueName, issueImageURL from issue, series where seriesName='Buffy, the Vampire Slayer' and issueVolume= 'Season 8' and issueNR=1");
If you not set form method = "post" it will be "get" and you should $_GET.
To correct:
<form method="post" action"getInfo.php">
Take it easy
The first version does not contain the apostrophes around the variables.
You should also consider security issues, like SQL injection.

PHP Mail() Function Issue - Message field not getting sent (WordPress)

I know there are thousands and thousands of ways to utilize the PHP mail() function, but I am fairly new to PHP and could use some pointers to get me set in the right direction. I have a PHP mail function written into my WordPress driven site and it emails all the information (name, email, & phone) except for the message field. I've done my research on here as well as every PHP related site, but I would prefer to understand my specific issue so I can better understand what I'm writing. So with that said...here's the code:
<?php
function spamcheck($field)
{
$field=filter_var($field, FILTER_SANITIZE_EMAIL);
if(filter_var($field, FILTER_VALIDATE_EMAIL))
{
return TRUE;
}
else
{
return FALSE;
}
}
if (isset($_POST['email']))
{
$mailcheck = spamcheck($_POST['email']);
if ($mailcheck==FALSE)
{
$submit_message = "Please input your information again.";
}
else
{
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];
mail("emailaddress#gmail.com", "From: $name", "Email: $email", "Phone Number: $phone", "Message: $message");
$submit_message = "Thank you for your message";
}
}
?>
And the HTML...
<form name="message-me" id="contact-form" action="<?php echo $_SERVER['REQUEST_URI']; ?>" method="POST" enctype="multipart/form-data">
<div class="field-group">
<label>Name:</label><input type="text" name="name" id="form_name" />
</div>
<div class="field-group">
<label>Email:</label><input type="text" name="email" id="form_email" />
</div>
<div class="field-group">
<label>Phone:</label><input type="text" name="phone" id="form_phone" />
</div>
<div class="field-group">
<label>Message:</label><textarea rows="4" cols="31" name="message" id="form_message"></textarea>
</div>
<div class="field-group">
<input type="image" src="<?php bloginfo('template_directory'); ?>/images/Send-Message-Arrow.png" width="90" height="72" class="form-button" />
</div>
</form>
Any information would be greatly appreciated. As I mentioned, I'm still learning PHP and I really want to understand what I'm writing - not just blindly copying & pasting code all the time. Thanks!
Your SMTP want to be configured, first check up that
and
//Header Information for mail
$headers = "YOUR HEADERS INFORMATION HERE";
$msg="Email: $email<br/>Phone Number: $phone<br/>Message: $message";
mail("emailaddress#example.com", $subject, $msg, $headers);
Please have look at Documentation.
You need to provide parameters as
mail($to, $subject, $message, $headers);
Here you have provided "to" email address right.
So this might help you:
$message = $_POST['message'];
//Give mail a subject
$subject = "YOUR SUBJECT HERE";
//Header Information for mail
$headers = "YOUR HEADERS INFORMATION HERE";
mail("emailaddress#gmail.com", $subject, $message, $headers);
$submit_message = "Thank you for your message";
Enjoy!
Kindly read this manual with the directives and examples on it and you'll understand well what you are doing. Just take your time to read and understand well then start asking your questions from that point. Right now, you don't seem to understand even how the PHP mail() works. Read then get back so together you'll understand any solutions pointed out to you and you won't just copy and paste the solution without being able to solve it tomorrow.
http://php.net/manual/en/function.mail.php