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 } ?>
Related
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.
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 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"
}
}
`
I wrote this code and I want to style it with css. I added style to it but same result appears can any body help please .
<p>
<phpcode>
<?php
$term = mysql_real_escape_string($_REQUEST['term']);
$servername = "localhost";
$username = "***********";
$password = "***********";
$dbname = "*************";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT Install , power , RPM FROM SN WHERE serial = '$term'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "serial number: " . $term.'<br>';
echo "installation: " . $row["Install"].'<br>';
echo "power: " . $row["power"].'<br>';
echo "RPM: " . $row["RPM"].'<br>';
}
} else {
echo "no result";
}
$conn->close();
?>
</phpcode>
</p>
<style>
.results div:nth-of-type(1){
color:red;
background:blue;
font-size:3rem;
}
.results div:nth-of-type(2){
color:blue;
background:yellow;
font-size:2rem;
}
.results div:nth-of-type(3){
color:green;
background:orange;
font-size:1rem;
}
.results div:nth-of-type(4){
color:orange;
background:black;
font-size:0.5rem;
}
</style>
while( $row = $result->fetch_assoc() ) {
echo "
<div class='results'>
<div>serial number:{$term}</div>
<div>installation:{$row['install']}</div>
<div>power:{$row['power']}</div>
<div>rpm:{$row['rpm']}</div>
</div>";
}
I have MySQL server installed and I have created a test database named "test" and done a simple login example, with the ID, username, password and email. According to W3Schools, I have modified the code they provide:
<!DOCTYPE html>
<html>
<head>
<style>
table, th, td {
border: 1px solid black;
}
</style>
</head>
<body>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, username, password, email FROM user";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<table><tr><th>ID</th><th>Username</th><th>Password</th><th>Email</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["id"]. "</td><td>" . $row["username"]. "</td><td>" . $row["password"]. "</td><td>" . $row["email"]. "</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
?>
</body>
</html>
I've searched the directory of the database and I see in C:\Program Files\MySQL\MySQL Server 5.6\data a folder named "test" that contains 3 files, a .opt file, a .frm and a .ibd.
My question is, where should I put the html file in order to load this database data? Or should I change something from my code? Thanks!