PHP Insert Command not working - php

Hi guys can you please tell me if there is an error on this code. this is not working. it didn't add any on my database. thanks you!
$con = mysql_connect("localhost","root","pass");
if (!$con){
die("Can not connect: " . mysql_error());
}
mysql_select_db("mytable",$con);
if(isset($_POST['add'])){
// Variables
$acc_class = $_POST['acc_class'];
$AddQuery = "INSERT INTO mytable ('acc_class') VALUES ('$acc_class')";
mysql_query($AddQuery, $con);
echo "Record Successfully Added!!";
};
mysql_close($con);
?>
<form action="add.php" method="post">
Account Classification:
<input required="required" placeholder="e.g Hotel, Restaurant" type="text" name='acc_class' size=15 />
<input type="submit" name='add' Value=' Add Record '/>
</form>

The column name(s) should be wrapped in backticks and not quotes
$AddQuery = "INSERT INTO mytable (`acc_class`) VALUES ('$acc_class')";
or remove the quotes
$AddQuery = "INSERT INTO mytable (acc_class) VALUES ('$acc_class')";
I suggest you move to mysqli_* functions with prepared statements or PDO.
and that you change $acc_class = $_POST['acc_class']; to
$acc_class = mysql_real_escape_string($_POST['acc_class']);
for the time being.
mysql_* functions are deprecated and will be removed from future PHP releases.

At a minimum:
$acc_class = $_POST['acc_class'];
$AddQuery = "INSERT INTO mytable ('acc_class') VALUES ('$acc_class')";
Should be:
$acc_class = $_POST['acc_class'];
$AddQuery = "INSERT INTO mytable ('acc_class') VALUES ('".$acc_class."')";
Also, it is unsafe to pass raw user input into to a SQL query in this way. Please read up on SQL Injection.

Related

Insert a value into database based on Session's User ID

Attempting to insert a Score based on the User's Session ID and POST , I've set up the database to use the UserID as a foreign key constraint but dont know how to do an insert query.
enter image description here
Database Values ^^
My attempt below
<?php
include("php/functions.php");
include('connections/conn.php');
$userID = $_SESSION["userID"];
//echo "all good here";
$newsoanxscore = mysqli_real_escape_string($conn, $_POST['socanxscore']);
$insertquery = "INSERT INTO socanxscore(socialanxietyscore)" . "VALUES('$newsoanxscore')";
$result = mysqli_query($conn, $insertquery) or die(mysqli_error($conn));
mysqli_close($conn);
?>
My insert form
<form action="insertsoanxietyscore.php" method="post">
Insert your score <input type="number" name="socanxscore" /><br><br>
<input type="submit" />
</form>
There are a few things here that may be helpful.
Firstly, you are not passing the user ID into your insert query. which can be written in this case as.
$insertquery = "INSERT INTO socanxscore(socialanxietyscore, UserId) VALUES('$newsoanxscore', '$userID')";
Secondly, please take the time to explore prepared queries to prevent SQL injection when passing end-user input to a database table. You may find the following resource useful.
http://php.net/manual/en/mysqli.prepare.php
go for this:
<?php
session_start();
include("php/functions.php");
include('connections/conn.php');
$userID = $_SESSION["userID"];
if(isset($_POST["socanxscore"]))
{
$query=INSERT INTO socanxscore(socialanxietyscore) VALUES('$newsoanxscore') WHERE userID=$userID";
$result = mysqli_query($conn, $insertquery) or die(mysqli_error($conn));
}
else
{
ehco "error";
}
mysqli_close($conn);
?>

SQL Near error for inserting data through HTML form

I've been trying to insert some data into my database for an events page. I have an html form and a seperate script, as seen below and the submit seems to go through for the ename id and imgsrc values but nothing past that. Anything more and I get a 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 'when, descr, positions) VALUES (test, 1 ,www.vzdc.org,2017-1-20 23:59:00' at line 1I've done some reasearch but maybe it's just a weird error on my end? I'm fairly new to mysql and I would love some help! Thanks, code below.
<!-- HTML form -->
<form id="newevent" action="insertevent.php" method="post">
<p>Event Name:</p><input name="ename" type="text" width="100">
<p>ID:</p><input name="id" type="text" size="5">
<p>Banner Link:</p><input name="imgsrc" type="text" size="50">
<p>Description</p><input name="descr" type="text" height="1000px" >
<p>Date / Time (yyyy-mm-dd HH:MM:SS):</p><input name="when" type="text">
<p>Positions (ONE per line)</p><textarea name="positions" form="newevent" rows="10" cols="50"></textarea><br>
<input value="Add Event" type="submit">
</form>
/* PHP script on insertevent.php */
<?php
$link = mysqli_connect("localhost", "root", "xxx", "xxx");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Escape user inputs for security
$ename = mysqli_real_escape_string($link, $_POST['ename']);
$id = mysqli_real_escape_string($link, $_POST['id']);
$imgsrc = mysqli_real_escape_string($link, $_POST['imgsrc']);
$when = mysqli_real_escape_string($link, $_POST['when']);
$descr = mysqli_real_escape_string($link, $_POST['descr']);
$positions = mysqli_real_escape_string($link, $_POST['positions']);
// attempt insert query execution
$sql = "INSERT INTO events (ename, id, imgsrc, when, descr, positions) VALUES (`$ename`, $id , `$imgsrc`, `$when`, `$descr`, `$positions`)";
if(mysqli_query($link, $sql)){
echo "Records added successfully.";
} else{
echo "ERROR: Could not execute $sql. " . mysqli_error($link);
}
// close connection
mysqli_close($link);
?>
Don't use back-ticks for binding variables to your query, use single ticks instead. You can use back-ticks for the table and column name:
INSERT INTO `events` (`ename`, `id`, `imgsrc`, `when`, `descr`, `positions`)
VALUES ('$ename', '$id', '$imgsrc', '$when', '$descr', '$positions')
WHEN is also a reserved word, so better change its name.
And since you're using mysqli_* API already, check prepared statement
You are using an SQL reserved word as a column name.
$sql = "INSERT INTO events (ename, id, imgsrc, when, descr, positions) VALUES (`$ename`, $id , `$imgsrc`, `$when`, `$descr`, `$positions`)";
You really shouldn't, but if you want to get away with this, surround your table/column names with back ticks ```, like this:
$sql = "INSERT INTO `events` (`ename`, `id`, `imgsrc`, `when`, `descr`, `positions`) VALUES ('$ename', '$id' , '$imgsrc', '$when', '$descr', '$positions')";
I've removed the back ticks you put around your values because, well, they shouldn't be there.
Please learn and use MySQLi prepared statements. They'll help.

Post will not insert into MySQL Database

I've been searching around for like 15 minutes and could not find anything that would fix this. Sorry if I just used wrong keywords or something it has been answered. Also to state this is not something that needs to be extremely secure, as anybody can view this.
So my PHP Post will not insert into MySQL Database.
Form:
<form method="post" action="./thankyou.php">
<h2>Please sign in</h2>
<input type="user"name="user" placeholder="Username">
<input type="textarea" class="" name="feedback" placeholder="Feedback for us."><br />
<button class="" type="submit" name="submitted">Submit Feedback</button>
</form>
Thank you: (Yes I replaced xxx with info)
<?php
$conn = mysql_connect('xxx', 'xxxx', 'xxxx');
if (!$conn) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("xxx") or die(mysql_error());
$user = $_POST['user'];
$fdb = $_POST['feedback'];
$insert = "INSERT INTO contact WHERE (user, feedback) VALUES ('".$user."', '".$fdb."')";
mysql_query($insert);
if(!$insert)
{
die('Could not enter data: ' . mysql_error());
}
echo $insert;
?>
Echo outputs correctly:
INSERT INTO contact WHERE (user, feedback) VALUES ('thisisauser', 'thisisfeedback')
I'm not sure what to do.
An insert does not, by definition, have a where clause.
Change your query as follows:
INSERT INTO contact (user, feedback) VALUES ('thisisauser', 'thisisfeedback')
OR, you can use this structure:
INSERT INTO contact SET user = 'thisisauser' , feedback = 'thisisfeedback'
Finally, this is bad for security. Use a different database API
You dont need to provide WHERE in insert its not correct
it should be
$insert = "INSERT INTO contact (user, feedback) VALUES ('".$user."', '".$fdb."')";
You had as
$insert = "INSERT INTO contact WHERE (user, feedback) VALUES ('".$user."', '".$fdb."')";
^.........here is the issue
The main issues are the SQL query and the way of you check the correct execution of the query
<?php
$conn = mysql_connect('xxx', 'xxxx', 'xxxx');
if (!$conn) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("xxx") or die(mysql_error());
$user = $_POST['user'];
$fdb = $_POST['feedback'];
$insert = "INSERT INTO contact (user, feedback) VALUES ('".$user."', '".$fdb."')";
$retval = mysql_query($insert, $conn);
if(!$retval) { //<---- You must check the result of the execution
die('Could not enter data: ' . mysql_error());
}
echo "Entered data successfully\n";

PHP MySQL Insert Form not working

I have a MySQL database named "culvers" with a user_id INT(4) auto incrementing, a full_name varchar(20) and a user_name varchar(20). I am trying to use this HTML form to add values to the table, but it is not working. I have explored dozens of tutorials and help sites, and it still isn't working. I even put the code on another hosting provider to see if that was the problem. When I click "add" I am taken to a blank page (which is expected, since I don't have a success/error message) but the form data does not insert into the database table.
Also, I know I should sanitize my inputs, but that's not the issue right now. (At least I don't think so)
Here's the form.html code:
<html>
<head>
<title>Add User to Table</title>
</head>
<body>
<h1>Add User</h1>
<form action="adduser.php" method="POST">
<label>Full name:</label>
<input id="postname" type="text" name="fullname">
<label>Username:</label>
<input id="postuser" type="text" name="username">
<input type="submit" name="submit" value="Add">
</form>
</body>
</html>
And here's the adduser.php code:
<?php
if(isset($_POST['submit'])){
$connection = mysql_connect("localhost", "xxxx", "xxxxxxxxxx");
mysql_select_db("culvers");
$fullnameOfUser = $_POST['fullname'];
$usernameOfUser = $_POST['username'];
$sql = "INSERT INTO users (full_name, user_name) VALUES ('$fullnameOfUser', '$usernameOfUser');
$result = mysql_query($sql, $connection);
mysql_close($connection);
}else{
echo "Error no form data";
}
?>
Thank you very much for your help!
you have error in this line :
$sql = "INSERT INTO users (full_name, user_name) VALUES ('$fullnameOfUser', '$usernameOfUser');
you did not have ending "
this line should be :
$sql = "INSERT INTO users (full_name, user_name) VALUES ('$fullnameOfUser', '$usernameOfUser')";
You should use mysqli_* or PDO since all functions of mysql_* are deprecated.
You miss the double Quotes at the end of SELECT Query
$sql = "INSERT INTO users (full_name, user_name) VALUES ('$fullnameOfUser', '$usernameOfUser')";
First if it is not a typo the you need to add a double quote to query.
$sql = "INSERT INTO users (full_name, user_name) VALUES ('$fullnameOfUser', '$usernameOfUser')";
if still issue remains then print query and run it directly in phpmyadmin to see there is not issue with query.
Note: you are using mysql_* function. Please used PDO or Mysqli as your current code is prone to Sql Injection.
PDO Link: http://php.net/manual/en/book.pdo.php
Before submitting your form data, you need to start the mysql server.
you can start mysql server by the use of xampp software. once you have started your mysql server through xampp software, you can find the mysql server port number also.
the actual format of including the database is,
mysql_connect("localhost:port/database","username","password");
You forgot to close the double quotes !
'$fullnameOfUser', '$usernameOfUser')";
----^ // Add one there
The right code.
$sql = "INSERT INTO `users` (`full_name`, `user_name`) VALUES ('$fullnameOfUser', '$usernameOfUser')";
You need to switch to PreparedStatements seriously as the above code of yours is directly prone to SQL Injection.

Insert into MySQL Table PHP

I am having some trouble making a simple form to insert data into a MySQL table. I keep getting this SQL error:
"Error: 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 'stock ('ItemNumber', 'Stock') VALUES ('#4','3'')' at line 1"
My HTML for the form is:
<form action="database.php" method="post">
Item Number: <input type="text" name="ItemNumber">
Stock: <input type="text" name="Stock">
<input type="submit">
</form>
And the PHP is:
<?php
$con=mysqli_connect("localhost","root","root","inventory");
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "INSERT INTO current stock ('ItemNumber', 'Stock')
VALUES
('$_POST[ItemNumber]','$_POST[Stock]'')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
?>
try this
you should not use quotes of parameter around POST . and you should use them inside POST
$sql = "INSERT INTO `current stock` (ItemNumber, Stock)
VALUES
('".$_POST['ItemNumber']."', '".$_POST['Stock']."' )";
you should escape your variables before you insert them to mysql like that
Note that the example does not call mysqli_real_escape_string. You would only need to use mysqli_real_escape_string if you were embedding the string directly in the query, but I would advise you to never do this. Always use parameters whenever possible.
You have an extra quote and you need ticks around your table name as it contains a space.
INSERT INTO current stock ('ItemNumber', 'Stock')
VALUES
('$_POST[ItemNumber]','$_POST[Stock]'')";
should be:
INSERT INTO `current stock` (`ItemNumber`, `Stock`)
VALUES
('$_POST[ItemNumber]','$_POST[Stock]')";
FYI, you also wide open to SQL injections
?php
$conn=new mysqli("localhost","root","","inventory")
or die("not connected".mysqli_connect_error());
if(isset($_POST['submit']{
$ItemNumber=$_POST['ItemNumber'];
$Stock=$_POST['Stock'];
$sql="insert into current stock(ItemNumber,Stock) values('$ItemNumber','$Stock')";
$query=mysqli_query($conn,$sql);
if($query){
echo"1 row inserted";
}else{
echo mysqli_error($conn);
}
}
?>
Please learn to use parameter binding. You are creating code with security vulnerabilities.
Here's how to do your code in mysqli:
$sql = "INSERT INTO current stock (ItemNumber, Stock) VALUES (?, ?)";
if (!($stmt = mysqli_prepare($con, $sql))) {
die('Error: ' . mysqli_error($con));
}
if (!mysqli_stmt_bind_param($stmt, "ii", $_POST[ItemNumber], $_POST[Stock])) {
die('Error: ' . mysqli_stmt_error($stmt));
}
if (!mysqli_stmt_execute($stmt)) {
die('Error: ' . mysqli_stmt_error($stmt));
}
It's easier to use bound parameters than to get all confused with quotes-within-quotes.
<form action="database.php" method="post">
Item Number: <input type="text" name="ItemNumber">
Stock: <input type="text" name="Stock">
<input type="submit" name="submit">
</form>`

Categories