I'm using php and a database to add books to a database.
HTML
<form method="POST" action="addbook.php">
<p>Enter Book title :<input type="text" name="bookname"></p>
<p>Enter Book Author :<input type="text" name="bookauthor"></p>
<p><input type="submit" value="addbook"></p>
</form>
PHP
$bname = $_POST['bookname'];
$bauthor = $_POST['bookauthor'];
$dbcon = mysqli_connect('localhost','root','password','bookstore') or die('asd');
$dbquery = "INSERT INTO books (title,author) VALUES ($bname,$bauthor)";
mysqli_query($dbcon,$dbquery) or die('not queryed');
echo "Your book has been added to your online library";
I'm getting the reply ' not queryed'
try putting single quotes around the values
ie
$dbquery = "INSERT INTO books (title,author) VALUES ('$bname','$bauthor')";
You should be using PDO and prepared statements in order to prevent SQL injection. The resultant PHP would be something like this:
$bname = $_POST['bookname'];
$bauthor = $_POST['bookauthor'];
$dbh = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass); //Fill in these variables with the correct values ('localhost' for host, for example)
$st = $dbh->prepare("INSERT INTO books (title,author) VALUES (?,?)");
$data = array($bname, $bauthor);
$st->execute($data);
You can then add logic to check if the statement executed successfully.
Also, I think you just gave us your root password?
For more information about PDO, see this tutorial.
Check the Column names in the table,whether they match with the one in the query.also check whether they are varchar itself.
I dont find any problem in the query, and also try putting
or die(mysqli_error());
and tell what exactly you can see.
If the type is varchar , you have to use single quotes around the values.
$dbquery = "INSERT INTO books (title,author) VALUES ('$bname','$bauthor')";
Related
So, I'm trying to push a comment to my database (icposts, below), and I'm not getting any results. I can pull and display the comments I directly insert into the database table fine, but when I try to send a comment from the html form, it doesn't seem to work at all.
<?php
$connect=mysqli_connect("localhost","root","");
$database=mysqli_select_db("icposts");
$username=$_POST['poster'];
$title=$_POST['postTitle'];
$body=$_POST['postText'];
$date=$_POST['currentDate'];
$submit=$_POST['submit'];
if($submit)
{
$query=mysql_query("INSERT INTO 'posts'('id', 'username', 'title', 'body', 'date') VALUES ('','$username','$title','$body','$date')");
}
?>
Here's the form's html, for reference:
<form name="input" action="comments.php" method="POST">
Username: <input id = "poster" type="text" name="poster"value="Guest" /><br>
Tite: <input id = "postTitle" type="text" name="postTitle" /><br>
Comment: <br> <textarea id = "postText" name = "postText"rows="4" cols="50"></textarea>
<input id = "submit" name = "submit" type="submit" value="Submit" />
<input id = "currentDate" name = "currentDate" type = "hidden" value = "" />
</form>
I've been looking at various examples, and I don't see anything wrong with what I've got there, when I compare it to what other people have posted online.
First, you need to pass connection to $database=mysqli_select_db("icposts");.
Then you're starting to mix MySQL APIs with mysql_query. They just don't intermix.
$database=mysqli_select_db($connect,"icposts");
then you're using the wrong identifiers for your table and columns, being quotes.
Either use ticks, or remove them (quotes) and also pass connection to the query:
$query=mysqli_query($connect,"INSERT INTO `posts` (`id`, `username`, `title`, `body`, `date`)
VALUES ('','$username','$title','$body','$date')");
Also add or die(mysqli_error($connection)) to mysqli_query() to check for DB errors, which is the reason why you are not getting errors; you're not checking for them. Error reporting is another you should look into.
Example:
if (!mysqli_query($connection,"INSERT INTO `posts` (`id`, `username`, `title`, `body`, `date`)
VALUES ('','$username','$title','$body','$date')");
)
{
echo("Error description: " . mysqli_error($connection));
}
else{
echo "Success!";
}
You can also use all 4 parameters instead:
$connect=mysqli_connect("localhost", "root", "", "icposts");
You may also want to replace if($submit) with
if(isset($_POST['submit']))
You can then get rid of $submit=$_POST['submit'];. It's best to use isset().
Nota: You will need to make sure that your currentDate column allows for blank data, otherwise you will need to give it some form of value.
Another note about the "id" column. If it is an auto_increment, you can just omit it from the query.
The database will increase on its own.
Sidenote:
Your present code is open to SQL injection. Use prepared statements, or PDO with prepared statements, they're much safer.
In the meantime till you get into using prepared statements, change your code using:
$username = stripslashes($_POST['poster']);
$username = mysqli_real_escape_string($connection, $_POST['poster']);
and do the same for all your variables.
Here is a prepared statements primer:
<?php
$link = new mysqli('localhost', 'root', '', 'database');
if ($link->connect_errno) {
throw new Exception($link->connect_error, $link->connect_errno);
}
// Check that the expected value has been provided via a POST request
if (!isset($_POST['input1'])) {
throw new Exception('Missing POST request parameter [input1]');
}
// now prepare an INSERT statement
if (!$stmt = $link->prepare('INSERT INTO `your_table` (`name`) VALUES (?)')) {
throw new Exception($link->error, $link->errno);
}
// bind parameters
$stmt->bind_param('s', $_POST['input1']);
if (!$stmt->execute()) {
throw new Exception($stmt->error, $stmt->errno);
}
$connect=mysqli_connect("localhost","root","");
Should be (the select db can simply be removed)
$connect=mysqli_connect("localhost","root","", "icposts");
And
$query=mysql_query("INSERT INTO 'posts'('id', 'username', 'title', 'body', 'date') VALUES ('','$username','$title','$body','$date')");
Should be
$query=mysqli_query("INSERT INTO 'posts'('id', 'username', 'title', 'body', 'date') VALUES ('','$username','$title','$body','$date')", $database);
Please do keep in mind that this is a really bad aprouch, also looking at your query it seems like the id is an auto incremented column. If that's the case, you don't even have to write it in the query itself.
You might wanna look further into Parameterizing queries.
This is a nice post for that.
How can I prevent SQL injection in PHP?
I've seen so many tutorials with so many different ways to insert using PDO. None of them seem to work for me. Can't seem to get mine to send to the database. I have no issue connecting and retreiving the data using FETCH but can't seem to post this data.
Any help with getting my post to work and redirect using the header or meta refresh would be nice. I am $_POST from an html form. Connecting to the db works just fine but can't get the data in.
$hostdb = 'myremoteip';
$namedb = 'cpdemo';
$userdb = 'root';
$passdb = 'mypassword';
$conn = new PDO("mysql:host=$hostdb; dbname=$namedb", $userdb, $passdb);
if(isset($_POST['fname'])) {
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$title = $_POST['title'];
$photo = $_POST['photo'];
$stmt = "INSERT INTO row_users (fname,lname,title,photo)
VALUES (:first,:last,:title,:photo)";
$q = $conn->prepare($stmt);
$results = $q->execute(array(
":first"=>$fname,
":last"=>$lname,
":title"=>$title,
":photo"=>$photo
));
echo 'User Added<br/>';
}
header ('Location:../insertUser.html');
exit();
What you have to understand that there is no such thing like "PDO Insert Into DB"
There is INSERT query, irrelevant to PDO but regular to database you are using.
And there is PDO prepared statement, irrelevant to query type. You have to follow exactly the same pattern, no matter if it insert or delete.
So - all you need is just a tutorial on PDO prepared statements. That's all. Preferably one that teach you to enable error reporting in the first place.
As requested by OP, comment leading to an answer (to close the question and marked as solved).
I tested your code "as is", and it worked fine.
The only thing I can tell that could be the issue is, that your insert won't happen unless it meets the conditional statement you've set if(isset($_POST['fname']))
Check to see if your HTML form's elements are indeed named?
I.e. <input type="text" name="fname"> etc. If one of those are not not named or has a typo, then your whole query will fail.
You can try binding parameter before passing it to execute, like for example in the below code
<?php
$stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (:name, :value)");
$stmt->bindParam(':name', $name);
$stmt->bindParam(':value', $value);
// insert one row
$name = 'one';
$value = 1;
$stmt->execute();
// insert another row with different values
$name = 'two';
$value = 2;
$stmt->execute();
?>
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
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.
The problem is I simply want to insert the fullname/address. I created a users table with the following columns: id (primary), fullname (unique), address (unique).
Here's the code:
<?php $username = "root";
$password = "artislife23";
$hostname = "localhost";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
//select a database to work with
$selected = mysql_select_db("test",$dbhandle)
or die("Could not select examples");?>
<body>
<div class="container">
<div class="content">
<h1><?php if(($selected!=null)){
echo "Database is on lock.";}
if(($dbhandle!=null)){
echo "Connected to MySQL<br>";
}?></h1>
<form method="post" action="input.php">
<tr><td>Name</td><td><input type="text" name="fullname" size="20"></td></tr>
<tr><td>Address</td><td><input type="text" name="address" size="40"></td></tr>
<tr><td></td><td align="right"><input type="submit" value="Submit"></td>
Here's input.php
<?php
$postr="INSERT INTO users
(fullname, address) VALUES('$_POST[fullname]','$_POST[address]')";
$result = mysql_query($postr);
echo "$result";?>
All that I can see that's happening is a single blank entry was inserted into the table. Am I doing something wrong here? All I want is to successfully insert the form data into my users table here.
$_POST['fullname']
you are missing quotes in your POSTs.
The reason why it doesn't work is that PHP doesn't expand arrays in strings the same way it does variables without some weird syntax I can never remember. Change:
$postr="INSERT INTO users (fullname, address) VALUES('$_POST[fullname]','$_POST[address]')";
To:
$postr="INSERT INTO users (fullname, address) VALUES('".$_POST['fullname']."','".$_POST['address']."')";
You were also missing the quotes on the array keys.
Additional notes:
Your code is wide open to SQL injection, if I entered my name as Bobby'; DROP TABLE users;-- guess what would happen?
mysql_*() functions are deprecated, take the time to learn PDO or MySQLi. They have neat thigns called 'parameterized queries' that allow you to easily avoid SQL injection like I've noted above.
Assuming that either a person's full name or address to be unique to them is a design mistake, don't do this in a 'real-world' project.
Edit
Alternate syntax for embedding arrays in strings:
$string = "Fee fie {$foo['bar']}.";