I need to create a form that will check it fills; if true, refresh itself after submit button is clicked.
viewing.php post to be display in earliest submission first with timestamp in descending order.
I have this connected to my local database to store and display data entered.
I have tried every code from forums and youtube but nothing works.
Below is the code:
index.php:
<style rel="stylesheet" type="text/css">
body {
left:20px;
font-size:15pt;
}
label, input, textarea{
left:20px;
margin:5px 5px 5px 5px;
font-size:15pt;
}
div {
width:50%;
background-color:lightgrey;
}
</style>
</head>
<body>
<div> <!--id="auto"-->
<form name="ajax" action="insert.php" method="post" id="contact">
<br>
<label>Please Enter Your Comments :</label>
<br><br>
<label>Name :<span>*</span>
<input type="text" name="Name" id="Name" value="" placeholder="Name" autocomplete="off"/>
</label>
<br>
<label>Enter Your Wishes : <span>*</span>
<br>
<textarea name="Comment" rows="10" cols="30" id="Comment" placeholder="Message" autocomplete="off"></textarea>
</label>
<br>
<input type="submit" value="Submit" onclick="aa();"/>
<input type="reset" value="Clear"/>
</form>
</div>
<script type="text/javascript">
location.refresh(true);
$('#contact').submit(function () {
sendContactForm();
return false;
});
</script>
</body>
</html>
insert.php:
<?php
session_start();
require 'config.php';
if(isset($_POST['Name'], $_POST['Comment'])){
$fields = [
'Name' => $_POST['Name'],
'Comment' => $_POST['Comment']
];
foreach ($fields as $field => $data) {
if (empty($data)){
$errors[] = 'The '.$field . ' field is required.';
}
}
}
else {
$errors[] = 'Error.';
}
// This function will run within each post array including multi-dimensional arrays
function ExtendedAddslash(&$params)
{
foreach ($params as &$var) {
// check if $var is an array. If yes, it will start another ExtendedAddslash() function to loop to each key inside.
is_array($var) ? ExtendedAddslash($var) : $var=addslashes($var);
unset($var);
}
}
// Initialize ExtendedAddslash() function for every $_POST variable
ExtendedAddslash($_POST);
$ID = $_POST['ID'];
$Name = $_POST['Name'];
$Comment = $_POST['Comment'];
/*$db_host = 'localhost:8889';
$db_username = 'root';
$db_password = 'root';
$db_name = 'Event';*/
mysql_connect( $db_host, $db_username, $db_password) or die(mysql_error());
mysql_select_db($db_name);
// search submission ID
$query = "SELECT * FROM 'demo' WHERE 'Name' = '$ID'";
$sqlsearch = mysql_query($query);
$resultcount = mysql_numrows($sqlsearch);
if ($resultcount > 0) {
mysql_query("UPDATE `demo` SET
`Name` = '$Name',
`Comment` = '$Comment',
WHERE `ID` = '$ID'")
or die(mysql_error());
} else {
mysql_query("INSERT INTO `demo` (ID, Name, Comment) VALUES ('$ID','$Name', '$Comment') ")
or die(mysql_error());
}
header('Location: index.php');
?>'
viewing.php:
<style rel="stylesheet" type="text/css">
body {
font-size:20pt;
}
</style>
<body>
<?php
require 'config.php';
$conn = mysqli_connect( $db_host, $db_username, $db_password, $db_name);
// Create connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT Name, Comment FROM demo";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
//echo "<table><tr><th>Name</th><th>Comment</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
//echo "<tr><td>".$row["Name"]." ".$row["Comment"]."</td></tr>";
echo "<fieldset>From : ".$row["Name"]."<br>".$row["Comment"]."<br></fieldset><br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
</body>
config.php:
<?php
/*Configuration Settings*/
$db_username = 'root';
$db_password = 'root';
$db_name = 'Event';
$db_host = 'localhost';
$port = 8889;
$socket = 'localhost:/Applications/MAMP/tmp/mysql/mysql.sock';
?>
Related
I am unable to send the information from a from into mysql. I get the following error:
Fatal error: call to undefined function mysqli_connect()
I know the db connection is working because I am able to send other data into the database. I have added the connection information on the signupcontact.php but that did nothing.
I am not sure what the issue is since the database is connected.
Thanks for your help in advance.
form:
<?php
echo "<div class='wrapper'>";
require ('header.php');
include ('signupcontact.php');
include ('db_connect2.php');
?>
<head>
<title>Contac Information</title>
<meta charset="utf-8"/>
<link rel="stylesheet" href="style.css"/>
</style>
<script>
function validateForm() {
if (document.forms[0].userName.value == "") {
alert("Name field cannot be empty.");
return false;
} //end if
if (document.forms[0].userLastName.value == "") {
alert("Last Name field cannot be empty.");
return false;
} // end if
if (document.forms[0].userEmail.value == "") {
alert("Email field cannot be empty.");
return false;
} // end if
alert ("Successful!");
return true;
} //end function validateForm
</script>
</head>
<body>
<?php
echo '<form method="POST"
action="db_connect2.php"
onsubmit="return validateForm();">
<fieldset style="width:900px; margin:auto;">
<legend class="pcenter">Subscribe for updates</legend>
<label for="userName">Name: </label><br />
<input type="text" name="userName" id="userName"/><br /><br />
<label for="Last_Name">Last Name: </label><br />
<input type="text" name="userLastName" id="userLastName"/><br /><br />
<label for="userEmail">Email: </label><br />
<input type="text" name="userEmail" id="userEmail"/>
<br /><br />
<input type="submit" value="submit" id="submit"/><br />
</fieldset>
</form>
dbconnect:
<?php
$conn = mysqli_connect('localhost', 'root', '', 'happy_blog');
if(!$conn) {
die("connection failed: ".mysqli_connect_error());
}
signupcontact (I added the connection here again to see if it helps, nothing)
<?php
$dBServername = "localhost";
$dBUsername = "root";
$dBPassword = "";
$dBName = "happy_blog";
// Create connection
$conn = mysqli_connect($dBServername, $dBUsername, $dBPassword, $dBName);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
if (isset($_POST['submit'])){
$Name = $_POST['userName'];
$LName = $_POST['userLastName'];
$Email = $_POST['userEmail'];
$Name = mysqli_real_escape_string($conn,$_POST['userName']);
$LName = mysqli_real_escape_string($conn,$_POST['userLastName']);
$Email = mysqli_real_escape_string($conn,$_POST['userEmail']);
//$sql = "INSERT INTO contact (userName, userLastName, userEmail) VALUES ('".$_POST["userName"]."', '".$_POST["userLastName"]."', '".$_POST["userEmail"]."')";
$sql = "INSERT INTO contact (userName, userLastName, userEmail) VALUES ($Name, $LName, $Email)";
$result = mysqli_query($conn, $sql);
if ($conn->query($sql) === TRUE) {
echo "Form submitted successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
I created an account on 000webhost to create html page that has a login form. But I am facing errors when i try to connect the form to the database.
Here is the html code:
<html>
<head>
<title>Login Page</title>
<style type = "text/css">
body {
font-family:Arial, Helvetica, sans-serif;
font-size:14px;
}
label {
font-weight:bold;
width:100px;
font-size:14px;
}
.box {
border:#666666 solid 1px;
}
</style>
</head>
<body bgcolor = "#FFFFFF">
<div align = "center">
<div style = "width:300px; border: solid 1px #333333; " align = "left">
<div style = "background-color:#333333; color:#FFFFFF; padding:3px;"><b>Login</b></div>
<div style = "margin:30px">
<form method="POST" action="C1.php">
<label>UserName :</label><input type = "text" name = "username" required = "box"/><br /><br />
<label>Password :</label><input type = "password" name = "password" required = "box" /><br/><br />
<input type = "submit" name="submit" value = " Login "/><br />
</form>
<div style = "font-size:11px; color:#cc0000; margin-top:10px"><?php echo $error; ?></div>
</div>
</div>
</div>
</body>
</html>
here is my php page
<?php
session_start();
$servername = "localhost";
$username = "******";
$password = "******";
// Create connection
$database_name = "id2425621_login";
$conn = mysqli_connect($servername, $username, $password, $database_name);
if (isset($_POST['submit']))
{
$username='king';
$password='king123';
$query = mysqli_query($conn, "SELECT * FROM mylogin WHERE username='$username' and password='$password'");
if (mysqli_num_rows($query) != 0)
{
echo "sucess";
}
else
{
echo "fail";
}
}
?>
mysql has a table named mylogin and has the values:
INSERT INTO `mylogin`(`username`, `password`) VALUES ('king','king123')
I couldn't connect to the database, appreciate your help in advance
Thanks
You are open to sql injection. So use prepared query.
Replace your php code:
<?php
session_start();
$servername = "localhost";
$username = "******";
$password = "******";
// Create connection
$database_name = "id2425621_login";
if(isset($_POST['submit'])){
$conn = mysqli_connect($servername, $username, $password, $database_name);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$username=$_POST['username']; // username value get by form using $_POST
$password=$_POST['password']; // password value get by form using $_POST
$stmt = mysqli_prepare($conn, "SELECT * FROM mylogin WHERE username=? AND password=?");
mysqli_stmt_bind_param($stmt, 'ss', $username, $password);
mysqli_stmt_execute($stmt);
if (mysqli_stmt_affected_rows($stmt) > 0){
echo "sucess";
} else {
echo "fail";
}
mysqli_stmt_close($stmt);
mysqli_close($conn);
}
Do checking for connection. Check error log if got any clues.
$conn = mysqli_connect($servername, $username, $password, $database_name);
// Check connection
if (!$conn)
{
die("Connection error: " . mysqli_connect_error());
}
Hope this help you. For reference
Here is your Answer
<?php
session_start();
$servername = "localhost";
$username = "******";
$password = "******";
// Create connection
$database_name = "id2425621_login";
$conn = mysqli_connect($servername, $username, $password, $database_name);
if (!$conn) {
die(mysqli_error($conn));
}
if (isset($_POST['submit']))
{
$username='abc';
$password='abc123';
$query = mysqli_query($conn, "SELECT * FROM mylogin WHERE username='$username' and password='$password'");
if(!$query){
echo("Error description: " . mysqli_error($conn));
} else if(mysqli_num_rows($query) > 0){
echo "success";
} else {
echo "invalid user name or password";
}
}
?>
I'm trying to figure out how to upload a file into the database where that form contains multiple textfields. I uploaded a BLOB field into the database. So as I try to search the field using the ID number, it will retrieve me the values associated with it. Which works fine, so I added the function of being able to upload a file into that specific id number. I get all sorts of errors and I would like to have an assistance with it. Anyone care to help out? Here are the codes:
<?php
$host = "localhost";
$user = "root";
$password ="";
$database = "ntmadb";
$id = "";
$firstname = "";
$lastname = "";
$username = "";
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
// connect to mysql database
try{
$connect = mysqli_connect($host, $user, $password, $database);
} catch (mysqli_sql_exception $ex) {
echo 'Error';
}
// get values from the form
function getPosts()
{
$posts = array();
$posts[0] = $_POST['id'];
$posts[1] = $_POST['firstname'];
$posts[2] = $_POST['lastname'];
$posts[3] = $_POST['username'];
return $posts;
}
// Search
if(isset($_POST['search']))
{
$data = getPosts();
$search_Query = "SELECT * FROM members WHERE id = $data[0]";
$search_Result = mysqli_query($connect, $search_Query);
if($search_Result)
{
if(mysqli_num_rows($search_Result))
{
while($row = mysqli_fetch_array($search_Result))
{
$id = $row['id'];
$firstname = $row['firstname'];
$lastname = $row['lastname'];
$username = $row['username'];
}
}else{
echo 'No Data For This Id';
}
}else{
echo 'Result Error';
}
}
// Edit
if(isset($_POST['update']))
{
$data = getPosts();
$update_Query = "UPDATE `members` SET `firstname`='$data[1]',`lastname`='$data[2]',`username`='$data[3]' WHERE `id` = $data[0]";
try{
$update_Result = mysqli_query($connect, $update_Query);
if($update_Result)
{
if(mysqli_affected_rows($connect) > 0)
{
echo 'Data Updated';
}else{
echo 'Data Not Updated';
}
}
} catch (Exception $ex) {
echo 'Error Update '.$ex->getMessage();
}
}
<!--UPLOADUPLOADUPLOADUPLOADUPLOADUPLOADUPLOADUPLOADUPLOADUPLOADUPLOADUPLOADUPLOAD -->
// Check if a file has been uploaded
if(isset($_FILES['uploaded_file'])) {
// Make sure the file was sent without errors
if($_FILES['uploaded_file']['error'] == 0) {
// Connect to the database
$dbLink = new mysqli('localhost', 'root', '', 'ntmadb');
if(mysqli_connect_errno()) {
die("MySQL connection failed: ". mysqli_connect_error());
}
// Gather all required data
$data = $dbLink->real_escape_string(file_get_contents($_FILES ['uploaded_file']['tmp_name']));
// Create the SQL query
$query = "
INSERT INTO `members` (
`data`
)
VALUES (
'{$data}' NOW()
)";
// Execute the query
$result = $dbLink->query($query);
// Check if it was successfull
if($result) {
echo 'Success! Your file was successfully added!';
}
else {
echo 'Error! Failed to insert the file'
. "<pre>{$dbLink->error}</pre>";
}
}
else {
echo 'An error accured while the file was being uploaded. '
. 'Error code: '. intval($_FILES['uploaded_file']['error']);
}
// Close the mysql connection
$dbLink->close();
}
else {
echo 'Error! A file was not sent!';
}
?>
and here is the html file:
<!DOCTYPE Html>
<html>
<head>
<title>PHP INSERT UPDATE DELETE SEARCH</title>
</head>
<body>
<form action="index4.php" method="post" enctype="multipart/form-data" >
<input type="number" name="id" placeholder="Id" value="<?php echo $id;?>"><br><br>
<input type="text" name="firstname" placeholder="First Name" value="<?php echo $firstname;?>"><br><br>
<input type="text" name="lastname" placeholder="Last Name" value="<?php echo $lastname;?>"><br><br>
<input type="text" name="username" placeholder="User Name" value="<?php echo $username;?>"><br><br>
<div>
<p>
<!-- Input For Edit Values -->
<input type="submit" name="update" value="Update">
<!-- Input For Find Values With The given ID -->
<input type="submit" name="search" value="Find">
</p>
<p>
<input type="file" name="uploaded_file">
<br>
<input type="submit" value="Upload file">
</p>
</div>
</form>
</body>
</html>
Thanks to anyone who can provide me with help. :)
My problem is to get the pagination to work correctly.
Since I have a $page = $POST_["zain"] for receiving the records there is a problem with the pagination that it shows only result of first page.
Here is my code
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form action="zain.php" method="post">
Topic: <input type="text" name="topic"><br />
<br />
Name: <input type="text" name="name"><br /><br />
Attendance: <input type="text" name="attendance"><br />
<br />
<input type="reset" name="reset">
<input type="submit" id = "go" name="submit" value="Go">
</form>
<?php
$user = 'root';
$password = 'zz224466';
$db = 'Zain';
// Create connection
$conn = mysqli_connect('localhost', $user, $password, $db);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "";
mysqli_select_db($conn, "zain");
//$sql = "CREATE TABLE Lectures(Topic varchar(20), Name varchar(20), Attendence int)";
$sqli = "INSERT INTO lectures(Topic , Name , Attendence) VALUES('$_POST[topic]','$_POST[name]','$_POST[attendance]')";
mysqli_query($conn, $sqli);
////////////////////////// For print DATABASE on the screen using PAGINATION ////////////////////////////////////////
mysqli_select_db($conn, "zain");
if(isset($_GET['page'])){
if($page=="" || $page=="1")
{
$page1 = 0;
}
else
{
$page1 = ($page*5)-5;
}
}
$dataBase = "SELECT * FROM lectures limit $page1,5";
$print = mysqli_query($conn, $dataBase);
while ($record = mysqli_fetch_array($print))
{
echo $record['Topic'];
echo "</br>";
}
$selectDatabase = "SELECT * FROM lectures";
$res1 = mysqli_query($conn, $selectDatabase);
$countRow = mysqli_num_rows($res1);
$a = $countRow/5;
$a = ceil($a);
echo "<br>" . $a;
echo "</br> </br>";
for($b=1; $b<=$a; $b++)
{
?><?php echo $b . " ";?><?php
}
mysqli_close($conn);
?>
</body>
</html>
on the top of your page.
$zain = !empty($_POST["zain"])?$_POST["zain"]:(!empty($_GET["zain"])?$_GET["zain"]:false);
if(!$zain) die("zain is empty");
then replace all other $_POST["zain"] to $zain
On the link part
for($b=1; $b<=$a; $b++)
{
?><?php echo $b . " ";?><?php
}
So i have a website, and i am trying to test the new user register functionality. I am not getting an output for any of the echos in my LogInHelper.php file. The goal is to be able to enter information for a new user, post it to LogInHelper.php, see if the passwords entered are equal, and if they are not, update the result div to the error message.
this is my LogIn.php file containing the html:
<!DOCTYPE html>
<html>
<head>
<title>Ticket Log In</title>
<script src = "../../jquery.js"></script>
<style>
body{
padding:0;
margin:0;
}
#box {
background:blue;
text-align:center;
padding:10px;
color:white;
width:500px;
height:300px;
margin: 0 auto;
}
#LogIn {
background:blue;
text-align:center;
padding:10px;
color:white;
width:500px;
height:300px;
margin: 0 auto;
}
</style>
<script>
$(document).ready(function(){
$("#sub").click(function(){
var fist_name = $("#firstname").val();
var last_name = $("#lastname").val();
var user_email = $("#email").val();
var department_id = $("#department").val();
var user_pass = $("#pass").val();
var user_pass2 = $("#pass2").val();
$.post("LogInHelper.php",{firstname:first_name,lastname:last_name,email:user_email,department:department_id,pass:user_pass,pass2:user_pass2},function(data){
$("#result").html(data);
});
});
$("#sub2").click(function(){
var loginuser_email = $("#loginemail").val();
var loginuser_pass = $("#loginpass").val();
$.post("LogInHelper.php",{loginemail:loginuser_email,loginpass:loginuser_pass},function(data){
$("#result2").html(data);
});
});
$('#box').hide();
$('.new').click(function() {
$('#box').toggle();
$('#LogIn').toggle();
});
});
</script>
</head>
<body>
<div id="box">
<input type ="submit" class = "new" value = "New User Register">
<h2>New User Register Here:</h2>
<input type ="text" name="firstname" id="firstname" placeholder="Enter Your First Name"/></br>
<input type ="text" name="lastname" id="lastname" placeholder="Enter Your Last Name"/></br>
<input type ="text" name="email" id="email" placeholder="Enter Your email"/></br>
<form action="LogInHelper.php" method="post">
<select id = "department" name = "department">
<?php
$servername = "localhost";
$username = "quantco_Ted";
$password = "Quantum1";
$database = "quantco_Interns";
$con = mysqli_connect($servername,$username,$password,$database);
if($con->connect_error){
die("Connection failed " . $con->connect_error);
}
$sql = "select Department_name,id from Department";
$result = mysqli_query($con,$sql);
while ($row = mysqli_fetch_array($result)) {
$department = $row['Department_name'];
$id = $row['id'];
echo "<option value = '$id'>$department</option>";
}
?></select></form>
<input type ="password" name="pass" id="pass" placeholder="Enter Your Password"/>
<input type ="password" name="pass2" id="pass2" placeholder="Re-Enter Your Password"/>
</br></br>
<input type ="submit" name = "sub" value = "Register" id = "sub"/>
<div id="result"></div>
</div>
<div id="LogIn">
<input type ="submit" class = "new" value = "New User Register">
<h2>Registered User Log In:</h2>
<input type ="text" name="loginemail" id="loginemail" placeholder="Enter Your Email"/></br>
<input type ="password" name="loginpass" id="loginpass" placeholder="Enter Your Password"/>
</br></br>
<input type ="submit" name = "sub2" value = "Submit" id = "sub2"/>
<div id="result2"></div>
</div>
</body>
</body>
</html>
Here is my LogInHelper file that receives the posts:
<?php
$servername = "localhost";
$username = "user";
$password = "pass";
$database = "db";
$con = mysqli_connect($servername,$username,$password,$database);
if($con->connect_error){
die("Connection failed " . $con->connect_error);
}
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$id = $_POST['department'];
$email = $_POST['email'];
$pass = md5($_POST['pass']);
$pass2 = md5($_POST['pass2']);
echo $firstname;
echo $lastname;
echo $id;
echo $email;
echo $pass;
echo $pass2;
$sel = "select * from Employee where email='$email'";
$run = mysqli_query($con,$sel);
$check_email = mysqli_num_rows($run);
if(!($pass==$pass2)){
echo "<h2>Your emails do not match, please try again!</h2>";
exit();
}
else if($check_email==1){
echo "<h2>This email is already registered, please try another!</h2>";
exit();
}
else{
$insert = "insert into Employee (email, first, last, department_id,pass,) values ('$email','$firstname','$lastname','$id', '$pass')";
$run_insert = mysqli_query($con,$insert);
if($run_insert){
echo "<h2>Registration Successful, Thanks!</h2>";
}
}
mysqli_close($con);
?>
I have check your $("#sub").click(function(){ and found that you have typo mistake in var fist_name = $("#firstname").val(); so it should be var first_name = $("#firstname").val();
Please update this after that it will work