i am very new to php mysql, i am using the following php from to input data. my var_dump shows all the values i have entered in the form correctly. database connection was also successful. but the data are not inserted into the MariaDB table. i have cross-checked that the table structure, values and data types are matching. everything seem to be ok but the database table was never updated with the data . any help would be much appreciated ! thanks in advance.
dropdown-form.php
=================
<?php
include('database.php');
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Chiefdom Zambia</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/water.css#2/out/water.min.css">
<style>
.container
{
border-radius: 5px;
background-color: #f2f2f2;
padding: 20px;
}
.col-25
{
float: left;
width: 25%;
margin-top: 6px;
}
.col-75
{
float: left;
width: 75%;
margin-top: 6px;
}
/* Clear floats after the columns */
.row:after {
content: "";
display: table;
clear: both;
}
/* Responsive layout - when the screen is less than 600px wide, make the two columns stack on top of each other instead of next to each other */
#media screen and (max-width: 600px) {
.col-25,
.col-75,
input[type=submit] {
width: 100%;
margin-top: 0;
}
}
Chiefdom Empowerment Data Collection
<div class="container">
<div class="dependent-dropdown">
<form method="post" action="dropdown-form.php">
<legend style="text-align: center"> Land Info </legend>
<legend style="text-align: center"> Country : Zambia </legend>
<div class="input-field">
<select name="pro_id" id="country">
<option value="pro_id">Select your Province here</option>
<?php
$countryData = "SELECT id, name from countries";
$result = mysqli_query($conn, $countryData);
if (mysqli_num_rows($result) > 0) {
while ($arr = mysqli_fetch_assoc($result)) {
?>
<option value="<?php echo $arr['id']; ?>">
<?php echo $arr['name']; ?>
</option>
<?php
}
}
?>
</select>
</div>
<div class="input-field">
<select name="dist_id" id="state">
<option value="dist_id">Select your District here</option>
</select>
</div>
<div class="input-field">
<select name="chief_id" id="city">
<option value="chief_id">Select your Chiefdom here </option>
</select>
</div>
<input type="text" placeholder="Enter Zone Number " name="zone_no">
<input type="text" placeholder="Enter Zone Name " name="zone_name">
<input type="text" placeholder="Enter Locality" name="locality">
<legend style="text-align: center"> Farmer Info </legend>
<input type="text" placeholder="Enter Name of the Farmer" name="farmer_name"></input>
<input type="text" placeholder="Enter NRC Number of the Farmer " name="nrc_no">
<input type="text" placeholder="Enter Contact Number of the Farmer " name="contact_no">
<input type="text" placeholder="Land Holding in Hectare (Ha)" name="land_holding">
<legend style="text-align: center"> Crop Info </legend>
<select name="crops_no" id="form-selector">
<option value="0">Select Total Number of Crops </option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
<br>
<button>submit</button>
</form>
</div>
</div>
</body>
</html>
<?php
$pro_id = filter_input(INPUT_POST, "pro_id", FILTER_VALIDATE_INT);
$dist_id = filter_input(INPUT_POST, "dist_id", FILTER_VALIDATE_INT);
$chief_id = filter_input(INPUT_POST, "chief_id", FILTER_VALIDATE_INT);
$zone_no = $_POST["zone_no"];
$zone_name = $_POST["zone_name"];
$locality = $_POST["locality"];
$farmer_name = $_POST["farmer_name"];
$nrc_no = $_POST["nrc_no"];
$contact_no = $_POST["contact_no"];
$land_holding = $_POST["land_holding"];
$crops_no = filter_input(INPUT_POST, "crops_no", FILTER_VALIDATE_INT);
ini_set('display_errors', 1); ini_set('log_errors',1); error_reporting(E_ALL); mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$sql = "INSERT INTO farmer (' province`, `district`, `chiefdom`, `zone no`, `zone name`,`local`, `farmer name`, `nrc no`, `mobile no`, `land holding`, `no of crops`, ) VALUES ( ?,?,?,?,?,?,?,?,?,?,?)";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
die(mysqli_error($conn));
}
mysqli_stmt_bind_param(
$stmt,
"iiisssssssi",
$pro_id,
$dist_id,
$chief_id,
$zone_no,
$zone_name,
$locality,
$farmer_name,
$nrc_no,
$contact_no,
$land_holding,
$crops_no
);
if (mysqli_stmt_execute($stmt)) {
echo "Record added successfully";
} else {
echo "Error: " . mysqli_error($conn);
}
mysqli_stmt_close($stmt);
database.php
============
$dbHost = "localhost";
$dbUsername = "root";
$dbPassword = "";
$dbName = "ddl";
$conn = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
if (mysqli_connect_errno()) {
die("Connection Error: " . mysqli_connect_error());
}
`
scenarios were:
i have checked the database connection for errors. data type and values are perfect.table column and sql query are matching. manual entry of sql query accepts the data and updated in the table.
i got the following error:
Fatal error: Uncaught mysqli_sql_exception: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '' province, district, chiefdom, zone no, zone name,local, farmer ...' at line 1 in dropdown-form.php:255 Stack trace: #0 dropdown-form.php(255): mysqli_stmt_prepare(Object(mysqli_stmt), 'INSERT INTO far...') #1 {main} thrown in dropdown-form.php on line 255
It looks like you are using a back tick around the field names rather than a straight quote. I would recommend using an editor that does syntax highlighting (there are lots of free ones) so these issues will jump to your eyes. This will bring your focus to the parts that matter more.
The MySQL syntax here is incorrect, which is precisely where the error spotted a problem:
INSERT INTO farmer (`province`, `district`, ...
-- ^ -- Fixed
Do pay extremely close attention to what MySQL says in its error messages. It is usually pinpointing the exact problem, and it did here, to the character.
Related
I am currently developing a hotel reservation system. I've created a sign up and login page for the guest to make reservation. Ive tested my program and whenever I enter details for sign up process, it got successfully stored in the database. The problem now is that when I try to enter the same detail for login process, its not working. I feel like its not connected to the database but I don't know what I got wrong.
The error that I get everytime I try to login is "incorrect id or password", eventhough Ive already stored the same details in database during signup process.
Please help me find the solution for this one. Below are my coding so far. Thank you.
*note: This project is done during online class so my groupmate and I have to do our parts and I am in charge of putting in all together. This part is my friend's. When she runs it on her computer, she can login successfully. I have already changed the database name to mine but its still seems like its not connected for some reason :/
<?php
$hostname = "localhost";
$username= "root";
$password = "";
$db_name = "project";
$connect = mysqli_connect($hostname, $username, $password, $db_name);
if (!$connect){
echo "Connection failed!";
}
?>
This is the login page. (File Name: custlogin.php)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset = "UTF-8">
<title> My First Web Page </title>
</head>
<style>
#import url('https://fonts.googleapis.com/css2?family=Poppins&display=swap');
body
{
font-family: Arial, Helvetica, sans-serif;
font-size: 15px;
background-attachment: fixed;
background-size: 100% 100%;
margin: 0;
padding: 0;
background-image: url('https://assets.hyatt.com/content/dam/hyatt/hyattdam/images/2019/06/25/1437/Grand-Hyatt-Seoul-P1448-Sofabed-Service.jpg/Grand-Hyatt-Seoul-P1448-Sofabed-Service.16x9.jpg?imwidth=1280');
background-repeat: no-repeat;
}
input[type=text], input[type=password]
{
width: 40%;
padding: 12px 20px;
margin: 8px 0;
border: 2px solid #ccc;
box-sizing: border-box;
}
button
{
background-color: black;
color: white;
font-family: 'Poppins', sans-serif;
font-size: 13px;
border: none;
cursor: pointer;
text-align : center;
width: 70px;
height:30px;
}
button: hover
{
opacity: 0.8;
}
.cancelbtn, .join
{
width: 70px;
height:30px;
text-align: center;
background-color: black;
color:white;
}
.container
{
margin-top: 110px;
padding: 30px;
background-color: white;
margin-left: 300px;
margin-right: 300px;
text-align:center;
background: rgba(211,211,211,0.6);
}
span. password
{
float: right;
padding-top: 16px;
}
/* Change styles for span and cancel button on extra small screens */
#media screen and (max-width: 300px) {
span.password {
display: block;
float: none;
}
.cancelbtn {
width: 100%;
}
* {
box-sizing: border-box;
}
/* Create two equal columns that floats next to each other */
.column {
float: left;
width: 70%;
padding: 10px;
}
/* Clear floats after the columns */
.row:after {
content: "";
display: table;
clear: both;
}
</style>
<body>
<div class="container">
<form action = "custlogin2.php" method="post">
<?php if (isset($_GET['error'])) { ?>
<p class="error"><?php echo $_GET['error']; ?></p>
<?php } ?>
<p style="text-decoration: underline;"><b>WELCOME TO SECRET MIRAGE HOTEL</b></p><br><br><br>
<b>Member Id</b><br>
<input type="text" placeholder="Enter Member Id" name="memberID" required><br>
<b>Password</b><br>
<input type="password" placeholder="Enter Password" name="password" required><br><br>
<br>
<button type="submit">Sign In</button>
</form> <br>
<button onclick="document.location='custsignup.php'" class="join" style="float:left; width: 90px;">Join Now</button>
<button onclick="document.location='project.php'" class="cancelbtn" style="float:right;">Cancel</button>
<br>
</div>
</body>
</html>
This one to check. (custlogin2.php)
<?php
session_start();
include "db_connect.php";
if (isset($_POST['memberID']) && isset($_POST['password'])) {
function validate($data){
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$memberID = validate($_POST['memberID']);
$password = validate($_POST['password']);
// hashing the password
$password = md5($password);
$sql = "SELECT * FROM customer WHERE memberID='$memberID' AND password='$password'";
$result = mysqli_query($connect, $sql);
if (mysqli_num_rows($result) === 1) {
$row = mysqli_fetch_assoc($result);
if ($row['memberID'] === $memberID && $row['password'] === $password) {
$_SESSION['memberID'] = $row['memberID'];
$_SESSION['firstName'] = $row['firstName'];
$_SESSION['lastName'] = $row['lastName'];
$_SESSION['cust_email'] = $row['cust_email'];
$_SESSION['cust_Address'] = $row['cust_Address'];
header("Location: home2.php");
exit();
}else{
header("Location: custlogin.php?error=Incorect Id or Password");
exit();
}
}else{
header("Location: custlogin.php?error=Incorect Id or Password");
exit();
}
}else{
header("Location: custlogin.php");
exit();
}
?>
This the sign up form
<body>
<div class="container">
<form action="custsignup-check.php" method="post">
<?php if (isset($_GET['error'])) { ?>
<p class="error"><?php echo $_GET['error']; ?></p>
<?php } ?>
<?php if (isset($_GET['success'])) { ?>
<p class="success"><?php echo $_GET['success']; ?></p>
<?php } ?>
<div class="row">
<p style="font-size:18px; text-decoration:underline;"><b>Join Secret Mirage</b></p>
<div class="column">
<b>First Name</b><br>
<input type="text"
placeholder="Enter First Name"
name="firstName" required><br>
<b>Id Number</b><br>
<input type="text"
placeholder="Enter Id Number"
name="memberID" required><br>
<b>Password</b><br>
<input type="password"
placeholder="Enter Password"
name="password" required><br>
<b>Email</b><br>
<input type="text"
placeholder="Enter Email"
name="cust_email" required><br>
</div>
<div class="column">
<b>Last Name</b><br>
<input type="text"
placeholder="Enter Last Name"
name="lastName" required><br>
<b>Address</b><br>'
<input type="text"
placeholder="Enter Address"
name="cust_Address" required><br>
<b>Confirm Password</b><br>
<input type="password" placeholder="Confirm Password" name="re_password" required><br>
<p style="text-align:justify;">By signing up, I agree to Secret Mariage's Terms of Use and Secret Mariage Member
Terms and Conditions.<p>
</div>
</div>
<button type="submit">Join</button>
</form>
<button onclick="document.location='project.php'" class="cancelbtn">Cancel</button>
<button onclick="document.location='custlogin.php'" class="login">Login</button>
<br>
</div>
</body>
</html>
This is the sign up check.
<?php
session_start();
include "db_connect.php";
if (isset($_POST['memberID']) && isset($_POST['firstName'])
&& isset($_POST['lastName']) && isset($_POST['password'])
&& isset($_POST['cust_email']) && isset($_POST['cust_Address'])) {
function validate($data){
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$memberID = validate($_POST['memberID']);
$firstName = validate($_POST['firstName']);
$lastName = validate($_POST['lastName']);
$password = validate($_POST['password']);
$re_password = validate($_POST['re_password']);
$cust_email = ($_POST['cust_email']);
$cust_Address = ($_POST['cust_Address']);
if($password !== $re_password){
header("Location: custsignup.php?error=The confirmation password does not match");
exit();
}
else{
// hashing the password
$password = md5($password);
$sql2 = "INSERT INTO customer(memberID, firstName, lastName, password, cust_email, cust_Address) VALUES('$memberID', '$firstName', '$lastName','$password', '$cust_email', '$cust_Address' )";
$result2 = mysqli_query($connect, $sql2);
if ($result2)
{
header("Location: custsignup.php?success=Your account has been created successfully");
exit();
}
else
{
header("Location: custsignup.php?error=unknown error occurred");
exit();
}
}
}else
{
header("Location: custsignup.php");
exit();
}
I am going to try to give you a simple solution and at the same time protect yourself from sql injection:
First here is the code of the connection to the database, file called connection.php
<?php
function connect(){
$con=mysqli_connect("localhost","root","","dbname");
if(!$con)
die("Could not connect");
return $con;
}
?>
Now the php code or form used to login:
login.php:
<html>
<head><title>Login Page</title></head>
<body>
<form method="POST" action="checkLogin.php">
<label>Username:
<input type="text" name="username" required>
</label><br>
<label>Password
<input type="password" name="password" required>
</label><br>
<input type="submit" value="Login">
</form>
</body>
</html>
Now I am going to define a function in another file called validate.php
<?php
function validate($con,$data){
$newData=htmlspecialchars($data);
$newData=mysqli_real_escape_string($con,$newData);//this function is a built in function used to protect you from sql injection. It requires 2 parameters.
The first one is the connection to database and the second is the variable you are using
return $newData;
}
?>
Now the php code used to check if the username and password are right . the file is called checkLogin.php:
<?php
session_start();
require("connection.php");
require("validate.php");
$username=$_POST["username"];
$password=$_POST["password"];
$con=connect();//this function is called from the connection.php file
$username=validate($con,$username);//this function called from validate.php file
$password=validate($con,$password);
$checkLogin="SELECT count(*) from users where username='$username' and password='$password'";
$res=mysqli_query($con,$checkLogin);
$row=mysqli_fetch_array($res);
if($row[0]==1){
$_SESSION["username"]=$username;
mysqli_close($con);
header("Location:home.php");
exit();
}else{
header("Refresh:0 ; url=login.php");//this wait until the alert shows up and when you press ok in the alert it will take you back to the login page
echo "<script>";
echo "window.alert('Wrong username and password')";//you can write javascript inside php
echo "</script>";
}
mysqli_close($con);
?>
Tips for solving your issue:
Add an error_log(print_r($sql,true)); to your code after you have called the $sql variable. copy this SQL and run it in your MySQL directly and see if it generates any result.
If it does generate a reesult then the issue is in your PHP.
If it does not generate a result then the issue is in the data in your MySQL.
Do not run validate on your $password string.
Add an error_log(print_r($row,true)); to your code after you have loaded the row data and see if it shows anything?
Be careful with type checking comparison === . If your memberId is an integer value, you should ensure that both side of the check are the correct type.
`if((int)$row['memberID'] === (int)$memberID
&& (string)$row['password'] === (string)$password){...`
Advice for your MySQL
You should NOT be using root as your active username, root is too open and is a huge security risk. You need to make a new SQL user associated with this database and use that connection rather than root.
You should be setting your Connection Character Set when you establish your MySQL script connection.
SELECT * is bad practise and inefficient. You should select only the columns you are actually going to use.
mysqli_num_rows (and all similar PHP processes) are unreliable and can in certain situations be inaccurate. If you want a row count you should run an SQL SELECT COUNT(*)... query. You don't need to count rows here, simply you need to be sure that the array that is generated is populated so you can simply use if(count($result) > 0){... instead.
Advice for your PHP coding style:
You should be using PHP Prepared Statements. No excuse. Learn them, use them.
you should be using PHP's own password_hash and password_verify functions and NOT MD5. MD5 is not appropriate for storing passwords and anyone who tells you different is very out of date!
You should NOT be running ANY processing on the input password string. You should NOT be using your validate() function on the given user password, as it might change the value and prevent their login.
Error messages for the user should be held in a $_SESSION value and not in the URL. If you insist on putting error messages in the URL you should at least urlencode() (and decode) them!
Error details should be sent to the PHP error_log and NOT output to the user (this can be a security issue). See also: Where does PHP store the error log? (php5, apache, fastcgi, cpanel)
How to learn more about how to code in PHP correctly and safely:
Visit here: https://phptherightway.com/
Advice for your HTML
You should be using HTML5. You should stop using older HTML4 tags and reshape your HTML pages to use HTML syntax (<strong> instead of <b>, etc.)
If you insist on using <style> syntax, it should be inside your <head> element. But using this is NOT RECOMMENDED.
Advice for your CSS
You should NOT be using inline CSS. You should be putting your CSS styles in an external stylesheet and calling that stylesheet in the <head> part of your HTML page.
It is bad practise to use float: for block positioning, there are many better methods of placing elements on the page with CSS3 such as Flexbox and others.
What you've done right:
You have correctly put exit statements after header redirects. Many people fail to do this, so I'm pleased to see you have this sorted! :-)
I'm trying to learn PHP & Mysqli and ran into a few problems when trying to echo/print row id (or in this case "ref") as H2 (where it says "FORM").
Also when I add a new row it should get the next id in the database.
I hope that makes sense.
Sorry if this has already been posted. Couldn't find it.
<?php
//server with default setting (user 'root' with no password) */
define('DB_SERVER', 'host');
define('DB_USERNAME', 'user');
define('DB_PASSWORD', '****');
define('DB_NAME', 'database');
$link = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD);
if (!$link) {
die('could not connect: ' . mysqli_connect_error());
}
$db_selected = mysqli_select_db($link, DB_NAME);
if (!$db_selected) {
die('Cant use ' . DB_NAME . ': ' . mysqli_connect_error());
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$value_1 = $_POST['column_1'];
$value_2 = $_POST['column_2'];
$value_3 = $_POST['column_3'];
$sql = "INSERT INTO maskiner (column_1, column_2, column_3) VALUES ('$value_1', '$value_2', '$value_3')";
if (!mysqli_query($link, $sql)) {
die('ERROR: ' . mysqli_connect_error());
}
mysqli_close($link);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Test2</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css">
<style type="text/css">
body{ font: 14px sans-serif; }
.wrapper{ width: 350px; padding: 20px; }
</style>
</head>
<body>
<div class="wrapper">
<h2>FORM</h2>
<p>Please fill this form to create an account.</p>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<div class="form-group">
<label>Column_1</label>
<input type="text" name="column_1"class="form-control" value="<?php echo $value_1; ?>">
<span class="help-block"></span>
</div>
<div class="form-group">
<label>Column_2</label>
<input type="text" name="column_2"class="form-control" value="<?php echo $value_2; ?>">
<span class="help-block"></span>
</div>
<div class="form-group">
<label>Column_3</label>
<input type="text" name="column_3"class="form-control" value="<?php echo $value_3; ?>">
<span class="help-block"></span>
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" value="Submit">
<input type="reset" class="btn btn-default" value="Reset">
</div>
</form>
</div>
</body>
</html>
I'm not sure to understand properly your problem, but please try to create your table in your database using
CREATE TABLE IF NOT EXISTS `your table` (
`id` int(11) NOT NULL AUTO_INCREMENT,
this way, your ID row will auto increment, and you don't have to feed the value
If i understand you need last insert id. If that true, you sould use fallowing code
$last_id = mysqli_insert_id($link);
Above code gets last inserted increment id.
Note: Your id column in your table, it have to been increment property
If you want to know in advance the next id, you can't use
$next_id = mysqli_insert_id($link)+1;
because when you close mysql connection the next time you use mysqli_insert_id() you get 0.
You can use the query: select max(id)+1 as next_id from maskiner; , but if you delete the last inserted row you'll get a wrong id. To avoid that you can assign next_id in the sql insert statement:
$sql = "INSERT INTO maskiner (id, column_1, column_2, column_3) VALUES ('$next_id','$value_1', '$value_2', '$value_3')";
<?php
include("connection.php");
session_start();
if($_SERVER["REQUEST_METHOD"] == "POST") {
// username and password sent from form
$myusername = mysqli_real_escape_string($conn,$_POST['username']);
$mypassword = mysqli_real_escape_string($conn,$_POST['password']);
$row['userID'] = $myuserid;
$sql = "SELECT * FROM u803621131_login.users WHERE username = '$myusername' and password = '$mypassword'";
$result = mysqli_query($conn,$sql);
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
$active = $row['active'];
$count = mysqli_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row
if($count == 1) {
session_start("myuserid");
$_SESSION['login_user'] = $myusername;
$_SESSION['login_id'] = $myuserid;
header("location: welcome.php");
}else {
$error = "Your Login Name or Password is invalid";
}
}
?>
<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 action = "" method = "post">
<label>UserName :</label><input type = "text" name = "username" class = "box"/><br /><br />
<label>Password :</label><input type = "password" name = "password" class = "box" /><br/><br />
<input type = "submit" value = " Submit "/><br />
</form>
<div style = "font-size:11px; color:#cc0000; margin-top:10px"><?php echo $error; ?></div>
</div>
</div>
</div>
</body>
</html>
Login.php - The login page with all the changed parts, the actual login works as it should. although it is hard to tell if there are any other issues
<?php session_start();
include'../../connection.php';?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="description" content="">
<meta name="keywords" content="">
<link rel="stylesheet" type="text/css" href=".../../../../style.css">
<title>Home</title>
<!--[if IE]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<?php include('../../main/main.php');?>
</head>
<body>
<div class=containermain>
<h1>I5-6600k.php</h1>
<form action="ratepost.php" method="post">
<label for="rating">rating:</label>
<select name="rating" id="rating" value="rating" >
<option>
<option value="1">1 </option>
<option value="2">2</option>
<option value="3">3 </option>
<option value="4">4</option>
<option value="5">5</option>
</option>
</select>
<input type="submit" value="Submit">
</form>
<h2>graphics card write up................</h2>
<?php echo "Hello " . $_SESSION['user']; ?>
<p> </p>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
</div>
<div
class="fb-like"
data-share="true"
data-width="450"
data-show-faces="true">
</div>
<!---------------------------------------COMMENT BOX---------------------------------------------------->
<div class="comments" align="center">
<form action="" method="post" >
<textarea rows="4" cols="50" name="comment">
Please type a comment if you are logged in....
</textarea>
<input type="submit" value="Submit">
</form>
<?php
if (isset($_SESSION['login_id']) && !empty($_SESSION['login_id'])) {
$id = $_SESSION['login_id'];
$sqlinsert = "INSERT INTO comment (userID, comment, dCpuID) VALUES ('$id', '$comment', '1')";
if(mysqli_query($conn, $sqlinsert)){
header("Location: i5-6600k");
} else {
echo "ERROR: Could not able to execute $sqlinsert. " . mysqli_error($conn);
}
}
// close connection
$sql = "SELECT `users`.`username`, `comment`.`comment`, `comment`.`timestamp`\n"
. "FROM `users`\n"
. "LEFT JOIN `comment` ON `users`.`userID` = `comment`.`userID` \n"
. "where dCpuID = 1";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<table><tr><th>Username</th><th>Comment</th><th>Timestamp</th>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["username"]. "</td><td>" . $row["comment"]."</td><td>" . $row["timestamp"]. "</td>";
}
echo "</table>";
} else {
echo "0 results";
}
?>
</div>
<?php include('../../assets/footer.php');?>
<div class="fb-comments" data-href="http://www.computercomparison.tk/#home" data-numposts="5"></div>
</body>
</html>
Have included entirety of 2nd page, incase there may be clashes with other parts of the code in the site that may be pointed out.
Also you will find lots of code in strange places, only testing bits at the mo.
<?php
include('connection.php');
session_start();
$user_check = $_SESSION['login_user'];
$ses_sql = mysqli_query($conn,"select username, from users where username = '$user_check' ");
$row = mysqli_fetch_array($ses_sql,MYSQLI_ASSOC);
$login_session = $row['username'];
if(!isset($_SESSION['login_user'])){
header("location:login.php");
}
?>
Have this session.php file, didn't think it was too relevant but changing it around did affect logging in and stuff, it is in good condition here, wonder if there is anything i need to change here too? it is linked to the welcome.php
Following the error message you connected a column for the comment authors ID to one in your account table using a foreign key.
As shown in your picture they're both INT. But you are trying to insert a VARCHAR (the username) into this column instead.
My approach would be to get the user's ID by a sql query or even better save the users ID to the session:
session_start();
$_SESSION['login_user'] = $usernameFromFormOrWhatever;
$_SESSION['login_id'] = $usersID;
So you can fill your userID column with it:
$id = $_SESSION['login_id'];
$sqlinsert = "INSERT INTO comment (userID, comment, dCpuID) VALUES ('$id', '$comment', '1')";
Additionally the entered ID in your comments table must also appear in a row of your accounts table as ID of a user. Otherwise you will get an error message like you do now.
Hi I'm having some problems when I'm trying to submit a form of mine, everything seems to look fine on my end but im not quite sure why it's still not working any help would be appreciated.
config.php
<?php
$servername = "localhost";
$username = "release";
$password = "";
$dbname = "release";
// Create connection
$con = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
submit.php
<?php
include('config.php');
$producers = $_POST['producers'];
$company = $_POST['company'];
$title = $_POST['title'];
if(!$producers or !$company or !$title) {
echo 'Please make sure to fill out all required feilds.';
} else {
// Insert into DB
$sql = "INSERT INTO release (id, producers, company, title)
VALUES ('null', '$producers', '$company', '$title')";
}
if ($con->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $con->error;
}$con->close();
?>
index.php
<html>
<head>
<link href="css/bootstrap.min.css" rel="stylesheet" media="screen">
<link href="css/bootstrap-responsive.min.css" rel="stylesheet" media="screen">
<script type="text/javascript" src="js/jquery-1.8.0.min.js"></script>
<script type="text/javascript" src="js/bootstrap.min.js"></script>
<style>
input[type="text"] {
height: 30px;
}
</style>
<title>RRP ยป Welcome!</title>
</head>
<body>
<div style="width: 1080px; margin-top: 50px;">
<h3>Welcome!</h3>
<h4>You can edit the basic release form info below. <br /> Once done hit the "Submit" button to carry on to the new form!</h4>
<div class="container">
<form class="contact-us form-horizontal" action="submit.php" method="post">
<div class="control-group">
<label class="control-label">Producers</label>
<div class="controls">
<div class="input-prepend">
<span class="add-on"><i class="icon-user"></i></span>
<input type="text" class="input-xlarge" name="producers" placeholder="Producers(seperate by commas)">
</div>
</div>
</div>
<div class="control-group">
<label class="control-label">Production Company</label>
<div class="controls">
<div class="input-prepend">
<span class="add-on"><i class="icon-globe"></i></span>
<input type="text" class="input-xlarge" name="company" placeholder="Rolling Ridges Productions">
</div>
</div>
</div>
<div class="control-group">
<label class="control-label">Title</label>
<div class="controls">
<div class="input-prepend">
<span class="add-on"><i class="icon-pencil"></i></span>
<input type="text" class="input-xlarge" name="title" placeholder="Desperate Measures">
</div>
</div>
</div>
<div class="control-group">
<div class="controls">
<button type="submit" class="btn btn-primary">Submit</button>
<button type="button" class="btn">Cancel</button>
</div>
</div>
</form>
</body>
</html>
error
Error: INSERT INTO release (id, producers, company, title) VALUES ('null', 'lol', 'lol', 'lol')
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'release (id, producers, company, title) VALUES ('null', 'lol', 'lol', 'lol')' at line 1
Resolved: was as simple as adding ticks to release
release is a MySQL keyword, and should be enclosed in backticks: `release`
try to use backticks in table name if it is keyword release
$sql = "INSERT INTO `release` (id, producers, company, title)
VALUES ('null', '$producers', '$company', '$title')";
Also it is better to write your database in the following format
database name -> db_name eg db_release, and
table name -> tb_name eg tb_release
so as to avoid keywords errors
It seems to me that id should not be assigned the string value 'null'. Typically id columns are auto increment, in which case you should simply omit the column:
$sql = "INSERT INTO `release` (producers, company, title)
VALUES ('".addslashes($producers)."', '".addslashes($company)."', '".addslashes($title)."'";
The addslashes is to protect again SQL injection. You should also sanitize your inputs:
$producers = strval($_POST['producers']);
$company = strval($_POST['company']);
$title = strval($_POST['title']);
I am trying to store form value in database but wrong value is stored in database for mobilenumber field in my table. In table, I have the following 4 fields.
id (auto increment),
mobilenumber,
operator,
date.
Value displayed correctly when I do echo.
But while storing mobile number in database table, I am not getting the same value of mobilenumber field.
I have the following code.
home page
<?php include "header.php"?>
<body>
<div class="form-group">
<form name="myForm" action="invite.php" method="post" class="elegant-aero" onsubmit="return ValidateForm()" >
<h1> Congratulations. You have been invited to win Rs 148 Recharge.
<span>Please fill all the details to get a Rs 148 Recharge.</span>
</h1>
<label>
<span>Mobile Number</span>
<input name="Mobile" id="mob" type="text" placeholder="Prepaid Mobile Number" required />
</label>
<label>
<span>Operator</span><select name="Operator">
<option value="Select Operator">Select Operator</option>
<option value="Bsnl">BSNL</option>
<option value="Airtel">Airtel</option>
<option value="reliance">Reliance</option>
<option value="Vodafone">Vodafone</option>
<option value="Videocone">Videocone</option>
<option value="Aircel">Aircel</option>
<option value="Telenor">Telenor</option>
<option value="Idea">Idea</option>
<option value="Tataindicom">Tataindicom</option>
<option value="other">Other</option>
</select>
</label>
<label>
<span> </span>
<input type="submit" class="button" value="Proceed To Recharge" />
</label>
</form>
<div>
</body>
<?php include "footer.php" ?>
</html>
page 2
<html>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "recharge_project";
/**$mobile = $_POST['Mobile'];
$operator = $_POST['Operator'];
**/
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO customer (id, mobilenumber, mobileoperator) VALUES ('', '$_POST[Mobile]', '$_POST[Operator]')";
if ($conn->query($sql) === TRUE) {
echo "datainserteed";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
<?php include "header.php"?>
<body xmlns="http://www.w3.org/1999/html">
<div class="form-group">
<form class="elegant-aero" >
<p> Invite your 10 active <span style="color:#FF0000"> WhatsApp Friends</span> <!-- and 3 <span style="color:#FF0000">WhatsApp Groups </span>-->to claim your recharge
</p>
<label>
<a class="button1" href="whatsapp://send?text=http://rechargetoday.net || Super Promo offer. Get Rs 148 free recharge. Visit above link to get your recharge.NOTE :Offer valid across India!!" onclick="return myFunction()" >Invite</a>
</br>
</label>
<?php echo"</br>";?>
<label>
<a name="finish" type="submit" class="button2" onclick="return aboveTen()">Finished- Inviting 10 friends </a>
</label>
<label>
</label>
</form>
<div>
</body>
</html>
I have the following JS code.
var invite = 0;
function ValidateForm()
{
var fld= document.forms["myForm"]["Mobile"].value;
var phoneno = /^\d{10}$/;
if(fld.match(phoneno))
{
return true;
}
else
{
alert("Please enter valid number");
return false;
}
}
function myFunction(){ invite ++; }
When I echoed $sql, I got the below query.
INSERT INTO customer (mobilenumber, mobileoperator) VALUES ( 8574968578, 'Vodafone')
Try using $sql = "INSERT INTO customer (id, mobilenumber, mobileoperator) VALUES ('', '$_POST['Mobile']', '$_POST['Operator']')"; rather
$sql = "INSERT INTO customer (id, mobilenumber, mobileoperator) VALUES ('', '$_POST[Mobile]', '$_POST[Operator]')";.