<?php
$conn= new mysqli("localhost", "my_user", "my_password", "world"); //changed for the sake of this question
$username = $_POST['Username'];
$password = sha1($_POST['Password']);
$email = $_POST['Email'];
$firstname = $_POST['FirstName'];
$lastname = $_POST['LastName'];
$insert = 'INSERT INTO User(FirstName, LastName, Email, Username, Password, Type) VALUES ("'.$firstname.'", "'.$lastname.'", "'.$email.'", "'.$username.'", "'.$password.'", 'User');';
$result = $conn->query($insert);
?>
<form method='post' action='regprocess.php'>
<fieldset class="register">
<h2>Register</h2>
<ul>
<li><label for="FirstName">First Name: </label> <input type="text" name="FirstName" id="FirstName"></li>
<li><label for="LastName">Last Name: </label> <input type="text" name="LastName" id="LastName"></li>
<li><label for="Email">Email: </label><input type="email" name="Email" id="Email"></li>
<li><label for="Username">Username: </label><input type="text" name="Username" id="Username"></li>
<li><label for="Password">Password: </label><input type="password" name="Password" id="Password"></li>
<li><input type="submit" value="Register"></li>
</ul>
</fieldset></form>
The form and the top sql code are in separate files.
Hello everybody, I'm trying to insert into an mysql table, and it won't insert into my table. I'm trying to get it to insert through a registration table. And I'm not quite sure why it's not working. Some insight would be great. If you need me to provide the table I will, but I don't think it's part of the reason it's not working.
It's a good thing you're using mysqli, but you're using it incorrectly and are exposing yourself to a number of very serious SQL injection bugs, the consequences of which could be severe.
This is what you should be doing to actually fix the numerous problems present in your example:
$stmt = $conn->prepare('INSERT INTO User(FirstName, LastName, Email, Username, Password, Type) VALUES (?,?,?,?,?,?)');
$stmt->bind_param($firstname, $lastname, $email, $username, $password, 'User');
$stmt->execute();
$result = $stmt->get_result();
The primary advantage of placeholders is not having to worry about how to properly quote data, it's done for you automatically. It also largely avoids having to use two different kinds of quotes within your statement.
If you do not use placeholders for ANY and ALL data being put into your SQL you may end up in serious trouble. You must be vigilant about this.
Your last parameter value is in single quotes. Replace with double quotes so that it reads ..."'.$password.'", "User");';
I don't know PHP. I will try helping you with MySQL though.
I think there is a problem with quotation marks in the insert query.
Try removing single quotes from your values clause.
As an advice, always use " from the start to the end of the sql query text;
$insert = 'INSERT INTO User(FirstName, LastName, Email, Username, Password, Type) VALUES ("'.$firstname.'", "'.$lastname.'", "'.$email.'", "'.$username.'", "'.$password.'", 'User');';
put it like:
$insert = "INSERT INTO User(`FirstName`, `LastName`, `Email`, `Username`, `Password`, `Type`) VALUES ('$firstname', '$lastname', '$email', '$username', '$password', 'User');";
In your query, you had 'User' and you need to escape the ' as \'
And dont forget to always sanitize your content before adding it to the database
Related
This is my textbox
This is my database table
<label> Guest Name: </label>
<input type="text" class="input-sm form-control" name="guest" id="guest" required>
mysqli_query($conn, "INSERT INTO `reservation` VALUES ('', '$guest')");
enter code here
You shouldnt do that, because of data validation.
You could just make a cut at the comma with something like split and use the comma as the seperator. But thats a very bad idea.
If you would do this, you should also do it in your backend in php, here is an example:
$array = (explode(",",$str));
You can also set a limit for the output in your array, so for first and last name :
$array = (explode(',',$str,2));
In your code it would look like this:
$array = (explode(',',$guest,2));
mysqli_query($conn, "INSERT INTO `reservation` VALUES ('', '$array[0]', $array[1])");
However its a bad idea and i would suggest you just create another field for last name.
<input type="text" class="input-sm form-control" name="firstname" id="firstname" required>
<input type="text" class="input-sm form-control" name="lastname" id="lastname" required>
mysqli_query($conn, "INSERT INTO `reservation` VALUES ('', '$firstname', $lastname)");
If you want to validate your data or there is no comma you will get errors.
//suppose you enter 'Asaduzzaman Arif' in guest name field
$name = explode(" ", $guest);
$firstName = $name[0];
$lastName = $name[1];
mysqli_query($conn, "INSERT INTO `reservation` VALUES ('', '$firstName', '$lastName')");
//although getting data by this type of way is a bad idea
HTML code
<form id="form1" name="addAnnouncement" method="post" action="ownerAddAnnouncement_exec.php" onsubmit="return validateForm()">
<label style="font-size:18px">Title:
<input type="text" name="title" />
</label>
<p>
<label style="margin-left: -36px; font-size:18px;">Description:
<textarea name="description" rows="6" cols="60"></textarea>
</label>
</p>
<label style="font-size:18px">Date & Time: <br>
From
<input type="text" name="from" /> <br>
To <input type="text" name="to" />
</label> <br>
<label style="font-size:18px">Venue
<input type="text" name="venue" />
</label>
<p>
<label>
<input type="submit" name="Submit" value="Submit" />
</label>
</p>
</fieldset>
</form>
PHP code
<?php
$title = $_POST['title'];
$description = $_POST['description'];
$from = $_POST['from'];
$to = $_POST['to'];
$venue = $_POST['venue'];
$link = mysql_connect("localhost","root","") or die();
$db = mysql_select_db("condo") or die("no database found");
$insert_sql="INSERT INTO announcement (title, description, from, to,venue, status)
VALUES('$title', '$description', '$from', '$to','$venue', 'Pending')";
$sql_result=mysql_query($insert_sql) or die("Error in inserting data due to ".mysql_error());
if($sql_result)
echo "Succesfully insert new data. Please log in back";
else
echo "Error in inserting new data";
?>
an error like this ("Error in inserting data due to 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 'from, to, status) VALUES('melvin', 'sdsaadsd', 'wew', 'ewrerw', 'we3', 'Pendi' at line 1" )
is show out when try to insert a data into database.
Anyone please help me fix the code.i have been stuck at here for 1 hour.
Display the field names with in ``.
Convert the insert statement to
$insert_sql="INSERT INTO announcement (`title`, `description`, `from`, `to`,`venue`, `status`)
VALUES('$title', '$description', '$from', '$to','$venue', 'Pending')";
You should escape reserved keywords using backticks. Currently, you are using the following reserved keywords - From and To Try this :-
$insert_sql="INSERT INTO `announcement` (`title`, `description`, `from`, `to`,`venue`, `status`)
VALUES('$title', '$description', '$from', '$to','$venue', 'Pending')";
From is a keyword. And also To. It is not recommended to use them. But if you can't avoid it and still want to use them, add backquote ` like below in your insert query :
INSERT INTO announcement (`title`, `description`, `from`, `to`, `status`)
VALUES('$title', '$description', '$from', '$to', 'Pending')
Hope this helped.
Regarding current error it is about reserved keywords like from as field name, so to avoid it either rename your db column or enclose it in back-quotes like `from`
further you may face other errors as you are ignoring many good practices in your code, for example
Validate user input before inserting into db
remember to escape user input (sql injection)
enclose field names in back-quotes
and many others see http://code.tutsplus.com/tutorials/30-php-best-practices-for-beginners--net-6194
I'm working on a cms for my site and this form is not submitting. I know its a query problem, but I can't figure out whats wrong. Any help? Also, the $db is in my config and I do include it at the top of the page. The problem is its not submitting and all it does it refresh, nothing else. I also want to display there form submissions in a table later, but I don't know how to do that, if anyone can help me with that part that would be great as well.
php:
<?php
if(isset($_POST['submit']))
{
$c_name = $_POST['channel_username'];
$v_link = $_POST['video_link'];
$v_title = $_POST['video_title'];
$v_desc = $_POST['vido_description'];
$v_tags = $_POST['video_tags'];
$m_sources = $_POST['music_sources'];
$s_requests = $_POST['special_requests'];
if(empty($c_name) or empty($v_link) or empty($v_title) or empty($v_title) or empty($v_desc) or empty($v_tags))
{
echo 'You must fill in the first 5 fields.';
}
else
{
$getRank = $db->query("SELECT * FROM users WHERE username = '".$_SESSION['username']."'");
while ($row = $getRank->fetch_assoc())
{
$usename = $row['username'];
$rank = $row['rank'];
}
$db->query("INSERT INTO submitted_forms (username, rank, channel_username, video_link, video_title, video_description, video_tags, music_sources, special_requests) VALUES ('$username', '$rank', '$c_name', '$v_link', '$v_title', '$v_desc', '$v_tags', '$m_sources', '$s_requests')");
echo 'Form submitted successfully.';
}
}
?>
Html:
<form method="POST">
<p>Channel name <input type="text" name="channel_name" required>*</p>
<p>Video Link <input type="text" name="video_link" required>*</p>
<p>Video Title <input type="text" name="video_title" required>*</p>
<p>Video Description <input type="text" name="video_description" required>*</p>
<p>Video Tags <input type="text" name="video_tags" required>*</p>
<p>Music Sources <input type="text" name="music_sources"></p>
<p>Special Requests <input type="text" name="special_requests"></p>
<br></br>
<p><input type="submit" name="submit" value="Submit"></p>
</form>
If the problem is indeed with the query, then it's probably this:
$db->query("INSERT INTO submitted_forms (username, rank, channel_username, video_link, video_title, video_description, video_tags, music_sources, special_requests) VALUES (''.$username.'', ''.$rank.'', ''.$c_name.'', ''.$v_link.'', ''.$v_title.'', ''.$v_desc.'', ''.$v_tags.'', ''.$m_sources.'', ''.$s_requests.'')");
I think instead, you want:
$db->query("INSERT INTO submitted_forms (username, rank, channel_username, video_link, video_title, video_description, video_tags, music_sources, special_requests) VALUES ('$username', '$rank', '$c_name', '$v_link', '$v_title', '$v_desc', '$v_tags', '$m_sources', '$s_requests')");
-- edit --
further to that, although it won't give you an error as-is, you really oughtn't insert fresh POST data in there. At the very least you probably want to use mysqli_real_escape_string on it.
I havent do php for some time, but i dont really see what am I missing.
I am trying to insert some datas from FORM into MYSQL , but it still fail.
This is the file with FORM :
<html>
<head>
<link type="text/css" rel="stylesheet" href="stylesheet.css"/>
<title>registrace</title>
</head>
<body>
<H1> The Best Page! </H1>
<p>
"Please registrate"
<form action="zpracovani.php" method="post">
Name <input type="text" size="20" name="Name" value=""><br>
Surname <input type="text" size="30" name="Surname" value=""><br>
Username <input type="text" size="30" name="username" value=""><br>
Password <input type="text" size="10" name="password" value=""><br>
Retype password <input type="text" size="10" name="password2" value=""><br>
<input type="image" name="button" value="submit" class="button" src="button.jpg">
</form>
</p>
</body>
</html>
As you can see i am sending data to proceed into file "zpracovani.php". I did test if i am connected to mysql server ( It passes ) and also a check if i am connected to the right database ( Also passes with no probs ).
<html>
<?php
echo "Wait please";
$con=mysql_connect ('localhost','root','');
if (!$con)
{
die ( 'Could not connect: ' . mysql_error());
}
mysql_select_db ('registrace') or die("cannot select DB");
echo #mysql_ping() ? 'true' : 'false';
$sql="INSERT INTO 'registrace'(Name, surname, username, password).
VALUES('$_POST[Name]','$_POST[Surname]','$_POST[username]','$_POST[password]')";
$result=mysql_query($sql);
if($result){
echo("<br>Input data is succeed");
}else{
echo("<br>Input data is fail");`
}
mysql_close($con);
?>
</html>
Below is overwiev of mysql table I made.
ID int(11)
Name varchar(20) latin1_swedish_ci
Surname varchar(30) latin1_swedish_ci
username varchar(30) latin1_swedish_ci
password varchar(10) latin1_swedish_ci
However I am connected to the database and to correct table it still is unable to insert anyone into the database. Can anyone look into this and help me out, please?
Thanks in advance!
Either remove the quotes in 'registrace' or use backticks in INSERT INTO 'registrace'
Example:
INSERT INTO `registrace`
Using backticks is better.
Also remove the dot in:
$sql="INSERT INTO 'registrace'(Name, surname, username, password).
It should read as:
$sql="INSERT INTO `registrace` (Name, surname, username, password)
Reformatted:
$sql="INSERT INTO `registrace` (Name, surname, username, password)
VALUES
('{$_POST['Name']}','{$_POST['Surname']}','{$_POST['username']}','{$_POST['password']}')";
Or follow this convention:
$unsafe_variable = $_POST["user-input"]
$safe_variable = mysql_real_escape_string($unsafe_variable);
mysql_query("INSERT INTO table (column) VALUES ('" . $safe_variable . "')");
NOTE: I also noticed that you are using the same name for both your DB and your table.
Make sure that this is in fact the case.
Your DB:
mysql_select_db ('registrace')
and your table?
INSERT INTO `registrace`
Plus, it would be a good idea to increase the values for your VARCHAR's and consider using MySQLi_ and prepared statements or PDO. MySQL_ functions are deprecated.
Do read the following articles:
How can I prevent SQL injection in PHP?
On owasp.org
First: use mysqli
Second: get rid of mysql ping
Third: change:
"......'$_POST[xxx]'......"
into:
"......'{$_POST['xxx']}'....."
Thanks guys it is working now.
By the way the mysql ping was just a check to see if i am well connected as i wrote in my original post :)
Anyway it was very helpful thx
I have a database, and I can't insert values into it. Here's my database and my code.
Can you tell me what my problem is?
The output tell me that my sql syntax is wrong. However, I can add values from phpmadmin without any problems.
When I use code, I fail. And, I couldn't find any proble.
Thank yuy very much.
DATABASE
<?php
$db_username = "root";
$db_password = "pass";
$db = "rmado";
$db_server = "localhost";
$db_handle = mysql_connect($db_server, $db_username, $db_password);
$db_found = mysql_select_db($db, $db_handle);
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$title = $_POST['username'];
$desc = $_POST['password'];
$aaa = $_POST['type'];
$bbb = $_POST['email'];
$query = "insert into users(username, password, type, email) values ($title, $desc, $aaa, $bbb)";
mysql_query($query);
}
?>
<html>
<body>
<div id="login_form">
<form name="login_form" method="post" action="zort.php">
username: <input name="username" type="text" value="">
password: <input name="password" type="text" value="">
type: <input name="type" type="text" value="">
email: <input name="email" type="text" value="">
<input name="addtask" type="submit" value="add task">
</form>
</div>
<!-- end login_form-->
</body>
</html>
Thank you very much.
EDIT:
id: int(5)
title: varchar(30)
desc: varchar(50)
assigner_id: int(5)
assignee_id: int(5)
creation_date: date
due_date: date
status_id: int(5)
category_id: int(5)
and here's my php code:
$query = "insert into tasks (title, desc, assigner_id, assignee_id, creation_date, due_date, status_id, category_id) values ('$title', '$desc', $ass1, $ass2, '$cre', '$due', $stat, $cat)";
Where's wrong in this code? Thank you very much.
Per your original question: all those fields are text in your table. You're not encapsulating your values with quotation marks in your original query for these text fields. That is, the following will work for your example:
$query = "insert into users (username, password, type, email) values " .
"('$title', '$desc', '$aaa', '$bbb')";
This will let MySQL know what strings you want inserted for those fields.
However, there are several issues with what you have on this page. A malicious user could put some MySQL-acceptable strings into these fields and those could cause harm to your database. You need to escape your input strings to prevent malicious content from damaging your database.
Considering using also mysqli or PDO as you are using a deprecated library. See here for some examples.
Also, your fields should not be text fields. They really should be varchars and you should limit their length.
EDIT
Your second query needs to encapsulate desc with backticks because DESC is a reserved MySQL word for descending.