MYSQL ERROR when submitting form - php

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']);

Related

Form to post into database table

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

Updating records in database using a pre populated form

Looks like I have 1 last issue that I can't solve due to the fact of being too unexperienced with this matter. This last issue that I can't get to work or basically I don't understand the order in how to do this.
Been able to do the following:
Form that writes records to database
Page that shows database records in a table
Added an edit button to the table that takes you to an edit.php page with a form that has all values pre filled.
What I'm trying to get to work now is to edit one of the inputs on the form so it get's updated in the database.
So far I have this on the edit.php page:
<?php
$servername = "localhost";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, name, email, age FROM members WHERE id =" .$_GET['id'];
$result = mysqli_query($conn,$sql);
if(mysqli_num_rows($result) > 0) {
$row = mysqli_fetch_assoc($result);
$id = $row['id'];
$name = $row['name'];
$email = $row['email'];
$age = $row['age'];
?>
<form action=" <?=$_SERVER['PHP_SELF']?> " method="POST">
<div align="center">
<div class="container">
<div class="row">
<div class="col-25">
<label for="#"></label>
</div>
<div class="col-75">
<h2>ID: <?php echo $row['id']; ?></h2>
</div>
</div>
<br>
<div class="row">
<div class="col-25">
<label for="name">Name:</label>
</div>
<div class="col-75">
<input type="text" name="name" value="<?php echo $row['name']; ?>" id="my-input" class="input-res">
</div>
</div>
<div class="row">
<div class="col-25">
<label for="email">Email:</label>
</div>
<div class="col-75">
<input type="text" name="email" value="<?php echo $row['email']; ?>" class="input-res">
</div>
</div>
<div class="row">
<div class="col-25">
<label for="age">Age:</label>
</div>
<div class="col-75">
<input type="text" name="age" value="<?php echo $row['age']; ?>" class="input-res">
</div>
</div>
<div class="row"><br>
<input type="submit" name="submit" value="Save updates" class="button">
</div>
</div>
</div>
</form>
</body>
</html>
Have tried adding this code below the form:
<?php
if(isset($_POST['Submit'])){//if the submit button is clicked
$sql="UPDATE name, email, age SET name, email, age WHERE name = ".$name.", email = ".$email.", age = ".$age.";
$conn->query($sql) or die("Cannot update");//update or error
}
?>
But the the page doesn't work anymore, tried changing from single quotes to double qoutes etc. but no success and a few other solutions (that unfortunatelly didn't work).
Need $_POST to get posted value
Use prepare for security
note: die is a wrong idea here
Correct code will be:
<?php
if (isset($_POST['Submit'],$_POST['name'],$_POST['email'],$_POST['age'],$_GET['id'])) { //if the submit button is clicked
$stmt = $conn->prepare('UPDATE name, email, age SET name = ?, email = ?, age = ? WHERE id=?');
$stmt->bind_param('ssii', $_POST['name'], $_POST['email'], $_POST['age'], $_GET['id']);
$stmt->execute();
echo "Updated successfully"; // Updated Successfully
}

mysqli insert row id

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')";

Phpmyadmin accepting only one field

I have a problem with Phpmyadmin, i just transfered my files to ubuntu because of a coursework
whenever i add a new field to phpmyadmin
it stops adding data
basically, its accepting only one field
and when you check the table data , it gives zero result
below are my codes
<!--This form links the fields to the database as well as allows inseting values to the database-->
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "password", "Pamplemousses_db");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$Name = mysqli_real_escape_string($link, $_POST['Name']);
$Surname = mysqli_real_escape_string($link, $_POST['Surname']);
// Attempt insert query execution
$sql = "INSERT INTO Transport (Name,Surname) VALUES ('$Name','$Surname')";
if(mysqli_query($link, $sql)){
echo "Records added successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Close connection
mysqli_close($db_connect);
header("location:Transportbooking.php?note=success");
?>
This is my html file
<!DOCTYPE html>
<html>
<head>
<title> Transport Booking | Pamplemousses </title>
<link rel="stylesheet" href="path/to/font-awesome/css/font-awesome.min.css">
<?php include("navigation_bar.html");?>
<?
error_reporting(0);
$note=$_REQUEST['note'];
?>
</head>
<title></title>
<link rel="stylesheet" type="text/css" href="hotels.css" />
</head>
<body>
<div id="page-wrap">
<?PHP if($note=='success')
{
echo "<div class=\"success\">Form successfully submitted!</div>";
}
?>
</div>
<br/>
<form action="transport_process.php" method="post" name="Transport">
<div id="contact-area">
<div class="form-all">
<ul class="form-section page-section">
<li id="cid_1" class="form-input-wide" data-type="control_head">
<div class="form-header-group">
<div class="header-text httal htvam">
<br/>
<h2 id="header_1" class="form-header">
Book Your Transport Here
</h2>
<br/>
</div>
</div>
</li>
<li class="form-line" data-type="control_fullname" id="id_3">
<div id="cid_3" class="form-input jf-required">
<span class="form-sub-label-container" style="vertical-align: top;">
<label class="form-sub-label" for="first_3" id="sublabel_first" style="min-height: 13px;"> Name </label><br/>
<input class="form-textbox" type="text" size="10" name="Name" id="Name" aria-describedby="name-format" required/><br/>
</span>
<span class="form-sub-label-container" style="vertical-align: top;">
<label class="form-sub-label" for="last_3" id="sublabel_last" style="min-height: 13px;"> Lastname </label><br/>
<input class="form-textbox" type="text" size="15" name="Surname" id="Surname" aria-describedby="name-format" required/>
</span>
<input type="submit" value="submit">
</ul>
</div>
</form>
</body>
</html>
Three Fields But only accepting ID and Name:
When i remove everything and include only name, the database store the Name
but the moment i add surname
it stops adding data
Please help

How to add variables into a mysql table from php

Okay so my objective is to have people able to select there schedule. her is the code so far
<?php
//if form has been submitted process it
if(isset($_POST['submit'])){
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "jesuitschedule";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = 'INSERT INTO schedule (Saturdaymorning, Saturdayafternoon, Sundaymorning, Sundayafternoon, weekday) VALUES (:Saturdaymorning, :Saturdayafternoon, :Sundaymorning, :Sundayafternoon, :weekday)';
// use exec() because no results are returned
$conn->exec($sql);
echo "New record created successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
}
//define page title
$title = 'schedule';
//include header template
require('layout/header.php');
?><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>schedule</title>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.1.0/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="style/main.css">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-xs-12 col-sm-8 col-md-6 col-sm-offset-2 col-md-offset-3">
<form role="form" method="post" action="" autocomplete="off">
<h2>Please Select your schedule</h2>
<hr>
<div class="form-group">
<input type="checkbox" name="Saturdamorning" id="Satmor" class="form-control input-lg" placeholder="User Name" value="yes" tabindex="1">Saturday Morning <br>
</div>
<div class="form-group">
<input type="checkbox" name="Saturdayafternoon" id="Sataft" class="form-control input-lg" placeholder="S" value="yes" tabindex="2">Saturday Afternoon <br>
</div>
<div class="form-group">
<input type="checkbox" name="Sundaymorning" id="Sunmor" class="form-control input-lg" placeholder="S" value="yes" tabindex="3">Sunday afternoon <br>
</div>
<div class="form-group">
<input type="checkbox" name="Sundayafternoon" id="Sataft" class="form-control input-lg" placeholder="S" value="yes" tabindex="4">Sunday Morning <br>
</div>
<div class="form-group">
<input type="checkbox" name="weekday" id="email" class="form-control input-lg" placeholder="S" value="yes" tabindex="5">weekday <br>
</div>
<div class="row">
<div class="col-xs-6 col-md-6"><input type="submit" name="submit" value="Register" class="btn btn-primary btn-block btn-lg" tabindex="6"></div>
</div>
</form>
</div>
</div>
</div>
</body>
</html>
When I run my code all it works no errors but I when I check the table all I get is blank rows. The code adds a new sets of rows just doesn't add the data to them. I am trying to add either Yes, or to keep it blank if they do not select it. Any help would be great thanks.
As pointed out by Fred -ii-, you've not bound anything to your statement. Here's you code using a prepared statement. I've also commented the code as well to explain my position
if(isset($_POST['submit'])){
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "jesuitschedule";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// You have a sql statement, but attempting to insert non-existant values. So you'll either
// wind up with an error, those values given in the statement inserted into the table,
// or just empty values.
//$sql = 'INSERT INTO schedule (Saturdaymorning, Saturdayafternoon, Sundaymorning, Sundayafternoon, weekday) VALUES (:Saturdaymorning, :Saturdayafternoon, :Sundaymorning, :Sundayafternoon, :weekday)';
// Create a prepared statement, let's you easily bind parameters
$stmt = $con->prepare(
'INSERT INTO schedule (
Saturdaymorning, Saturdayafternoon, Sundaymorning, Sundayafternoon, weekday
) VALUES (
:Saturdaymorning, :Saturdayafternoon, :Sundaymorning, :Sundayafternoon, :weekday
)';
);
// use exec() because no results are returned
//$conn->exec($sql); // You're executing a statement with no bound parameters
// You can use bindParam, but I find this method a tad easier
// Take the stmt created above, and bind the values to the parameters given
// in the statement, BUT, also execute. :)
$stmt->execute(array(
':Saturdaymorning' => 'value',
':Saturdayafternoon' => 'value',
':Sundaymorning' => 'value',
':Sundayafternoon' => 'value',
':weekday' => 'value'
));
echo "New record created successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
}
If you'd like more info on this, take a look at the PDO page from the PHP site, which is where I pulled your fix: PHP: PDO - Manual

Categories