I have the recaptcha displaying in my form but when someone hits submit I just get a blank white screen. Right now I have the questionable php commented out and the site works you can see it at www.necowindtest.com under the comments tab. Here is the php routine that runs when the submit button is clicked: Everything after the commented section works.
<?php
// define variables and set to empty
$moniker = $commentdate = $comment = "";
//
//set timezone to mountian
date_default_timezone_set("America/Denver");
//
/*This starts the possibly problematic statements
//
// files placed in root of server
require_once "recapthchalib.php";
//
//exit for troubleshooting move this up if you didn't get a message or down if you did
exit("MADE IT THIS FAR");
//
//secret key
$secret = "6LfUTwoaAAAAAGIDFC8FqCoZX0TOTzSKFyOKT57h";
//
//empty response
$response = null;
//
//check secret key
$reCaptcha = new ReCaptcha($secret);
//
//if submitted check response
if ($_POST["g-recaptcha-response"]){
$response = $reCaptcha->verifyResponse(
$_SERVER["REMOTE_ADDR"],
$_POST["g-recaptcha-response"]
);
}
//
//display form or thank you for submission
if ($response != null && $response->success) {
echo "Hi " . $_POST["moniker"] . " thanks for the submission";
}
else {
echo "Sorry captcha verification was unsuccessful";
}
//
//This is the end of the problematic statements
//
*/
//load form fields into variables and check for extraneous characters
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$moniker = test_input($_POST["moniker"]);
$comment = test_input($_POST["comment"]);
}
//
function test_input($data) {
$data = trim($data); //trim out spaces
$data = stripslashes($data); //strip out slashes
$data = htmlspecialchars($data); //change special characters to entities
return $data;
}
//
//write comment to end of comment file (commenttest.txt)
$dateofcomm = date("m-d-Y");
$dateofcomm = $dateofcomm . " ";
$newline = "\n";
$comment = $comment . " ";
$moniker = str_replace(" ", "", $moniker);
$newrecord = $dateofcomm . $comment . $moniker;
//
$prevcomm = fopen("commenttest.txt", "r") or die ("Unable to open file");
$allfiledcomments = file_get_contents("commenttest.txt");
file_put_contents("commenttest.txt", $dateofcomm);
file_put_contents("commenttest.txt", $comment, FILE_APPEND);
file_put_contents("commenttest.txt", $moniker, FILE_APPEND);
file_put_contents("commenttest.txt", $newline, FILE_APPEND);
file_put_contents("commenttest.txt", $allfiledcomments, FILE_APPEND);
fclose($prevcomm);
//
//display return link
echo "<div class='container' style='text-align: center'><br>";
echo "<a href='comments.php'><h2>Return to site</h2><br>";
echo "</div>";
//
//read comments from file (commenttest.txt)
$prevcomm = fopen("commenttest.txt", "r") or die ("Unable to open file");
while (!feof($prevcomm)) {
$acomm = fgets($prevcomm);
$acomm = chop($acomm);
$commdate = substr($acomm, 0, 10);
$bypos = strrpos($acomm, " ",); //get position of last space before name
$commenter = substr($acomm, $bypos,); //name is from last space to end
$bypos = $bypos - 10;
$filedcomm = substr($acomm, 11, $bypos); //comment is from position 11, after the date, to last space left to right
//
//write formatted comment to screen
echo "<div container style='font-size: 25px; border: solid red; border-radius: 20px;'><br>";
echo "<div container style='padding-left: 25px;'>";
echo $commdate;
echo "</div>";
echo "<div container style='padding-left: 50px; width: 225px; display: inline-block;'>";
echo "<h2><strong>COMMENT: </strong></h2>";
echo "</div><br>";
echo "<div container style='padding-left: 75px; width: 600px; display: inline-block;'>";
echo $filedcomm;
echo "</div><br>";
echo "<div container style='padding-left: 50px; width: 100px; display: inline-block;'>";
echo "<h2><strong>BY: </strong></h2>";
echo "</div>";
echo "<div container style='padding-left: 1px; width: 500px; display: inline-block;'>";
echo $commenter;
echo "</div>";
echo "</div><br>";
}
fclose($prevcomm);
?>
Thanks Alvaro, It took a while but I figured out how to get bluehost to show the php errors. Now I am getting closer.
Related
I am editing my earlier post. Hope I can explain the requirement in a better way.
I use the following script (Courtesy Stack Overflow) to upload the data from an XML file to MySQL tabele
The XML file gets uploaded daily (sometimes a couple of times) in the uploads folder. Can the following script be modified so that a dropdown menu appears with lastest last 8 file names in the uploads folder alongwith with date and time stamp (uploads/data-20230214.xml was uploaded on: 15-02-2023 17:20:24). And a submit button. After selecting a file from the dropdown menu and on clicking the submit button, the following script should run.
<?php
// Connect to database
$servername = "localhost";
$username = "abc";
$password = "******";
$dbname = "dbnamexx";
$db="dbyy";
$tablename="testtable";
$conn = mysqli_connect($servername, $username, $password, $dbname);
$affectedRow = 0;
// Load xml file else check connection
$xml = simplexml_load_file("dgdata/feed-20230214.xml")
or die("Error: Cannot create object");
// Assign values
foreach ($xml->children() as $row) {
$id = mysqli_real_escape_string($conn, $row->id);
$Name = mysqli_real_escape_string($conn, $row->Name);
$City = mysqli_real_escape_string($conn, $row->City);
$Country = mysqli_real_escape_string($conn, $row->Country);
$Url = mysqli_real_escape_string($conn, $row->Url);
$documents = mysqli_real_escape_string($conn, $row->documents);
// SQL query to insert data into xml table
$sql = 'INSERT INTO testtable(id, Name, City, Country, Url, documents) VALUES ("' . $id . '","' .$Name . '","' .$City . '","' .$Country . '","' .$Url . '","' .$documents . '")';
$result = mysqli_query($conn, $sql);
if (! empty($result)) {
$affectedRow ++;
} else {
$error_message = mysqli_error($conn) . "\n";
}
}
?>
<center><h2>Upload Status</h2></center>
<center><h1>XML Data Uploaded in Mysql</h1></center>
<?php
if ($affectedRow > 0) {
$message = $affectedRow . " records inserted";
} else {
$message = "No records inserted";
}
?>
<style>
body {
max-width:550px;
font-family: Arial;
}
.affected-row {
background: #cae4ca;
padding: 10px;
margin-bottom: 20px;
border: #bdd6bd 1px solid;
border-radius: 2px;
color: #6e716e;
}
.error-message {
background: #eac0c0;
padding: 10px;
margin-bottom: 20px;
border: #dab2b2 1px solid;
border-radius: 2px;
color: #5d5b5b;
}
</style>
<div class="affected-row">
<?php echo $message; ?>
</div>
<?php if (! empty($error_message)) { ?>
<div class="error-message">
<?php echo nl2br($error_message); ?>
</div>
<?php } ?>
So far, I've gotten my PHP to output my form data to another page once it has been input. After it has been submitted, I need the data to be inserted into a mySQL database titled 'megatravel'. I am getting errors i.e "Table 'megatravel.reservations' doesn't exist" and another one "Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, bool given in C:\xampp1\htdocs\JordanMahsman-MegaTravel2\contactform.php on line 111"
I am using XAMPP and have been to localhost/phpmyadmin to create the database 'megatravel' and to create the table 'reservations' but I am getting errors, and I need help.
<?php
$required = array('name', 'email', 'phone', 'adultsNo', 'children', 'city', 'activity', 'date');
$error = false;
foreach($required as $field) {
if (!isset($_POST[$field])) {
$error = true;
}
}
if(!$error){
if(!(is_numeric($_POST['phone']) && is_numeric($_POST['adultsNo']) && is_numeric($_POST[
'children']))){
$error=true;
echo "Numeric entries are required for Phone Number, No.of Adults, and No.of Children<br>";
}
}
if(!$error){
if(!validateEmail($_POST['email']))
{
$error=true;
echo "Not a valid Email Address. Please try again.<br>";
}
}
if(!$error){
if(!validateDate($_POST['traveldate'])){
$error=true;
echo "Not a valid date. Please try again.<br>";
}
}
if (!$error) {
echo "All fields are required.</br>";
} else {
echo "Hello, a client has submitted their information for you to review! <br>";
echo "<br>Name: ".$_POST['name']."
<br></br>
Email: ".$_POST['email']."
<br></br>
Phone Number: ".$_POST['phone']."
<br></br>
No. of Adults: ".$_POST['adultsNo']."
<br></br>
No. of Children: ".$_POST['children']."
<br></br>
City: ".$_POST['city']."
<br></br>
Activity: ".$_POST['activity']."
<br></br>
Date: ".$_POST['traveldate'];
}
function validateEmail($email) {
// Validate email
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
return 1;
} else {
return 0;
}
}
function validateDate($traveldate, $format = 'Y-m-d')
{
$d = DateTime::createFromFormat($format, $traveldate);
return $d && $d->format($format) === $traveldate;
}
// DATABASE CREATION AND INSERTION
$servername = "localhost";
$username = 'root';
$password = '';
$dbname = 'megatravel';
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Failed to Connect: " . $conn->connect_error);
}
$sql = "CREATE DATABASE megatravel";
if ($conn->query($sql) === TRUE) {
echo "Database created!";
} else {
echo "A problem occurred creating your database. Try again!: " . $conn->error;
}
$sql = "INSERT INTO reservations (name, email, phone, adultsno, children, city, activity, date)
VALUES ('{$_POST['name']}', '{$_POST['email']}','{$_POST['phone']}','{$_POST['adultsNo']}', '{$_POST['children']}',
'{$_POST['city']}', '{$_POST['activity']}', '{$_POST['traveldate']}')";
if ($conn->query($sql) === TRUE) {
echo "<br><br>Success!<br>";
} else {
echo "<br>Error: " . $sql . "<br>" . $conn->error;
}
$sql = "SELECT * FROM reservations";
$result = mysqli_query($conn, $sql);
echo "<br>";
echo "<table border='1'>";
echo "<tr>";
echo "<td style='text-align: center; font-weight: bold'>Name</td>","<td style='text-align: center; font-weight: bold'>Email</td>","<td style='text-align: center; font-weight: bold'>Phone</td>","<td style='text-align: center; font-weight: bold'>Adults</td>","<td style='text-align: center; font-weight: bold'>Children</td>","<td style='text-align: center; font-weight: bold'>City</td>","<td style='text-align: center; font-weight: bold'>Activity</td>","<td style='text-align: center; font-weight: bold'>Date</td>";
echo "</tr>";
while ($row = mysqli_fetch_assoc($result)) {
echo "<tr>";
foreach ($row as $field => $value) {
echo "<td>" . $value . "</td>";
}
echo "</tr>";
}
echo "</table>";
$conn->close();
?>
You only need to create the database once.
The error message is telling you that the reservations table needs creating.
CREATE TABLE reservations (
name VARCHAR(250),
email varchar(100)
)
It helps to use a SQL utility to manage the DB. and to play attention to any error messages SQL throws.
I am using "while" to loop through my PDO database results, and I am using PHP to build HTML tables as long as results exist. When the query returns the data, the PHP code will only place one result in an HTML table and everything else outside of the table format. What am I missing in my code?
I have moved my table coding inside and out side of my while loop. I tried embedding a foreach loop inside the while loop, but it just returns 11 of each result and still only one in the HTML table format.
<?php
public static function find_members() {
/* -------------BEGIN PDO-----------*/
if (!extension_loaded ('PDO' )) {
echo 'PDO is NOT loaded!'."\n";
if (!extension_loaded('pdo_mysql')){
echo 'PDO mysql driver is NOT loaded.'."\n";
}
}
try {
// calling stored procedure command
$sql = 'CALL `Members`()';
//$sql = "SELECT * FROM members";
// prepare for execution of the stored procedure
$stmt = self::$database->prepare($sql);
// execute the stored procedure
$stmt->execute();
if ($stmt->rowCount() > 0) {
echo "<table class='membertable'>";
echo "<thead>" . "header for table" ."</thead>";
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$mejpeg = $row['photojpeg'];
$email = $row['me_email'];
$name = $row['me_name'];
echo "<tbody>";
echo "<tr>";
echo "<td>
{$name}<br />
{$email }<br />
</td>";
echo "<td>". '<img src="data:image/jpeg;base64, ' .base64_encode($mejpeg). ' " height="120" width="" />'."</td>";
echo "</tboby>";
echo "</tr>";
echo "<tfoot>";
echo "<tr>";
echo "<td>"."</td>";
echo "</tr>";
echo "</tfoot>";
echo "</table>";
}} else {
echo "0 results";
}
} catch (PDOException $e) {
die("Error occurred:" . $e->getMessage());
}
return null;
}
?>
called on result webpage:
<?php $mbs = array(memberPage::find_members()); foreach($mbs as $mb) { echo $mb;} ?>
I expect the php code to build tables for each of the results. However, the actual result is only the first record is formatted with the table tags while the other results have no table tags.
MY FINAL SOLUTION
The PHP code:
<?php
public static function find_members() {
/* -------------BEGIN PDO-----------*/
if (!extension_loaded ('PDO' )) {
echo 'PDO is NOT loaded!'."\n";
if (!extension_loaded('pdo_mysql')){
echo 'PDO mysql driver is NOT loaded.'."\n";
}
}
try {
// calling stored procedure command
$sql = 'CALL `Members`()';
//$sql = "SELECT * FROM members";
// prepare for execution of the stored procedure
$stmt = self::$database->prepare($sql);
// execute the stored procedure
$stmt->execute();
if ($stmt && $stmt->rowCount() > 0) {
/*INSTEAD OF ECHOING TABLES, I AM ECHOING <div> TAGS*/
echo '<div class="head"><h2>Title of query results will go here</h2></div><div class="content">';
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$mejpeg = $row['photojpeg'];
$email = $row['me_email'];
$name = $row['me_name'];
echo '<div id="info">' .
'<img src="data:image/jpeg;base64, ' . base64_encode($mejpeg) . ' " class="textwrap" />' .
$name<br /> .
$email<br /> .
'</div>';
}
echo '</div>';
}} else {
echo "0 results";
}
} catch (PDOException $e) {
die("Error occurred:" . $e->getMessage());
}
return null;
}
?>
THEN MY WEB PAGE HTML/PHP FOR THE MAIN DIV search.php
<div class="members">
<h2 class="hidden">members</h2>
<?php $mbs = array(memberPage::find_members()); foreach($mbs as $mb) { echo $mb;} ?>
</div>
Then I managed the output to the webpage via CSS
#charset "utf-8";
/* CSS Document */
* {
margin: 0;
padding: 0;
}
/*This <div class="members"></div> is already on the webpage and not being echoed from php everything below is called between the open and closing tag*/
.members {
display: grid;
grid-template-columns: auto;
grid-gap: 20px 50px;
grid-template-areas:
"head"
"content";
}
.head {
grid-area: head;
display: grid;
margin-top: 20px;
text-align: center;
}
.content {
grid-area: content;
display: grid;
grid-template-columns: auto auto auto;
margin-left: 10px;
margin-right: 10px;
grid-column-start: 1;
grid-column-end: 2;
grid-row-gap: 10px;
grid-column-gap: 10px;
}
#info {
outline: solid;
}
.textwrap {
float: left;
margin: 1px;
position: relative;
width: auto;
height: 160px;
background-position: 50% 50%;
background-repeat: no-repeat;
background-size: cover;
}
.info{
grid-area: info;
}
.photo {
grid-area: photo;
}
.hidden {
display: none;
}
The final output loops through the results and displays the results on the webpage with styling. It was far easier and more flexible than using tables.
Untested, but here's how I've done things in the past.
<?php
public static function find_members() {
/* -------------BEGIN PDO-----------*/
if (!extension_loaded ('PDO' )) {
echo 'PDO is NOT loaded!'."\n";
if (!extension_loaded('pdo_mysql')){
echo 'PDO mysql driver is NOT loaded.'."\n";
}
}
try {
// calling stored procedure command
$sql = 'CALL `Members`()';
// prepare for execution of the stored procedure
$stmt = self::$database->prepare($sql);
// execute the stored procedure
$stmt->execute();
if ($stmt && $stmt->rowCount() > 0) {
echo '<table class="membertable">';
echo '<thead><tr><th>Name/Email</th><th>Photo</th></tr></thead>';
echo '<tbody>';
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$mejpeg = '<img src=data:image/jpeg;base64, ' . base64_encode($row['photojpeg']) . ' height="120" width="80" />';
$email = $row['me_email'];
$name = $row['me_name'];
echo '<tr>';
echo '<td>'.$name.'<br />'.$email.'<br /></td>';
echo '<td>'.$mejpeg.'</td>';
echo '</tr>';
}
echo '</tbody>';
echo '<tfoot>';
echo '<tr>';
echo '<td>something 1</td>';
echo '<td>something 2</td>';
echo '</tr>';
echo '</tfoot>';
echo '</table>';
} else {
echo '<div>0 results</div>';
}
} catch (PDOException $e) {
die('Error occurred: ' . $e->getMessage());
}
}
Try this, the proper way to return data from a function.
<?php
public static function find_members()
{
/* -------------BEGIN PDO-----------*/
if (!extension_loaded('PDO')) {
echo 'PDO is NOT loaded!' . "\n";
if (!extension_loaded('pdo_mysql')) {
echo 'PDO mysql driver is NOT loaded.' . "\n";
}
}
try {
// calling stored procedure command
$sql = 'CALL `Members`()';
// $sql = "SELECT * FROM members";
// prepare for execution of the stored procedure
$stmt = self::$database->prepare($sql);
// execute the stored procedure
$stmt->execute();
if ($stmt->rowCount() > 0) {
$returnDataOutter[] = "<table class='membertable'>";
$returnDataOutter[] = "<thead>" . "header for table" . "</thead>";
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$mejpeg = $row['photojpeg'];
$email = $row['me_email'];
$name = $row['me_name'];
$returnData = "<tbody>";
$returnData.= "<tr>";
$returnData.= "<td>
{$name}<br />
{$email}<br />
</td>";
$returnData .= "<td>" . '<img src="data:image/jpeg;base64, ' . base64_encode($mejpeg) . ' " height="120" width="" />' . "</td>";
$returnData .= "</tr>";
$returnData .= "</tboby>";
$returnData .= "<tfoot>";
$returnData .= "<tr>";
$returnData .= "<td>" . "</td>";
$returnData .= "</tr>";
$returnData .= "</tfoot>";
$returnData .= "</table>";
$returnDataOutter[] = returnData;
}
} else {
$returnDataOutter[] = "0 results";
}
return $returnDataOutter;
}
catch(PDOException $e) {
die("Error occurred:" . $e->getMessage());
}
return [];
}
?>
called on result webpage:
<?php $mbs = array(memberPage::find_members()); foreach($mbs as $mb) { echo $mb;} ?>
I have MySQL database and web page which are linked. When I updated data on database, my web page is showing date and time wrong what should I do , also how to display data in rows and columns(Table format)
Post / Display data
<?php
include("dbconnection.php");
$DTN = $CNT->query("select * from smsinbox ORDER BY id DESC");
$msg = $DTN->rowCount();
echo "<div width=\"auto\" align=\"center\">";
echo "Inbox: <b>$msg</b> text messages <a style=\"background-color: #4CAF50;border:none;color: white;padding: 5px 11px;text-align: center;text-decoration: none;display: inline-block;font-size: 16px;\" href=\"$PHP_SELF\">Refresh</a> <br>";
if($msg > 0){
echo "<table cellpadding=\"10\" cellspacing=\"0\" style=\"border-color: #666666;border-width: 1px;padding:5px;border: 0px solid #666666;\">"
."<tr style=\"text-align:center;font-weight: bold; background-color: #ebf4fb;\"><td>Id</td><td>Phone</td><td>Text</td><td>Time</td></tr>";
while($row = $DTN->fetch()) {
echo "<tr>"
."<td style=\"background-color:#efefef;\">$row[id]</td>"
."<td style=\"background-color:#efefef;\">$row[phone]</td>"
."<td style=\"background-color:#efefef;\">$row[text]</td>"
."<td style=\"background-color:#efefef;\">$row[date]</td>"
."</tr>";
}
echo "</form>"
."</table>"
."</div><br>"
."</td>"
."</table>";
} else {
echo "<br><br><div style=\"width:20%;background-color: #efefef;padding: 8px 36px;\">inbox is empty<div>";
}
echo "</div>";
?>
Retrieving data
<?php
include("dbconnection.php");
$token = $_REQUEST['token'];
$phone = $_REQUEST['from'];
$text = $_REQUEST['text'];
if (($phone == "") AND ($text == "")) {
echo "";
} else {
$date = date('Y-m-d H:i:s');
$sql = "INSERT INTO smsinbox (phone,text,date) VALUES (:phone,:text,:date)";
$q = $CNT->prepare($sql);
$q->execute(
array(
':phone'=>"$phone",
':text'=>"$text",
':date'=>"$date"
)
);
}
?>
The above are php code files, one is for retrieving data and another is posting or displaying data on webpage
I have made an english to persian dictionary using php and a database,I get the english word from the user and post it to process.php and then in that file I search for the entered word in my database and I return the persian meaning.This works fine but my problem is when the entered word is not in my database the code does not enter the else condition and it does not print the "0 result" statement.I'll be really thankfull if someone could help .
so this is my first file :
<html>
<head>
<style>
body {
background-image: url("final.jpg");
}
#par {
width: 320px;
padding: 10px;
border: 5px solid gray;
margin-left:auto;
margin-Right:auto;
position: absolute;
top: 20%;
left:35%;
text-align: center;
background-color:Powderblue;
}
#footer{
margin-top:45%;
background-color:#C7BDBB;
text-align:right;
}
</style>
<title>niloofar-dictionary</title>
</head>
<body>
<div id=par>
<?php
$username="raanaste_niloo1";
$password="Nt13541372";
$dbname="raanaste_niloofar-dictionary";
$usertable="dictionary";
$yourfield = "english";
$yourfield1 = "persian";
//Connect to the database
$connection = mysql_connect($hostname, $username, $password);
mysql_select_db($dbname, $connection);
$name = $_POST["word"];
//Setup our query
$query = "SELECT persian FROM $usertable WHERE english='{$_POST["word"]}'";
//Run the Query
$result = mysql_query($query);
//If the query returned results, loop through
// each result
if($name)
{
if($result!=NULL)
{
while($row = mysql_fetch_array($result))
{
$na = $row["$yourfield1"];
echo "word in persian: " . $na;
}}
else {
echo "0 results"
}
}
?>
</div>
<div id="footer">
<h4> COPYRIGHT: © 2017 niloofartarighat. </h4></div>
</body>
</html>
and this is the process.php
You can use a function :
function getDataForAdmin($select, $from, $where, $orderBy, $multi = false){
global $con;
$q = "select ".$select." from ". $from;
if(strlen($where)>0 && $where != " " || $where != null){
$q .= " where ".$where;
}
if(strlen($orderBy)>0 && $orderBy != " " || $orderBy != null){
$q .= " order by ".$orderBy;
}
$r = mysqli_query($con, $q);
if($r){
if(mysqli_num_rows($r)>0){
$data['result'] = true;
if($multi){
$data['data'] = getMultilineData($r);
}else{
$data['data'] = mysqli_fetch_assoc($r);
}
}else{
$data['result'] = false;
$data['data'] = "No Record Found!";
}
}else{
$data['result'] = false;
$data['data'] = "Error: 0xDS31ADMN". mysqli_errno($con);
}
return $data;
}
function getMultilineData($sql){
$c = 0;
while ($r = mysqli_fetch_assoc($sql)){
$data[$c] = $r;
$c++;
}
return $data;
}
function escapeString($val) {
global $con;
return mysqli_real_escape_string($con, $val);
}
if(isset($_POST)){
$name = escapeString($_POST['name']);
$data = getDataForAdmin("*", "table", "name = '$name'", null);
}
and make your own code as well as you want :)
I changed the while to else and the problem was fixed!!`
if($name)
{
if($result!=NULL)
{
if($row = mysql_fetch_array($result))\\this is the change
{
$na = $row["$yourfield1"];
echo "word in persian: " . $na;
}}
else {
echo "0 results"
}
}
`