<form> and $_POST with sql in php [closed] - php

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have this form list:
<form action="">
Inlognaam: <input type="text" name="inlognaam">
</form>
Now i want it that if you put there text in, the text will set into the database.
// Create connection
$con=mysqli_connect("localhost","root","","phpexpr");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$inlognaam = $_POST['inlognaam'];
if(isset($POST['inlognaam'])){
$filename = $_POST['inlognaam'];
}
if(isset($filename)){
echo $filename;
}
$sql = 'INSERT INTO gebruikers (inlognaam) VALUES('.$filename.')';
mysql_query($sql);
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con);
?>
I got this code, but i don't know what there is wrong and what schould be changed.
Can somebody help me please? :)

There are several flaws with your code:
you don't specify a method, so your form will be sent with GET, whereas you use $_POST variables in your PHP code. Use
<form action="" method="POST">
you are mixing mysql_* functions and mysqli_* functions. Don't use the former anymore, those are deprecated. Use either MySQLi or PDO (I prefer the latter). If you can't decide which, this article will help you. If you pick PDO, here is a good tutorial.
you're performing two queries here (resulting in two INSERTs):
mysql_query($sql);
if (!mysql_query($sql,$con))
just catch the value of the first query (and use mysqli_query if you want to use MySQLi).
last but not least, due to your string concatanation of your query, you're open to SQL injection. Switch to prepared statements like this:
$sql = 'INSERT INTO gebruikers (inlognaam) VALUES (?)';
$stmt = $con->prepare($sql);
$stmt->bind_param('s', $filename);
$success = $_stmt->execute();
if ($success) {
…

Use the method name POST at the line <form action="" method="post">
and one thing you have mistake that use $_POST NOT $POST in the line
if(isset($POST['inlognaam'])){
$filename = $_POST['inlognaam'];
}

Here,
When you dont specify method attributes of form tag, then default it will use GET method to post data.
So set or use $_REQUEST to get data from html file which independant of form method.

The form maybe like this <form action="" method="POST">
try it

Can you give us an error if you're getting one? I see that you're using a MySQLI connection but you're putting everything in the database with just a MySQL query.
You need this code:
<form action="" method="POST">
<?php
// Create connection
$con = mysqli_connect("localhost","root","","phpexpr");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQLI: " . mysqli_connect_error();
}
$inlognaam = trim($_POST['inlognaam']);
if(isset($_POST['inlognaam']))
{
$filename = trim($_POST['inlognaam']);
}
if(isset($filename))
{
echo $filename;
}
$sql = 'INSERT INTO gebruikers (inlognaam) VALUES('.$con->real_escape_string($filename).')';
$con->query($sql);
if (!mysqli_query($sql,$con))
{
die('Error: ' . mysqli_error());
}
echo "1 record added";
mysqli_close($con);
?>
I've used OO side of MySQLI because I'm not used to produceral side of MySQLI, apoliges for that and the bad English from my side.
I also see that you didn't declared the action in your form, you need to use POST if you wont that user can post informatie that you can send to your DB.

Related

adding new mySQL table row with PHP doesn't work

I got a little form:
<form id="plannerform" action="save.php" method="post">
<input id="plannername" placeholder=" " type="text" autocomplete="off" name="plannername">
<input id="plannersubmit" type="submit" value="eintragen">
</form>
As you can see there is the action="save.php" and method="post" on the text-input there is name="plannername".
And thats my php:
$con = mysql_connect("myHost","myUser","myPW");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("myDB", $con);
$sql="INSERT INTO anmeldungen (FR_PM)
VALUES ('$_POST[plannername]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
The FR_PM is one column of my table. But when I press submit, not even a new row gets created. Nothing happens.
But when I call my php with "mywebsite.com/save.php" it adds a new row in my table (with no value at "FR_PM", what's pretty obvious)
What do I do wrong?
one of the things that you need to learn if you are a beginner, you should try by all means to stay away from using mysql_* function this is depreciated and its no longer supported in php. instead use mysqli_* with prepared statements, or use PDO prepared statements.
prepared statments make you code looks clean and its easy to debug.
this is you example with prepared statements.
<form id="plannerform" action="save.php" method="post">
<input id="plannername" placeholder=" " type="text" autocomplete="off" name="plannername">
<input id="plannersubmit" type="submit" value="eintragen" name="submit">
</form>
save.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if (isset($_POST['submit'])) {
if (empty($_POST['plannername'])) {
die("Enter plannername");
} else {
// prepare and bind
$stmt = $conn->prepare("INSERT INTO anmeldungen (FR_PM) VALUES (?)");
$stmt->bind_param("s", $_POST['plannername']);
if ($stmt->execute()) {
echo "New records created successfully";
} else {
echo "Could not insert record";
}
$stmt->close();
}
}
?>
The reason I used prepared statements :
Prepared statements reduces parsing time as the preparation on the
query is done only once (although the statement is executed multiple
times)
Bound parameters minimize bandwidth to the server as you need send
only the parameters each time, and not the whole query
Prepared statements are very useful against SQL injections, because
parameter values, which are transmitted later using a different
protocol, need not be correctly escaped. If the original statement
template is not derived from external input, SQL injection cannot
occur.
But when I call my php with "mywebsite.com/save.php" it adds a new row
in my table (with no value at "FR_PM", what's pretty obvious)
What do I do wrong?
Well do prevent that from happening you need to check if the form was submitted before you can actual process any thing.
Note: If we want to insert any data from external sources (like user input from a form ), it is very important that the data is sanitized
and validated. always treat input from a form as if its from a very
dangerous hacker
change your insert query:
$sql="INSERT INTO anmeldungen (FR_PM) VALUES ('".$_POST["plannername"]."')";
Or
$plannername = $_POST["plannername"];
$sql="INSERT INTO anmeldungen (FR_PM) VALUES ('".$plannername."')";
Also, use "name"= and not "id"= in the HTML form.
This is usually misleading when working with forms and HTTP POST method.
you may try
$value = $_POST['plannername'];
$sql="INSERT INTO anmeldungen (FR_PM) VALUES ('{$value}')";

MYSQL loop update row value separately [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
i have the following php:
<?php
$connection=mysqli_connect("host","user","pass","db");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($connection,"SELECT ID FROM tbname");
while($row = mysqli_fetch_array($result))
{
mysqli_query($connection,"UPDATE tbname SET amount= (amount+ 1) WHERE ID='$row[ID]' ");
}
mysqli_close($connection);
echo 'OK'; ?>
I want to 'corelate' the pressing of a button to update the associated row value from the table but when i use this code i get all my values updated. Can anyone help me ?
This assumes that your ajax request is passing an 'id' parameter. Note that this code is open to SQL injection attacks. I am assuming that you know how to properly sanitize your inputs and parameterize your queries to protect yourself. If you don't, Jay's answer includes some good links that you should check.
<?php
if(!empty($_POST["id"]))
{
$id = $_POST["id"];
$connection=mysqli_connect("host","user","pass","db");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit;
}
mysqli_query($connection,"UPDATE tbname SET amount= (amount+ 1) WHERE ID = '" . $id . "'");
mysqli_close($connection);
echo 'OK';
}
else
{
echo 'NO ID PASSED';
}
?>
You have to properly identify the variable in the array and concatenate the variable in the query:
mysqli_query($connection,"UPDATE tbname SET amount = amount+ 1 WHERE ID='" . $row['ID']. "' ");
you also do not need the parentheses around the calculation in the SET clause.
Since you're selecting all of the rows in your table and then looping through all of the rows and changing the value, which is not what you want, you have to select with a filter:
SELECT ID FROM tbname WHERE *some condition is met*
Once you do that you'll be able to update a subset of your records as you desire.
Since you're using MySQLi you should learn about prepared statements for MySQLi to guard yourself from potential SQL Injection Attacks.
in addition you should employ error checking, such as or die(mysqli_error()) to your connection and queries. If not you'll have to look in your error logs to fish out any problems that you could have with these.

Trying to mysqli_query to INSERT INTO my database. Not receiving errors

I'm trying to make a very basic form that inserts into my database. I've worked through countless hours working on this. I feel I understand each line of code. I can't imagine what the problem is. I'm not receiving any errors, although I haven't set up error checks in my code yet. Hopefully my problem is simple and obvious.
Here is my connect.php file. $con is my connection to a new mysqli. talk is my database.
<?php
$con= new mysqli("localhost","root","","talk");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
Here is the relevant form part of my html. title and content and the two pieces of information I'm trying to insert into my database. I include the connect.php. The textarea should be linked to the form through the form="talkform". This form uses action="process.php", which I'll cover next.
<?php
include 'connect.php';
?>
<center>
<h1>/talk/</h1>
<form method="post" action="process.php" id="talkform">
<input type="text" name="title"/><br><br>
<textarea form="talkform" rows="10" cols="80" name="content"></textarea><br>
<input type="submit" value="talk" />
</form>
And here is my process.php. I included connect.php in this file as well. Not sure if that's redundant and causing problems, but I don't think so. I also used this $_SERVER['REQUEST_METHOD'] bit you see, which I picked up from a tutorial. Not sure if there's a better way of accomplishing that. I put everything into variables. When I was working through errors, it was all on the mysqli_query line. I have the strongest suspicion that's the culprit.
<?php
include 'connect.php';
if($_SERVER['REQUEST_METHOD'] = 'POST')
{
$title = $_POST['title'];
$content = $_POST['content'];
$operation = "INSERT INTO
main(title, content)
VALUES($title, $content);";
$result = mysqli_query($con, $operation);
}
?>
I hope that I didn't leave anything out. I've been struggling with getting a database working for over a week. It's been a painful process, and although I'm learning a lot, I'm not getting anything to work. Please help, and thank you.
use == operator to compare
if($_SERVER['REQUEST_METHOD'] == 'POST')
and quote your query variable
$operation = "INSERT INTO main(title, content) VALUES('$title', '$content');";
so code looks like with escape string
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$title = mysqli_real_escape_string($_POST['title']);
$content = mysqli_real_escape_string($_POST['content']);
$operation = "INSERT INTO main(title, content) VALUES('$title', '$content');";
$result = mysqli_query($con, $operation);
}
Also better to use check for post values exist or not with empty() or isset()
Line 4: if($_SERVER['REQUEST_METHOD'] == 'POST')
Better is check out directly if form was sent using if (isset($_POST['title'])).
When you call mysqli_error() you´ll find our you try to insert strings without quotes (and you don´t escape inputs - look for SQl injection).
$operation = "INSERT INTO main(title, content) VALUES('" . mysqli_real_escape_string($con, $title) . "', '" . mysqli_real_escape_string($con, $content) . "')";
You're not checking for errors after your mysqli_query call, of course you won't see any.
You're vulnerable to SQL injection. Use mysqli's prepared query syntax to avoid that. See How can I prevent SQL injection in PHP?.
Your immediate problem is that your query reads ... VALUES(foobar, baz), which is invalid. You're missing quotes around the values. However, if you properly use prepared statements, that will become a non-issue, so ignore that.

How to insert long Strings into mySQL database using PHP?

I'm using a simple html-form and PHP to insert Strings into mySQL Database, which works fine for short strings, not for long ones indeed.
Using the phpmyadmin I'm able to insert Strings of all lengths, it's only doesn't work with the html file and PHP.
Will appreciate every kind of help, would love to learn more about this topic...
Thank you all a lot in advance and sorry if the question is to simple...
There are two very similar questions, I found so far... unfortunately they couldn't help:
INSERTing very long string in an SQL query - ERROR
How to insert long text in Mysql database ("Text" Datatype) using PHP
Here you can find my html-form:
<html>
<body>
<form name="input" action = "uploadDataANDGetID.php" method="post">
What is your Name? <input type="text" name="Name"><br>
Special about you? <input type="text" name="ThatsMe"><br>
<input type ="submit" value="Und ab die Post!">
</form>
</body>
</html>
and here is the PHP-Script named uploadDataANDGetID.php :
<?php
$name = $_POST["Name"];
$text = $_POST["ThatsMe"];
$con = mysql_connect("localhost", "username", "password") or die("No connection established.");
mysql_select_db("db_name") or die("Database wasn't found");
$q_post = mysql_query("INSERT INTO profiles VALUES (null, '{$name}' ,'{$text}')");
$q_getID =mysql_query("SELECT ID FROM profiles WHERE Name = '{$name}' AND ThatsMe = '{$text}'");
if(!$q_post) // if INSERT wasn't successful...
{
print('[{"ID": "-3"}]');
print("uploadDataAndGetID: Insert wasn't successful...");
print("about ME: ".$text);
}
else // insertion succeeded
{
while ($e=mysql_fetch_assoc($q_getID))
$output[]=$e;
//checking whether SELECTion succeeded too...
$num_results = mysql_num_rows($q_getID);
if($num_results < 1)
{
// no such profile available
print('[{"ID": "-1"}]');
}
else
{
print(json_encode($output));
}
}
mysql_close();
?>
Thank you guys!
Use the newer way to connect to MySQL and use prepared statements http://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php
you MUST escape your strings, with mysql_real_escape_string, like this:
$name = mysql_real_escape_string($_POST['Name']);
$text = mysql_real_escape_string($_POST["ThatsMe"]);
$q_post = mysql_query('INSERT INTO profiles VALUES (null, "' . $name . '" ,"' . $text . '")');
also read about SQL injection

PHP and MySQL posting system

Okay, Here's my problem. I am trying to make a posting script for my website. However this script is not working; the script is below:
<?php
// Make sure the user is logged in before going any further.
if (!isset($_SESSION['user_id'])) {
echo '<p class="login">Please log in to access this page.</p>';
exit();
}
else {
echo('<p class="login">You are logged in as ' . $_SESSION['username'] . '. Log out.</p>');
}
// Connect to the database
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (isset($_POST['submit'])) {
// Grab the profile data from the POST
$post1 = mysqli_real_escape_string($dbc, trim($_POST['post1']));
$query = "INSERT INTO ccp2_posts ('post') VALUES ('$post1')";
$error = false;
mysqli_close($dbc);
?>
<form enctype="multipart/form-data" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<legend>Posting</legend>
<label for="post">POST:</label>
<textarea rows="4" name="post1" id="post" cols="50">Write your post here...</textarea><br />
<input type="submit" value="submit" name="submit" />
</form>
</div>
<?php
include ("include/footer.html");
?>
</body>
</html>
Nothing shows up in the database when I submit the form. Help would be amazing. Thanks.
You haven't executed the query. All you've done is opened a connection, defined the query string and closed the connection.
Add:
if(msyqli_query($dbc, $query)) {
// Successful execution of insert query
} else {
// Log error: mysqli_error($dbc)
}
after this line:
$query = "INSERT INTO ccp2_posts ('post') VALUES ('$post1')";
Update:
Started editing but had to leave... As other answerers have pointed you need to either quote the post column with a backick or remove the single quote that you currently have altogether. The only case where you need to use backticks to escape identifiers that are one of the MySQL Reserved Words.
So the working version of your query would be:
$query = "INSERT INTO ccp2_posts (post) VALUES ('$post1')";
You may have other problems, but your SQL is bad. You can't use single quotes around 'post'. You want backticks or nothing:
INSERT INTO ccp2_posts(post) VALUES ('$post1')
You missed
mysqli_query($dbc,$query);
In your code,
$query = "INSERT INTO ccp2_posts ('post') VALUES ('$post1')";
mysqli_query($dbc,$query);
Your query is not quite right:
$query = "INSERT INTO `ccp2_posts` (`post`) VALUES ('$post1')";
Note that those are backticks `, not single-quotes. This is very important! Backticks are used to name databases, tables and column names, and in particular it means you don't have to remember the extensive list of every single reserved word. You could call your column `12345 once I caught a fish alive!` if you want to!
Anyway, more importantly, you aren't actually running your query!
mysqli_query($dbc,$query);
You are not submiting to the database using, for example, the mysql_query() function.

Categories