My form is capturing date from jquery date picker, the form works fine without the date picker but with it, it just gives this error:
Error: Unknown column '$time' in 'field list'
Below is my php & html code
<?php
//form submitted
if (isset($_POST['create'])) {
//require db details
require_once '../dblogin.php';
//set flag
$OK = false;
// create database connection
$conn = new mysqli ($host, $user, $password, $database) or die("Connection Failed");
// initialize prepared statement
$stmt = $conn->stmt_init();
// create SQL to insert task
$sql = 'INSERT INTO tasks (task_name, task_project_id, task_assignee_id, datepicker, task_created_by, task_schedule, task_duration, task_end_date, task_creation_date, task_notes, task_status)
VALUES(?, ?, ?, ?, '.$_SESSION['id'].', ?, ?, $time, NOW(), ?, ?)';
if ($stmt->prepare($sql)) {
// bind parameters and execute statement
$stmt->bind_param('siissss', $_POST['task_name'], $_POST['task_project_id'], $_POST['task_assignee_id'], $_POST['datepicker'], $_POST['task_duration'], $_POST['task_notes'], $_POST['task_status']);
// execute and get number of affected rows
$stmt->execute();
if ($stmt->affected_rows > 0) {
$OK = true;
}
}
// redirect if successful or display error
if ($OK) {
header('Location: task_confirmation.php');
exit;
} else {
$error = $stmt->error;
}
}
?>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=utf-8” />
<title>Create new task</title>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.1/jquery-ui.js"></script>
<script>
$(function() {
$( "#datepicker" ).datepicker({dateFormat: 'yy-mm-dd' });
});
</script>
<link rel="stylesheet" type="text/css" href="../allcss/style.css" />
</head>
<body>
<?php
require('../Login/includes/header.inc.php');
?>
<div id="content">
<?php if (isset($error)) {
echo "<p>Error: $error</p>";
} ?>
<form id="form1" method="post" action="">
<div id="add">
<p>
<label for="task_name"class="title">Task name:</label>
<input name="task_name" type="text" class="widebox" id="task_name">
</p>
<p>
<span class="title">Project: </span><select name="task_project_id" size "5">
<?php
require_once '../dblogin.php';
$conn = new mysqli ($host, $user, $password, $database) or die("Connection Failed");
$stmt2 = $conn->stmt_init();
//pulls project names for the select element//
$sql2 = 'select * from projects';
$stmt2->prepare($sql2);
$stmt2->execute();
$result = $stmt2->get_result();
while($resultRow = $result->fetch_array(MYSQLI_ASSOC))
{
var_dump($resultRow);
echo "<option value='".$resultRow[project_id]."'>".$resultRow[project_name]."</option>";
}
$result->close();
$stmt2->close();
?>
</select>
</p>
<p>
<span class="title">Assignee: </span><select name="task_assignee_id" size "5">
<?php
require_once '../dblogin.php';
$conn = new mysqli ($host, $user, $password, $database) or die("Connection Failed");
$stmt3 = $conn->stmt_init();
//pulls intern names for the select element//
$sql3 = "select * from users where user_role='INT'";
$stmt3->prepare($sql3);
$stmt3->execute();
$result = $stmt3->get_result();
while($resultRow = $result->fetch_array(MYSQLI_ASSOC))
{
var_dump($resultRow);
echo "<option value='".$resultRow[person_id]."'>".$resultRow[user_name]."</option>";
}
$result->close();
$stmt3->close();
?>
</select>
</p>
<p>
<label for="dates"class="title">Schedule for:</label>
<input name="datepicker" type="text" id="datepicker"/>
</p>
<p>
<span class="title">Duration: </span><select name="task_duration" size "1">
<option value="00:30:00">30 minutes</option>
<option value="01:00:00">1 hour</option>
<option value="01:30:00">1,5 hours</option>
</select>
</p>
<p>
<label for="task_notes"class="title">Additional notes:</label>
<input name="task_notes" type="text" class="widebox" id="task_notes">
</p>
<p>
<span class="title">task status: </span><select name="task_status" size "1">
<option value="Complete">Complete</option>
<option value="Incomplete">Incomplete</option>
</select>
</p>
<p class="submit">
<input type="submit" name="create" value="Create task" id="create">
</p>
</div>
</form>
</div>
<?php
require('../Login/includes/footer.inc.php');
?>
</body>
</html>
Could anyone help me solve this please
For some reason you are not using prepared statement for the $time value (and for $_SESSION['id'] as well).
It's either dangerous and being the very reason for the error you are getting.
$sql = 'INSERT INTO tasks (task_name, task_project_id, task_assignee_id,
datepicker, task_created_by, task_schedule, task_duration,
task_end_date, task_creation_date, task_notes, task_status)
VALUES(?, ?, ?, ?, ?, ?, ?, ?, NOW(), ?, ?)';
if ($stmt->prepare($sql)) {
// bind parameters and execute statement
$stmt->bind_param('siisissss', $_POST['task_name'], $_POST['task_project_id'],
$_POST['task_assignee_id'], $_POST['datepicker'], $_SESSION['id'],
$_POST['task_duration'], $time, $_POST['task_notes'], $_POST['task_status']);
it should be, or something like that. You need to check placeholders, types string and corresponding values yourself.
You are using single quotes for your query. That way $time isn't expanded to the variable value. You should use double Quotes (") like this:
"INSERT INTO tasks (task_name, task_project_id, task_assignee_id, datepicker, task_created_by, task_schedule, task_duration, task_end_date, task_creation_date, task_notes, task_status)
VALUES(?, ?, ?, ?, ".$_SESSION['id'].", ?, ?, $time, NOW(), ?, ?)";
Also I think you should use a parameter for $_SESSION['id'] and $time, too, since everyting coming from the user can't really be trusted.
Related
I have a html form which includes a question involving three radio buttons. I want the word 'road', 'both' or gravel' to be saved to my database. This field is set up as a varchar in the database.
This is my html:
<div class="form-group">
<label>Do you prefer just road or gravel/trail cycling as well?</label>
<label for="road">Just road</label>
<input type="radio" name="bike_terrain" id="road" value="road" required/>
<span class="invalid-feedback"><?php echo $bike_terrain_err; ?></span>
<label for="both">Both</label>
<input type="radio" name="bike_terrain" id="both" value="both" />
<span class="invalid-feedback"><?php echo $bike_terrain_err; ?></span>
<label for="gravel">Just gravel/trail</label>
<input type="radio" name="bike_terrain" id="gravel" value="gravel" />
<span class="invalid-feedback"><?php echo $bike_terrain_err; ?></span>
</div>
I am then using php to validate the input is not empty:
if(empty($_POST["bike_terrain"])){
$bike_terrain_err = "Please select a bike terrain.";
} else {
$bike_terrain = isset($_POST["bike_terrain"]);
}
And php to send it to my localhost database:
if(empty($username_err) && empty($email_err) && empty($bike_terrain_err)) {
// Prepare an insert statement
$sql = "INSERT INTO users (username, email, terrain) VALUES (?, ?, ?)";
if($stmt = mysqli_prepare($link, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "sss", $param_username, $param_email, $param_terrain);
// Set parameters
$param_username = $username;
$param_email = $email;
$param_terrain = $bike_terrain;
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
// Redirect to login page
header("location: login.php");
} else{
echo "Oops! Something went wrong. Please try again later.248";
}
}
}
(Note: I have cut out some of the other fields that I am inserting for simplicity)
$bike_terrain has previously been initialised as a string.
The problem is that nothing is being saved to the terrain field in my database and I don't know why!
Thank you very much! All suggestions, thoughts or ideas are very welcome.
Something like this (untested) should do the trick. you save the same radio with the same name so it would look like a selection somehow.
Had to quickly code from my mobile device XD
<?php
if(isset($_POST['submit'])){
$host = '127.0.0.1';
$user = 'root';
$pass = '';
$db = 'people_db'
$con = mysqli_connect($host, $user, $pass, $db) or die ('Cannot connect'.mysqli_error());
$fullname = mysqli_real_escape_string($con,$_POST['fullname']);
$gender = mysqli_real_escape_string($con,$_POST['gender']);
$q = "insert into employeedb (fullname, gender) values ('".$fullname."', '".$gender."')";
mysqli_result($con,$q);
echo 'Data Saved to Database!';
}
?>
<html>
<head>
<title>Save Radio to DB</title>
</head>
<body>
<form name="people" method="POST" action="index.php"
<input type="text" name="fullname" placeholder="Enter your name"/><br/>
<input type="radio" name="gender" value="Male"/>
<input type="radio" name="gender" value="Female"/><br/>
<input type="submit" name="submit" value="Submit"/>
</form>
</body>
</html>
I'm trying to make a form that posts the index.php input to my database table using index.php and connection.php. Also I'm trying to specify everything else to be in letter format except the phone number (puhelinnumero) in numeric format using bind_param, but it gives me this error:
Here is the index.php.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="lomake-container">
<form action="connection.php" method="POST">
<h2>Ilmoittautumis lomake</h2>
<div class="lomake-block">
<label for ="nimi">Etunimi</label>
<input type="text" name="etunimi" id="nimi" placeholder="Etunimi">
</div>
<div class="lomake-block">
<label for ="sukunimi">Sukunimi</label>
<input type="text" name="sukunimi" placeholder="Sukunimi">
</div>
<div class="lomake-block">
<label for="male">Mies</label>
<input type="radio" id="male" name="sukupuoli">
</div>
<div class="lomake-block">
<label for="female">Nainen</label>
<input type="radio" id="female" name="sukupuoli">
</div>
<div class="lomake-block">
<label for="other">Muu</label>
<input type="radio" id="other" name="sukupuoli">
</div>
<div class="lomake-block">
<label for ="sähköposti">Sähköposti</label>
<input type="text" name="sähköposti" id="sähköposti" placeholder="Sähköposti">
</div>
<div class="lomake-block">
<label for ="salasana">Salasana</label>
<input type="text" name="salasana" id="salasana" placeholder="Salasana">
</div>
<div>
<label for ="puhelinnumero">Puhelin numero</label>
<input type="text" name="puhelinnumero" id="puhelinnumero" placeholder="Puhelin num.">
</div>
<input type="submit" value="Lähetä">
</form>
</div>
</body>
</html>
Here is the connection.php
<?php
$etunimi = $_POST["etunimi"];
$sukunimi = $_POST["sukunimi"];
$sukupuoli = $_POST['sukupuoli'];
$sähköposti = $_POST['sähköposti'];
$salasana = $_POST['salasana'];
$puhelinnumero = $_POST['puhelinnumero'];
$servername = "localhost";
$username = "root";
$password = '';
$database = 'palvelu';
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}else {
echo "Yhteys onnistui";
$stmt = $conn->prepare("insert into lomake($etunimi, $sukunimi, $sukupuoli, $sähköposti, $salasana, $puhelinnumero)
values(?, ?, ?, ?, ?, ?)");
}
$stmt->bind_param("sssssi",$etunimi, $sukunimi, $sukupuoli, $sähköposti, $salasana);
echo "onnistui jea";
$stmt->execute();
$stmt->close();
$conn->close();
?>
Here is the table:
You can't parameterise column names, but anyway I'm pretty sure that's not actually your intention, and you've possibly slightly misunderstood how to build an INSERT query. You need to specify the column names you want to insert into. The variable values you're currently trying to use in place of column names will be automatically assimilated into the query via the ? placeholders when MySQL receives the query.
Also you forgot to put the last value into the bind_param command.
Lastly your logic is a tiny bit flawed - if the connection fails, then your code will die. There's no need for the else. If it doesn't die, just carry on.
Try this instead:
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Yhteys onnistui";
$stmt = $conn->prepare("insert into lomake(`nimi`, `sukunimi`, `gender`, `email`, `password`, `number`) values(?, ?, ?, ?, ?, ?)");
$stmt->bind_param("sssssi",$etunimi, $sukunimi, $sukupuoli, $sähköposti, $salasana, $puhelinnumero);
echo "onnistui jea";
$stmt->execute();
$stmt->close();
$conn->close();
P.S.
Here is the MySQL documentation reference for INSERT: https://dev.mysql.com/doc/refman/8.0/en/insert.html
Ok, here's what I'm trying to do. I'm inserting some data into my database. It's for a blog, and I have fields like author, tags, hidden meta tags, etc. I've been trying to figure this out for a few weeks. Essentially, I'm on my CMS and nothing seems to be inserting, yet I'm not getting any errors (even when forcing with error_reporting( E_ALL );). From what I can tell, everything is being submitted in the right order with the right variables Here's my code below, and thanks for helping!
HTML:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Admin Panel</title>
<link rel="stylesheet" href="../css/master.css">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css" integrity="sha384-UHRtZLI+pbxtHCWp1t77Bi1L4ZtiqrqD80Kn4Z8NTSRyMA2Fd33n5dQ8lWUE00s/" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/tag-editor/1.0.20/jquery.tag-editor.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/tag-editor/1.0.20/jquery.tag-editor.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js" type="text/javascript"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jodit/3.2.34/jodit.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/izitoast/1.4.0/css/iziToast.css">
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tag-editor/1.0.20/jquery.tag-editor.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jodit/3.2.34/jodit.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/izitoast/1.4.0/js/iziToast.min.js"></script>
</head>
<body>
<div class="admin">
<div class="a-padding"><li class="isni"><i class="fas fa-pen"></i> Write Posts</li></div>
<div class="a-padding"><li class="isni"><i class="fas fa-file-alt"></i> View Posts</li></div>
<div class="a-padding"><li class="isni"><i class="fas fa-bookmark"></i> Viewers</li></div>
<div class="a-padding"><li class="isni"><i class="fas fa-plus"></i> Widget</li></div>
</div>
<div class="main-body">
<h1>Start Writing</h1>
<form method="post">
<input type="text" name="title" placeholder="Title" class="form" required>
<div class="form-padding"><input type="text" name="author" placeholder="Author" class="form" required></div>
<div class="form-padding"><input type="text" name="imgurl" placeholder="IMG URL..." class="form"></div>
<div class="form-padding"><input type="text" name="tags" required></div>
<div class="form-padding"><input type="text" name="htags" required></div>
<div class="form-padding"><textarea id="body" name="bodydata" required></textarea></div>
<div class="spacer"><input type="checkbox" name="hpbox"> Make Highlight</div>
<input type="submit" name="post" class="form">
</form>
<!-- This is where the PHP lies -->
</div>
<script>
$(document).ready(function() {
var editor = new Jodit("#body", {
"uploader": {
"insertImageAsBase64URI": true
}
});
});
$('input[name="tags"]').tagEditor({
placeholder: "Meta Tags",
animateDelete: 100
});
$('input[name="htags"]').tagEditor({
placeholder: "Hidden Meta Tags",
animateDelete: 100
});
</script>
</body>
</html>
PHP:
// This is before the HTML
require '../imports/database.php';
error_reporting(E_ALL);
date_default_timezone_set('America/Chicago');
// ------ This is the rest of it, placed where the comment is in the HTML section above
if (isset($_POST["post"])) {
if (isset($_POST["hpbox"])) {
$title = $_POST["title"];
$author = $_POST["author"];
$imgurl = $_POST["imgurl"];
$tags = $_POST["tags"];
$htags = $_POST["htags"];
$bd = $_POST["bodydata"];
$date = date("D M d, Y");
$time = date("h:i A");
$p = "true";
$harch_date = date("M Y");
$pinsql = "UPDATE `posts` SET `hp`='false' WHERE `hp`='true'";
if ($con->query($pinsql) === TRUE) {
echo
'
<script type="text/javascript">
iziToast.show({
title: "Success!",
message: "Queried highlight",
backgroundColor: "#37c2dd"
});
</script>
';
} else {
echo "Error updating record: " . $con->error;
}
$stmt = $con->prepare("INSERT INTO `posts` (`title`, `author`, `image`, `bodydata`, `tags`, `htags`, `date`, `time`, `hp`, `arch_id`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
$stmt->bind_param("ssssssssss", $title, $author, $imgurl, $bd, $tags, $htags, $date, $time, $p, $harch_dat);
$stmt->execute();
$stmt->close();
echo
'
<script type="text/javascript">
iziToast.show({
title: "Success!",
message: "Post inserted",
backgroundColor: "#37c2dd"
});
</script>
';
}else {
$title = $_POST["title"];
$author = $_POST["author"];
$imgurl = $_POST["imgurl"];
$tags = $_POST["tags"];
$htags = $_POST["htags"];
$bd = $_POST["bodydata"];
$date = date("D M d, Y");
$time = date("h:i A");
$arch_date = date("M Y");
$p = "false";
$stmt = $con->prepare("INSERT INTO `posts` (`title`, `author`, `image`, `bodydata`, `tags`, `htags`, `date`, `time`, `hp`, `arch_id`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
$stmt->bind_param("ssssssssss", $title, $author, $imgurl, $bd, $tags, $htags, $date, $time, $p, $arch_date);
$stmt->execute();
$stmt->close();
$con->close();
echo
'
<script type="text/javascript">
iziToast.show({
title: "Success!",
message: "Post inserted",
backgroundColor: "#37c2dd"
});
</script>
';
}
}
Note: View entire file https://pastebin.com/xtmSGJRA
imports/database.php file:
<?php
$con = new mysqli('localhost', 'root', '', 'WWDB');
?>
I'd try to isolate the error first.
I asked for the database.php file to check if you are checking whether the connection is being made successfully. You are not. You can enable mysqli report mode in the same time using the following sequence in your database.php file:
mysqli_report(MYSQLI_REPORT_STRICT);
try {
$con = new mysqli('localhost', 'root', '', 'WWDB');
if ($con->connect_error) {
die('Connect Error (' . $con->connect_errno . ') ' . $con->connect_error);
}
} catch (Exception $e) {
echo 'ERROR:'.$e->getMessage();
}
After this, if it doesn't show any valuable error, try putting the execute command in similar try-catch block. I guess there may be a field that is defined like integer or boolean in your database table structure and you are passing a string value to it, so try catching that error.
EDIT: You didn't provide information whether the update query works. If you only have issues with the prepared statements and normal queries are working, you'll need to try different things, so does this work actually?
"UPDATE `posts` SET `hp`='false' WHERE `hp`='true'"
I am having trouble creating this login system. When someone logs in I want it to create a table, if not already. Then bring them to the form page, then insert the data. I have everything working until the insert on the last page.
After Steam API Login
<?php
session_start();
require ('../../../mysql_connect/mysqli_connect_accounts.php');
require ('../steamauth/steamauth.php');
require ('../steamauth/userInfo.php');
$steamid=$_SESSION['steamid'];
$query = "SELECT * FROM `".$steamid."`";
$response = #mysqli_query($dbc, $query);
if($response){
header("Location: http://theskindealer.com/index.php");
} else {
$create = "CREATE TABLE `".$steamid."` (
steam64 VARCHAR(30),
fullname VARCHAR(60),
tradeurl VARCHAR(60),
email VARCHAR(50),
age INT(3),
tos INT(1),
access INT(1),
freeze INT(1),
balance DECIMAL(9,2),
newsletter INT(1),
emailVerified INT(1)
)";
if ($dbc->query($create) === TRUE) {
header("Location: http://theskindealer.com/scripts/createAccount.php");
} else {
header("Location: http://theskindealer.com/pages/errorlogin.php");
}
}
$stmt->close();
$dbc->close();
?>
Then it REDIRECTS to the form page:
<!DOCTYPE HTML>
<?php
session_start();
require ('../../../mysql_connect/mysqli_connect_accounts.php');
require ('../steamauth/steamauth.php');
require ('../steamauth/userInfo.php');
$steamid=$_SESSION['steamid'];
?>
<html>
<head>
<title>TheSkinDealer | Setup</title>
<link rel="stylesheet" type="text/css" href="../css/accept.css"></head><body>
<div id="content">
<div id="acceptbox">
<img src="../images/logo.png">
<form action="setup.php" method="post">
<div id="name1">Full Name:</br> <input type="text" name="fullname"> </br></div>
<div id="name1">TradeURL: <a target="_blank" href="http://steamcommunity.com/id/me/tradeoffers/privacy#trade_offer_access_url">(?)</a></div> <input type="text" name="tradeurl"> </br>
<div id="name1">EMAIL:</div> <input type="text" name="email"> </br>
<div id="checkboxes">
Terms Of Serice: <input type="checkbox" name="tos" value="1"> </br>
18 Or Older: <input type="checkbox" name="age" value="1"></br>
Newsletter: <input type="checkbox" name="newsletter" value="1"></br>
</div>
<div id="returnhome">
<div id="accept"><input type="submit" value="Create Account"></a></div>
</div>
</form>
</div>
<center><div id="par">Purchases Or Sales Cannot Be Made Without Accepting TOS.</div></center>
</div>
</body>
</html>
Lastly the insert page:
<?php
session_start();
require ('../../../mysql_connect/mysqli_connect_accounts.php');
require ('../steamauth/steamauth.php');
require ('../steamauth/userInfo.php');
$steamid=$_SESSION['steamid'];
$insert = "INSERT INTO `".$steamid."` (steam64, freeze, access,
tos, balance, age, email, tradeurl, fullname, newsletter, emailVerified)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
$stmt = $dbc->prepare($insert);
$stmt->bind_param('sssssssssss',
$steam64,
$freeze,
$access,
$tos,
$balance,
$age,
$email,
$tradeurl,
$fullname,
$newsletter,
$emailVerified
);
$steam64 = $steamid;
$freeze = 0;
$access = 0;
$tos = $_POST["tos"];
$balance = 0.00;
$age = $_POST["age"];
$email = $_POST["email"];
$tradeurl = $_POST["tradeurl"];
$fullname = $_POST["fullname"];
$newsletter = $_POST["newsletter"];
$emailVerified = 0;
$stmt->execute();
header("Location: http://theskindealer.com/");
$stmt->close();
$dbc->close();
?>
Do you get any errors when executing this script?
You could for instance add error_reporting(E_ALL); to the top of your script to get a better look at errors.
Looking at the script it seems like you are binding variables before they exist.
You should put the variable assigments before the bind_param exetution:
$steam64 = $steamid;
$freeze = 0;
$access = 0;
$tos = $_POST["tos"];
$balance = 0.00;
$age = $_POST["age"];
$email = $_POST["email"];
$tradeurl = $_POST["tradeurl"];
$fullname = $_POST["fullname"];
$newsletter = $_POST["newsletter"];
$emailVerified = 0;
$stmt->bind_param('sssssssssss',
$steam64,
$freeze,
$access,
$tos,
$balance,
$age,
$email,
$tradeurl,
$fullname,
$newsletter,
$emailVerified
);
$stmt->execute();
Also keep in mind that numeric values like 0 must be bind with 'i' instead of 's'
See http://php.net/manual/de/mysqli-stmt.bind-param.php for more info.
For instance.
$stmt->bind_param('iiisdissssi',
This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 7 years ago.
I'm trying to write a registration form, firstly I tried to do it OO, but this didn't respond, it seemed to just clear the form and refresh the page, but didn't insert any data:
EDIT: Current code:
<?php
session_start();
include 'registrationform.php';
include 'connection.php';
if (isset($_POST['regsubmit']))
{
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$user = $_POST['username'];
$pass = $_POST['password'];
$query = "INSERT INTO users (firstname, lastname, username, password) VALUES(?, ?, ?, ?)";
$statement = $connection->prepare($query);
//bind parameters for markers, where (s = string, i = integer, d = double, b = blob)
$statement->bind_param('ssss', $firstname, $lastname, $username, $password);
if($statement->execute()){
print 'Success! ID of last inserted record is : ' .$statement->insert_id .'<br />';
//$_SESSION['username'] = $_POST['username'];
}else{
die('Error : ('. $mysqli->errno .') '. $mysqli->error);
}
$statement->close();
?>
Registration Form
<!DOCTYPE html>
<?php
include 'header.php';
?>
<center>
<html>
<link rel="stylesheet" type="text/css" href="web.css" />
</font>
<head>
</head>
<body>
<div id="registrationform">
Please enter your registration details<br /><br />
<form method="post" action="registrationsubmit.php">
First Name:
<input type="text" name="firstname" />
<br /><br>
Last Name:
<input type="text" name="lastname" />
<br /><br>
Username:
<input type="text" name="username" />
<br /><br>
Password:
<input type="text" name="password" />
<br /><br>
<input type="submit" name="regsubmit" value="Submit" />
</form>
</div>
</body>
</html>
</center>
OO Attempt
<?php
session_start();
include 'registrationform.php';
include 'connection.php';
if (isset($_POST['regsubmit']))
{
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$user = $_POST['username'];
$pass = $_POST['password'];
$stmt = $connection->prepare("INSERT INTO users VALUES (?, ?, ?, ?)");
$stmt->bind_param('ssss', $firstname, $lastname, $user, $pass);
$stmt->execute();
printf("%d Row inserted.\n", $stmt->affected_rows);
$stmt->close();
}
?>
As this wasn't working I tried just doing it without OO, for a starting point. But now I'm given the error "Access denied for user ''#'10.246.64.24' (using password: NO)", yet my connection connects fine and I've also written a login that works perfectly so can't figure it out. Here is the current code that I have:
registrationsubmit.php
<?php
include "connection.php";
include "header.php";
if(isset($_POST['regsubmit']))
{
mysql_select_db("c3438525_co_uk",$connection);
$firstname = $_POST['$firstname'];
$lastname = $_POST['$lastname'];
$username = $_POST['username'];
$password = $_POST['password'];
$query = "INSERT INTO users (FirstName, LastName, Username, Password) VALUES ('$firstname', '$lastname', '$username', '$password')";
$data = mysql_query ($query)or die(mysql_error());
if($data) { echo "Successfully Registered"; }
else
{
?>
<script>alert('error while registering you...');</script>
<?php
}
}
?>
Connection.php
<?php
ob_start();
$connection = mysqli_connect("***", "***", "BFUWGpn3", "***");
?>
You're using a mysqli_ connection and your query is mysql_
For the registrationsubmit.php
Use something on the lines:
$query = "INSERT INTO users (firstname, lastname, username, password) VALUES(?, ?, ?, ?)";
$statement = $connection->prepare($query);
//bind parameters for markers, where (s = string, i = integer, d = double, b = blob)
$statement->bind_param('ssss', $firstname, $lastname, $username, $password);
if($statement->execute()){
print 'Success! ID of last inserted record is : ' .$statement->insert_id .'<br />';
//$_SESSION['username'] = $_POST['username'];
}else{
die('Error : ('. $mysqli->errno .') '. $mysqli->error);
}
$statement->close();
Refer to : http://php.net/manual/en/mysqli.insert-id.php