Data not inserting into mysql table interestingly - php

I was making a review form in which a review will be taken from a textbox and inserted into the database. But the problem is that when I try running the code it gives the following error:
Warning: mysqli::query(): Couldn't fetch mysqli in C:\wamp64\path\to\file on line 12
The code that I wrote for doing the same is given below:
<?php
require_once('data.php');
require_once('connect.php');
$personName = $_GET['name'];
$value = $_POST['review'] ?? '';
echo "<p>".$personName;
echo "<p>".$value;
$sql = "INSERT INTO reviews (name, review) VALUES ('$personName', '$value')";
if($connection->query($sql) === TRUE) {
echo "Inserted";
} else {
echo "Not inserted";
}
?>
<!DOCTYPE html>
<html>
<head>
<style>
input[type=text], select {
width: 100%;
padding: 12px 20px;
margin: 8px 0;
display: inline-block;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
}
button[type=submit] {
width: 100%;
background-color: #4CAF50;
color: white;
padding: 14px 20px;
margin: 8px 0;
border: none;
border-radius: 4px;
cursor: pointer;
}
input[type=submit]:hover {
background-color: #45a049;
}
</style>
</head>
<body>
<form class="" method="post" >
<label for="form-element"></label>
<input type="text" name="review" class="form-control" id="review" placeholder="Enter anonymous review">
<button type="submit" class="menu">Submit</button>
</form>
</div>
</body>
</html>
It is interesting to note that everything that is stored in $personName and $value are being echoed correctly. But the problem appears when I try inserting the data stored in the variable into the database. This seems pretty disgusting topic. I tried to solve it the whole previous day but failed. Any help will be highly appreciated.
Also, I haven't added prepared statements feature for the time being but I will add the same to prevent it from mysql injection attacks as soon as this problem is solved.
[P.S.: I am still a beginner in PHP, So there are high chances that my mistakes are silly. Pardon if it is so. ]
connect.php:
<?php
$connection = mysqli_connect('localhost','root','');
if(!$connection) {
die("Failed to connect" . mysqli_error($connection));
}
else {
echo "";
}
$select_db = mysqli_select_db($connection, 'db2');
if(!$select_db) {
die("Database selection failed" . mysqli_error($connection));
}
else {
echo "";
}
?>

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "invoice";
$personName = "Bhaskar";
if(isset($_POST['submit'])){
$value = $_POST['review'];
echo "<p>".$personName;
echo "<p>".$value;
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql ="INSERT INTO tbl_review (name, review) VALUES ('$personName', '$value')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
?>
<!DOCTYPE html>
<html>
<head>
<style>
input[type=text], select {
width: 100%;
padding: 12px 20px;
margin: 8px 0;
display: inline-block;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
}
button[type=submit] {
width: 100%;
background-color: #4CAF50;
color: white;
padding: 14px 20px;
margin: 8px 0;
border: none;
border-radius: 4px;
cursor: pointer;
}
input[type=submit]:hover {
background-color: #45a049;
}
</style>
</head>
<body>
<form class="" method="post" action="" >
<label for="form-element"></label>
<input type="text" name="review" class="form-control" id="review" placeholder="Enter anonymous review">
<button type="submit" name="submit" class="menu">Submit</button>
</form>
</div>
</body>
</html>

Related

Displaying the post after entered

I have some HTML and PHP code, which is responsible for basically, when some text is entered into a field, it should display as a post (which I have already made partially), and I have written the PHP code responsible for database insertion as well. However, the only thing I want to do is, when the user types in the field and clicks post, the post should display. So for that I tried some code, however it isn't working. When filled in and the post button is clicked, the post isn't displaying. What to do? Code:
PHP:
<?php
session_start();
// Making Connection To The Database
$dbHost = "localhost";
$dbUser = "root";
$dbPass = "";
$database = "signup";
$connection = mysqli_connect($dbHost, $dbUser, $dbPass, $database) or die ("Sorry, we could not connect to the database");
// Posting System
if (!empty($_POST['postContent'])) {
$post = $_POST['postContent'];
$firstname = $_SESSION['firstname'];
$lastname = $_SESSION['lastname'];
$sql = "INSERT INTO posts (firstname, lastname, body, date_posted) VALUES (?, ?, ?, NOW())";
$stmt = mysqli_stmt_init($connection);
// nested if statement
if (!mysqli_stmt_prepare($stmt, $sql)) {
echo "";
} else {
mysqli_stmt_bind_param($stmt, "sss", $firstname, $lastname, $post);
mysqli_stmt_execute($stmt);
}
} else {
echo "";
}
?>
HTML & PHP:
<style>
.postPFP {
margin-left: 680px;
width: 70px;
position: fixed;
margin-top: 20px;
cursor: pointer;
}
.info {
margin-left: 756px;
position: fixed;
font-family: 'Rajdhani';
font-weight: bolder;
margin-top: 25px;
}
.postOptions {
position: fixed;
width: 70px;
margin-left: 1176px;
margin-top: 16px;
}
.thepost {
margin-top: 55px;
position: fixed;
display: none;
}
</style>
<div class="thepost">
<?php
$sql = "SELECT * FROM posts";
$result = mysqli_query($connection, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
?>
<div class="postFormat">
<img src="img/pfp.png" alt="pfp" onclick="location.href='profile.php'" class="postPFP">
<b><div class="info"><?php echo $firstname . " " . $lastname ?></div></b>
<img src="img/options.png" alt="postOptions" class="postOptions">
<hr style="margin-top: 85px; width: 600px; position: fixed; margin-left: 663px; border:1px solid black; border-radius: 10px">
<hr style="margin-top: 85px; width: 0px; height: 215px; position: fixed; margin-left: 1150px; border: 1px solid black; border-radius: 10px">
<hr style="margin-top: 300px; width: 600px; position: fixed; margin-left: 663px; border:1px solid black; border-radius: 10px">
<p style="margin-left: 670px; margin-top: 95px; position: fixed; font-family: 'Rajdhani'"><?php echo $row["body"]; ?></p>
</div>
<?php
}
}
?>
</div>

Trying to self delete a file with unlink() with no success

A new client who has a WordPress site needed to access his administration from which he was locked out by the person who setup the site. He only had FTP access so I had to create a script to connect to the DB and run a password change query. (yes I did confirm that he was truly the owner).
Because the file must be deleted after use, I placed unlink(__FILE__); at the end of the process, but the file remained.
The code (hopefully not considered unethical)
<?php
if( file_exists(dirname(__FILE__).'/wp-config.php') )
{
include 'wp-config.php';
$dbconnect = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
$usertbl = $table_prefix.'users';
$usermeta = $table_prefix.'usermeta';
$userlvl = $table_prefix.'user_level';
$users = "
SELECT ID, user_login, user_email
FROM $usertbl
LEFT JOIN $usermeta
ON $usertbl.ID = $usermeta.user_id
WHERE meta_key = '$userlvl'
AND meta_value = 10
";
$res = $dbconnect->query($users);
$usr= $optname='';
if( $res->num_rows > 0 ) {
while($row = $res->fetch_assoc()) {
$usr .= '<ul><li>'.$row['user_login'].'</li><li>'.$row['user_email'].'</li></ul>';
$optname .= '<option value="'.$row['user_login'].'">'.$row['user_login'].'</option>';
}
}
if( $dbconnect->connect_error ) {
echo '<p style="color:red">DB connection failed: ('.$dbconnect->connect_errno.') '.$dbconnect->connect_error.'<br>Database connection was blocked</p>';
exit();
}
// Run password update
$result='';
if( isset($_POST['username']) && isset($_POST['pwset']) )
{
$password = '"'.MD5($_POST['pwset']).'"';
$username = '"'.$_POST['username'].'"';
$query = "UPDATE $usertbl SET user_pass = $password WHERE user_login = $username";
$admin = str_replace($_SERVER['SCRIPT_NAME'],'',$_SERVER['SCRIPT_URI']).'/wp-admin';
if( $dbconnect->query($query) === TRUE )
{
$result = '<p class="success">The password update ran successfully.</p>';
$result .= '<p class="success">Now redirecting to admin...</p>';
// redirect to admin login in 7 seconds
echo '<meta http-equiv="refresh" content="7; URL='.$admin.'" />';
// file self delete
unlink(__FILE__);
}
}
} ?>
<!DOCTYPE html>
<html>
<head>
<title>Reset</title>
<style>
body {font-family: verdana; font-size: 13px; padding: 0 50px 50px;}
a {text-decoration: none; color: #b22525; font-weight: 900;}
input, select {display: block; border: 1px solid #bbb; padding: 4px; margin-bottom: 5px;}
.notice {background: #ddf7ff; padding: 8px;}
.notice-alert {background: #ffdde1; padding: 8px; font-size: 28px; text-align: center; color: #ce0100; font-weight: 900;}
.success {background: #f1ffdb; padding: 8px;}
input[type="submit"] {cursor: pointer;}
input[type="text"] {font-family: courier; padding: 3px;}
.footnote {text-align: center; background: #f2f2f2; padding: 5px;}
.list {margin: 20px 0;}
.list ul {list-style: none; padding: 0; margin: 0; overflow: hidden;}
.list li {float: left; padding: 5px; border: 1px solid #eee; width: 50%; box-sizing: border-box;}
.list .th {background: #ddd; font-weight: 900;}
</style>
</head>
<body>
<?php if( !file_exists(dirname(__FILE__).'/wp-config.php') ) {
echo '
<p class="notice-alert">
This file must be in the WordPress root directory where the wp-config.php file is located.
</p>
';
}else{
if( !empty($dbconnect->stat) )
echo '<p class="notice">database connection OK</p>';
?>
<form method="post" action="">
<h3>Admin Password Reset</h3>
<p class="notice-alert">Be sure to delete this file once done</p>
Select the user name to update*<br />
<select name="username" required="required">
<option value="">Select</option>
<?php echo $optname; ?>
</select>
Set new password*<br />
<input type="text" name="pwset" value="" required="required" />
<input type="submit" name="pwsend" value="Reset Password" />
<?php echo $result; ?>
</form>
<div class="list">
<h4>List of Administrators Found In User Database</h4>
<ul class="th"><li>Username</li><li>Email</li></ul>
<?php echo $usr; ?>
</div>
<?php } ?>
</body>
</html>
The output
What's missing in the process to get the self delete to run?

Display flex causes text to be split up

I'm trying to align the items in the center of the page. I'm using display: flex however, this causes the text to be split up into different columns but I don't want that, I want the text to be normal, you know. When the session is set, the text will show; you can see the forms are aligned in the center, but the text isn't.
* {
margin: 0;
padding: 0;
font-family: Arial, Helvetica, sans-serif;
font-size: 14px;
letter-spacing: -0.5px;
}
html,
body {
height: 100%;
width: 100%;
background: #fff;
}
.content-container {
width: 100%;
height: auto;
padding: 10pt;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
margin: 0 auto;
margin-top: 30pt;
display: flex;
justify-content: center;
}
.header {
top: 0;
position: fixed;
height: 30pt;
width: 100%;
background: rgba(255, 255, 255, 0.50);
border-bottom: 1.5px solid #0047FF;
}
.header-content {
width: 100%;
height: inherit;
margin: 0 auto;
white-space: nowrap;
line-height: 30pt;
padding: 0 5pt;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
.header-menu {
border-right: 1px solid #0047FF;
margin-right: 10pt;
width: auto;
height: inherit;
float: left;
padding: 0 5pt 0 0;
}
.header-menu ul li {
list-style: none;
float: left;
}
.header-menu ul li a {
color: #555;
text-decoration: none;
padding: 0 3pt;
float: left;
}
.logout-form__ button {
background: none;
cursor: pointer;
border: none;
outline: none;
color: #555;
}
.logout-form__ button:hover {
color: #888
}
.header-menu ul li a:after {
content: "/";
padding: 0 0 0 5pt
}
.header-menu ul li:last-child a:after {
content: "";
padding: 0;
}
.header-menu ul li a:hover {
color: #888;
}
.header-menu ul li a:hover:after {
color: #555
}
.header-search form input {
border: none;
background: rgba(255, 255, 255, 0.50);
outline: none;
padding: 5pt;
border-top: 1px solid #eee;
width: 250pt;
display: inline-block;
color: #555
}
.header-search form input:focus {
border-color: #ccc;
background: rgba(255, 255, 255, 0.80)
}
.header-search form button {
background: rgba(255, 255, 255, 0.50);
border: none;
outline: none;
border-top: 1px solid #eee;
padding: 5pt;
cursor: pointer;
color: #555
}
.header-search form button:hover {
border-color: #ccc;
background: rgba(255, 255, 255, 0.60);
}
.same-form-styling {
float: left;
padding: 10pt 0;
border-bottom: 1px solid #ccc;
width: auto;
width: 400pt
}
.forms-title {
border-bottom: 1px solid #ccc;
padding: 0 0 10pt 0;
margin-bottom: 10pt
}
.forms-title span {
font-size: 16px;
}
.same-form-styling form input {
width: 100%;
display: block;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
padding: 10pt 0;
border: none;
outline: none;
border-bottom: 1px solid #eee;
}
.same-form-styling form button {
border: none;
outline: none;
padding: 10pt;
border-left: 1px solid #eee;
float: left;
background: none;
border-right: 1px solid #eee;
width: 150pt;
}
<?php
include_once './Private/Backend/Database/conn.php';
if(isset($_POST['logout'])) {
session_destroy();
unset($_SESSION['id']);
unset($_SESSION['username']);
unset($_SESSION['email']);
header("location: index.php?a=login");
}
/* ### */
if(isset($_POST['login-btn'])) {
$l_email = mysqli_real_escape_string($main, $_POST['l-email']);
$l_email = stripcslashes($l_email);
$l_pass = mysqli_real_escape_string($main, $_POST['l-pass']);
$l_pass = stripcslashes($l_pass);
if(filter_var($l_email, FILTER_VALIDATE_EMAIL)) {
$hashed = md5(sha1(md5(sha1($l_pass))));
$sql = "SELECT * FROM accounts WHERE email='$l_email' and password='$hashed'";
$result = mysqli_query($main, $sql);
if(mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$_SESSION['id'] = $row['id'];
$_SESSION['username'] = $row['username'];
$_SESSION['email'] = $row['email'];
header("location: index.php");
}
} else {
header("location: index.php?a=login&loginErr=wrong&email=$l_email");
}
} else {
header("location: index.php?a=login&loginErr=invalidEmail&email=$l_email");
}
}
if(isset($_POST['reg-btn'])) {
$username = mysqli_real_escape_string($main, $_POST['reg-uname']);
$username = stripcslashes($username);
$username = strip_tags($username);
$email = mysqli_real_escape_string($main, $_POST['reg-email']);
$email = stripcslashes($email);
$email = strip_tags($email);
$email_c = mysqli_real_escape_string($main, $_POST['reg-c-email']);
$email_c = stripcslashes($email_c);
$pass = mysqli_real_escape_string($main, $_POST['reg-pass']);
$pass = stripcslashes($pass);
$pass_c = mysqli_real_escape_string($main, $_POST['reg-c-pass']);
$pass_c = stripcslashes($pass_c);
if(!empty($username && $email && $email_c && $pass && $pass_c)) {
$sql = "SELECT * FROM accounts WHERE username='$username'";
$result = mysqli_query($main, $sql);
if(mysqli_num_rows($result) > 0 ){
header("location: index.php?a=register&registerErr=userTaken&username=$username&email=$email&cEmail=$email_c");
} else {
if(filter_var($email, FILTER_VALIDATE_EMAIL)) {
if($email == $email_c) {
$sql = "SELECT * FROM accounts WHERE email='$email'";
$result = mysqli_query($main, $sql);
if(mysqli_num_rows($result) > 0) {
header("location: index.php?a=register&registerErr=emailTaken&username=$username&email=$email&cEmail=$email_c");
} else {
if(strlen($pass) >= 6) {
if($pass == $pass_c) {
$hashedBrown = md5(sha1(md5(sha1($pass))));
$sql = "INSERT INTO accounts (username, account_type, first_name, last_name, gender, bio, email, password) VALUES ('$username', 'Regular User' , '', '', '', '','$email', '$hashedBrown')";
$result = mysqli_query($main, $sql);
$sql = "SELECT * FROM accounts WHERE username='$username' and email='$email'";
$result = mysqli_query($main, $sql);
$row = mysqli_fetch_assoc($result);
$_SESSION['id'] = $row['id'];
$_SESSION['username'] = $row['username'];
$_SESSION['email'] = $row['email'];
header("location: index.php");
} else {
header("location: index.php?a=register&registerErr=passwordsDoNotMatch&username=$username&email=$email&cEmail=$email_c");
}
} else {
header("location: index.php?a=register&registerErr=passwordLen&username=$username&email=$email&cEmail=$email_c");
}
}
} else {
header("location: index.php?a=register&registerErr=emailsDoNotMatch&username=$username&email=$email&cEmail=$email_c");
}
} else {
header("location: index.php?a=register&registerErr=username=$username&email=$email&cEmail=$email_c");
}
}
} else {
header("location: index.php?a=register&registerErr=allEmpty");
}
}
?>
<!DOCTYPE html>
<html lang="en" style="overflow-x: hidden;">
<head>
<meta charset="UTF-8" />
<title>ICode Foundation</title>
<link rel="stylesheet" type="text/css" href="./Public/CSS/Beta/all.css" />
</head>
<body>
<div class="header">
<div class="header-content">
<div class="header-menu">
<ul>
<?php if(!isset($_SESSION['id'])) { ?><li>Register</li><?php } ?>
<?php if(!isset($_SESSION['id'])) { ?><li>Login</li><?php } ?>
<?php if(isset($_SESSION['id'])) { ?><li>Home</li><?php } ?>
<?php if(isset($_SESSION['id'])) { ?><li>You <span>(<strong><?php echo $_SESSION['username']; ?></strong>)</span></li><?php } ?>
<?php if(isset($_SESSION['id'])) { ?><li><a href="#">
<form action="index.php" method="POST" class="logout-form__">
<button type="submit" name="logout">
Logout
</button>
</form>
</a></li><?php } ?>
</ul>
</div>
<div class="header-search">
<form action="#" method="GET">
<input type="text" placeholder="Search" name="q" autocomplete="off" /><button type="submit" name="search-btn">Search</button>
</form>
</div>
</div>
</div>
<div class="content-container">
<?php if(!isset($_SESSION['id'])) { ?>
<?php if(isset($_GET['a'])) { ?>
<?php if($_GET['a']=="register") { ?>
<div class="register same-form-styling">
<div class="forms-title"><span>Register</span></div>
<form action="index.php" method="POST">
<input type="text" name="reg-uname" placeholder="Username" <?php if(isset($_GET['username'])) { echo 'value="' . $_GET['username'] . '"'; } ?> />
<input type="text" name="reg-email" placeholder="Email Address" <?php if(isset($_GET['email'])) { echo 'value="' . $_GET['email'] . '"'; } ?> />
<input type="text" name="reg-c-email" placeholder="Confirm Email" <?php if(isset($_GET['cEmail'])) { echo 'value="' . $_GET['cEmail'] . '"'; } ?> />
<input type="password" name="reg-pass" placeholder="Password" />
<input type="password" name="reg-c-pass" placeholder="Confirm Password" />
<button type="submit" name="reg-btn">Register</button>
</form>
<div class="register-info" style="clear:both;border-top: 1px solid #ccc;padding: 10pt 0 0 0;">You are not hindered to a specific array of characters to inlude in your password therefore, ensure your password is strong and memorable. Hindering users on what characters they can use in their password is an idiotic move hence, we don't include such feature nor endorse this practice. It is solely your fault and responsibility if your password is easily guessable.</div>
</div>
<?php } elseif($_GET['a']=="login") { ?>
<div class="login same-form-styling">
<div class="forms-title"><span>Login</span></div>
<form action="index.php" method="POST">
<input type="text" placeholder="Email" name="l-email" <?php if(isset($_GET['email'])) { echo 'value="' . $_GET['email'] . '"'; } ?> />
<input type="password" placeholder="Password" name="l-pass" />
<button type="text" name="login-btn">Login</button>
</form>
</div>
<?php } else { ?>
<div class="unknown">
Unknown operation; it's either login or register.
</div>
<?php } ?>
<?php } ?>
<?php } else { ?>
<h1>Welcome</h1>
<p>All you can do is log in, edit your profile can search, view other profiles. Functionality such as blogging is an intended feature to soon be implemented. This site will go through major updates to ensure full reliability and user usability. Other major implementations such as code integrations to advance the site's functionality is desirable however, this site shouldn't be too advanced which could lead to hindrances thinking of new concepts for future updates.</p>
<p>This site will be powered by volunteers; voluntary developers, graphic designers and other skills that are beneficially suggestive towards this project. Your skills must include an array of professional and impeccable knowledge of a broad range of subjects and that bring in a diverse array of talent of knowledge to this project to grow and enlarge the project in many different ways. If you're interested in developing the site, email the lead developer at adamhope470#gmail.com. </p>
<p>You must lay your email out in a way that is comprehensible and professional. Ensure that you include your skills and how you will benefit the project in an innovative and intuitive manner. Include your programming skills and what programming languages do you know etc. Any other things that may help the project in different ways.</p>
<p>Skills like legal and business is helpful alongside impeccable English language skills. These skills will eventually contribute to administration and communicating with users to provide support wherever mandatory. You account role will fluctuate the features that you have access to; do not ask nor request roles of high rank, trusted members will be granted administration whereas moderators will be nominated based on the contributions they have made like translations etc. This is a for-profit project however, this will be a non-profitable project for the time being. </p>
<p>If you have any inquiries, questions or reports, you can contact the site's lead developer here or you can contact another administrator here.</p>
<p><strong>Your account could be susceptible to a susepnsion or a perminate ban if you're ever witnessed infringing our community guidelines. Review them here. These guidelines will ensure that the tranquility is persistant throughput, which will ensure that this service is safe for everyone to use. With that stated, before pursuing, you agree that you're 13 years or older.</strong></p>
<?php } ?>
</div>
<div class="footer-wrap">
</div>
</body>
</html>
When you set display: flex on an element it automatically applies flex-direction: row and flex-wrap: nowrap on the children (flex items).
This means that the items will line up horizontally and cannot wrap.
You have this:
.content-container {
display: flex;
justify-content: center;
}
jsfiddle demo
Instead, set the container to a vertical direction and then center the items:
.content-container {
display: flex;
flex-direction: column;
align-items: center;
}
jsfiddle demo

How to add a simple validation in PHP?

How can i add a simple validation which checks if every input is not empty?
I'm just aiming a simple validation which shows an error in the php file if at least 1 form is empty. and proceed to add the input into the database when everything is completely filled up. I already set the variable for every input in the form field of the html form.
HTML code:
<html>
<head>
<title>FEATHER FRIENDS PIZZA SHOP</title>
</head>
<img src="pics/logo.png">
<style>
img {
display: block;
margin: auto;
width:100%;
}
input[type=text], select {
width: 100%;
padding: 12px 20px;
margin: 8px 0;
display: inline-block;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
}
input[type=submit] {
width: 100%;
background-color: #4CAF50;
color: white;
padding: 14px 20px;
margin: 8px 0;
border: none;
border-radius: 4px;
cursor: pointer;
}
input[type=reset] {
width: 100%;
background-color: #bfac2c;
color: white;
padding: 14px 20px;
margin: 8px 0;
border: none;
border-radius: 4px;
cursor: pointer;
}
input[type=reset]:hover {
background-color: #c43848;
}
input[type=submit]:hover {
background-color: #c43848;
}
div {
background-image: url('pics/bg.png');
background-attachment: fixed;
background-repeat: no-repeat;
background-size: 100% 100%;
padding: 100px;
}
body {
display: block;
margin: auto;
width: 100%;
height: 100%;
background-color: #f6f6d4;
background-attachment: fixed;
background-repeat: no-repeat;
background-size: 100% 100%;
}
</style>
<div>
<body>
<img src="pics/pizza.png">
<form action="http://localhost/insert.php" method="post">
<img src="pics/name.png">
<input type="text" id="fname" name="name" placeholder="Your full name...">
<img src="pics/size.png">
<select id="size" name="size">
<option value="small">Small</option>
<option value="medium">Medium</option>
<option value="large">Large</option>
<option value="extra large">Extra Large</option>
</select>
<img src="pics/crust.png">
<select id="crust" name="crust">
<option value="pan">Pan</option>
<option value="thin">Thin</option>
<option value="stuffed">Stuffed</option>
<option value="handtossed">Hand-Tossed</option>
<option value="deepdish">Deep Dish</option>
</select>
<img src="pics/garnish.png">
<input type="text" id="garnish" name="garnish" placeholder="Write your choices here! Ex: Pepperoni, Cheese, Bacon, Mushroom">
<img src="pics/address.png">
<input type="text" id="address" name="address" placeholder="Where should we deliver?">
<img src="pics/contact.png">
<input type="text" id="contact" name="contact" placeholder="What is your contact number?">
<input type="submit" value="Submit">
<input type="reset" value="Reset your Order?">
</form>
</div>
</body>
</html>
PHP code:
<?php
$link = mysqli_connect("localhost", "root", "", "pizza");
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$name = mysqli_real_escape_string($link, $_POST['name']);
$size = mysqli_real_escape_string($link, $_POST['size']);
$crust = mysqli_real_escape_string($link, $_POST['crust']);
$garnish = mysqli_real_escape_string($link, $_POST['garnish']);
$address = mysqli_real_escape_string($link, $_POST['address']);
$contact = mysqli_real_escape_string($link, $_POST['contact']);
$sql = "INSERT INTO deliver (name, size, crust, garnish, address, contact)
VALUES ('$name', '$size', '$crust', '$garnish', '$address', '$contact')";
if(mysqli_query($link, $sql)){
echo "Data successfully Saved.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
mysqli_close($link);
?>
Here is a simple line of code to check if all the form fields are populated:
<?php
$link = mysqli_connect("localhost", "root", "", "pizza");
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$name = mysqli_real_escape_string($link, $_POST['name']);
$size = mysqli_real_escape_string($link, $_POST['size']);
$crust = mysqli_real_escape_string($link, $_POST['crust']);
$garnish = mysqli_real_escape_string($link, $_POST['garnish']);
$address = mysqli_real_escape_string($link, $_POST['address']);
$contact = mysqli_real_escape_string($link, $_POST['contact']);
/*check if all the fields are not empty*/
if( $name != "" && $size != "" && $crust != "" && $garnish != "" && $address != "" && $contact != "") {
$sql = "INSERT INTO deliver (name, size, crust, garnish, address, contact) VALUES ('$name', '$size', '$crust', '$garnish', '$address', '$contact')";
if(mysqli_query($link, $sql)){
echo "Data successfully Saved.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
} else {
echo "Form incomplete";
}
mysqli_close($link);
?>

Check if Username and Email lalready exists using PHP [duplicate]

This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 6 years ago.
Hello Im trying to make my signup page check if a username or email is already in use. But it just goes over the code like its not their and before you mark this as a dupe of Check if username already exists using PHP I've already went over there and i tried the fix their but i didn't work so at this point I'm clueless I've tried every thing i know!
HTML for the sign up page
<?php
session_start();
include 'header.php';
$url = "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
if (strpos($url, 'error=username') !== false) {
echo "<div class='transition' style='height: 20px; background-color: #ff6b66; text-align: center; margin-top: 30px; margin-right: 40%; margin-left: 40%; border-radius: 20px; padding: 5px;'>Fill out username box!</div>";
}
$url = "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
if (strpos($url, 'error=password') !== false) {
echo "<div class='transition' style='height: 20px; background-color: #ff6b66; text-align: center; margin-top: 30px; margin-right: 40%; margin-left: 40%; border-radius: 20px; padding: 5px;'>Fill out password box!</div>";
}
$url = "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
if (strpos($url, 'error=first') !== false) {
echo "<div class='transition' style='height: 20px; background-color: #ff6b66; text-align: center; margin-top: 30px; margin-right: 40%; margin-left: 40%; border-radius: 20px; padding: 5px;'>Fill out First Name box!</div>";
}
$url = "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
if (strpos($url, 'error=last') !== false) {
echo "<div class='transition' style='height: 20px; background-color: #ff6b66; text-align: center; margin-top: 30px; margin-right: 40%; margin-left: 40%; border-radius: 20px; padding: 5px;'>Fill out Last Name box!</div>";
}
$url = "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
if (strpos($url, 'error=email') !== false) {
echo "<div class='transition' style=' transition-delay: 1s;box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2); height: 20px; background-color: #ff6b66; text-align: center; margin-top: 30px; margin-right: 40%; margin-left: 40%; border-radius: 20px; padding: 5px;'>Fill out Email box!</div>";
}
$url = "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
if (strpos($url, 'error=user_name_taken') !== false) {
echo "<div class='transition' style='height: 20px; background-color: #ff6b66; text-align: center; margin-top: 30px; margin-right: 40%; margin-left: 40%; border-radius: 20px; padding: 5px;'>This username is already in use!</div>";
}
$url = "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
if (strpos($url, 'error=user_email_taken') !== false) {
echo "<div class='transition' style='height: 20px; background-color: #ff6b66; text-align: center; margin-top: 30px; margin-right: 40%; margin-left: 40%; border-radius: 20px; padding: 5px;'>This email is already in use!</div>";
}
if (isset($_SESSION['id']) !== true) {
header('Location: ../login.php');
}
?>
<html>
<head>
<title>Add Teacher</title>
<link rel="stylesheet" type="text/css" href="../assets/css/adduser.css">
</head>
<body>
<div class="loginbox">
<h1 class="longintitle" style="font-family: Tahoma;">Add Teacher</h1>
<form class="form" action="../includes/adduser.php" method="post" enctype="multipart/form-data">
<input autocomplete="off" placeholder="Username" name="username" type="text" >
<input autocomplete="off" placeholder="Password" name="password" type="password">
<input autocomplete="off" placeholder="First Name" name="first" type="text">
<input autocomplete="off" placeholder="Last Name" name="last" type="text">
<input autocomplete="off" placeholder="Email" name="email" type="email">
<input class="loginbutton" name="create" type="submit" value="Create">
</form>
<p>Students will be in beta copie THIS IS ALPHA</p>
</div>
</body>
</html>
php for it
<?php
session_start();
include_once("../includes/db.php");
$id = $_POST['id'];
$username = $_POST['username'];
$password = $_POST['password'];
$first = $_POST['first'];
$last = $_POST['last'];
$email = $_POST['email'];
if (empty($username)) {
header('Location: ../teacher/adduser.php?error=username');
exit();
}
if (empty($password)) {
header('Location: ../teacher/adduser.php?error=password');
exit();
}
if (empty($first)) {
header('Location: ../teacher/adduser.php?error=first');
exit();
}
if (empty($last)) {
header('Location: ../teacher/adduser.php?error=last');
exit();
}
if (empty($email)) {
header('Location: ../teacher/adduser.php?error=email');
exit();
} else {
$sql = "SELECT * FROM user WHERE username='".$username."'";
$result = mysqli_query($conn, $sql);
$usernamecheck = mysql_num_rows($result);
if ($usernamecheck > 0) {
header('Location: ../teacher/adduser.php?error=user_name_taken');
exit();
}
$sql = "SELECT * FROM user WHERE email='$email'";
$result = mysqli_query($conn, $sql);
$emailtaken = mysql_num_rows($result);
if ($emailtaken > 0) {
header('Location: ../teacher/adduser.php?error=user_email_taken');
exit();
} else {
$sql = "INSERT INTO user (id, username, password, first, last, email) VALUES ('$id', '$username', '$password', '$first', '$last', '$email')";
$result = mysqli_query($conn, $sql);
header('Location: ../teacher/adduser.php');
}
}
?>
If need but "doubt it tho" the db.php
<?php
$conn = mysqli_connect("localhost", "dbuser", "dbpass", "dbmain");
if (!#mysqli_connect("localhost", "dbuser", "dbpass", "dbmain")) {
echo "<div style=' box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2); padding: 3px; background-color: red; height: 20px;'><h3 style='text-align: center;'>Cannot connect to database have the admin take a look!</h3></div>";
die(mysql_error());
}
else {
echo "<div style=' box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2); padding: 3px; background-color: lightgreen; height: 20px;'><h3 style='text-align: center;'>Connected to database Successfully!</h3></div>";
}
?>
Please help I dont know how to fix this! If you need more info just ask.
Thanks in advance!
As you are using mysqli, I think you may need to replace mysql_num_rows with mysqli_num_rows. (missing 'i' in mysqli_num_rows).
Replace "mysql_num_rows" with "mysqli_num_rows" , while fetching the rows. As $conn is a "mysqli_connect " instance.

Categories