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.
Related
I want import a data (from a form) in my database but i've this error :
Parse error: syntax error, unexpected ';' in /homepages/38/htdocs/index2.php on line 7
and the script is
<?php
//Connecting to sql db.
$connect = mysqli_connect("","","","");
//Sending form data to sql db.
mysqli_query($connect,"INSERT INTO posts (email, pseudo)
VALUES ('$_POST[email]', '$_POST[pseudo]')";
?>
What is the error ?
Thank you
Solution
You have not concatenated the $_POST[] variable correctly.
You have been missing the close brace for the mysqli_query opening.
It is advised to have a separate query and then to execute the mysqli_query().
Necessary Checks:
Ensure that you have given the name for the input type in the form attributes.
Have a check that whether you have called the name what you have given in the form at the PHP code while insert.
(E.g) - Input Attribute needs to be like this
<input type="email" name="email" value="" />
Like this you have to provide for all the Input types.
PHP Code
Usage of the mysqli::real_escape_string is better if you use it avoids SQL Injection.
<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// escape variables for security
$email=mysqli_real_escape_string($con,$_POST['email']);
$pseudo=mysqli_real_escape_string($con,$_POST['pseudo']);
$stmt = "INSERT INTO posts (`email`, `pseudo`)VALUES('".$email."','".$pseudo."')";
$query = mysqli_query($con,$stmt);
if($query)
{
echo "Inserted Successfully";
}
else
{
// Handle Error over here.
}
?>
$email=$_POST['email'];
$pseudo=$_POST['pseudo'];
mysqli_query($connect,"INSERT INTO `posts` (`email`, `pseudo`) VALUES ('$email', '$pseudo');");
You have missed quote inside POST .Check below code
<?php
//Connecting to sql db.
$connect = mysqli_connect("","","","");
$sql ="INSERT INTO posts (email, pseudo)VALUES('".$_POST['email']."','".$_POST['pseudo']."')";
//Sending form data to sql db.
mysqli_query($connect,$sql);
?>
I am creating a users database where there are 4 fields: ID, username, password, and occupation. This is a test database. I tried querying the db table and it worked but i have a lot of trouble having a user input and a MySQL query based off of it. I run an Apache server in Linux (Debian, Ubuntu).
I have 2 pages. The first one is a bare-bone test index page. this is where there are textboxes for people to input easy info to register their info in the db. Here is the code for it:
<html>
<form action="reg.php" method="POST">
Username:
<input type="text" name="u">Password:
<input type="password" name="p">Occupation:
<input type="text" name="o">
<input type="submit" value="register">
</form>
</html>
After the submit button is clicked. It goes to the reg.php file. This is where it gets complicated. The page goes blank!!! Nothing is displayed or inputted in the db. Normal queries work well, but when user interaction is added, something is wrong. Here is the code for reg.php:
<?php
$un = $_POST["u"]
$pk = $_POST["p"]
$ok = $_POST["o"]
$u = mysql_real_escape_string($un);
$p = mysql_real_escape_string($pk);
$o = mysql_real_escape_string($ok);
$link = mysql_connect('localhost', 'root', 'randompassword');
if (!$link){
die(' Oops. We Have A Problem Here: ' . mysql_error());
}
if ($link){
echo 'connected succesfully';
}
mysql_select_db("forum") or die(' Oops. We Have A Problem Here: ' . mysql_error());
$data = mysql_query("INSERT INTO users (username, password, occupation) VALUES ('{$u}', '{$p}', '{$o}')");
?>
Can anyone hep me to correct this code to make this work?
Thank you so much for your time. Much appreciated.
EDIT:
I noticed that i did not add semicolons in the first 3 lines. after doing so i got this 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 '{'', '', '')' at line 1." Can someone explain why?
EDIT: the website is just on my local machine...
on an apache server on linux
You are missing semi-colons in the first three lines.
$un = $_POST["u"];
$pk = $_POST["p"];
$ok = $_POST["o"];
mysql_real_escape_string() requires a db connection.
Try this ....
<?php
$un = $_POST["u"];
$pk = $_POST["p"];
$ok = $_POST["o"];
$link = mysql_connect('localhost', 'root', 'randompassword');
if (!$link){
die(' Oops. We Have A Problem Here: ' . mysql_error());
}
if ($link){
echo 'connected succesfully';
}
mysql_select_db("forum") or die(' Oops. We Have A Problem Here: ' . mysql_error());
$u = mysql_real_escape_string($un);
$p = mysql_real_escape_string($pk);
$o = mysql_real_escape_string($ok);
$sql = "INSERT INTO users (username, password, occupation) VALUES ('$u', '$p', '$o')";
$ins_sql = mysql_query($sql);
IF($ins_sql) {
echo 'Inserted new record.';
}ELSE{
echo 'Insert Failed.';
}
?>
Try adding this to the top of your script:
error_reporting(E_ALL);
ini_set("display_errors", 1);
This way you will see all errors that you made syntactically or even within your SQL.
Basically i've been scratching my head at this and I still can't figure out why it's not inserting.
I'm 100% sure the database is connected as it's fetching information just fine, however the following code fails to insert anything into the database. I've checked for spelling mistakes, i've checked from deprecated php code etc, and have used mysqli and mysql.
<?php
include_once "settings.php";
if (isset($_POST['sendMessage']) && isset($_POST['messageTo']) && isset($_POST['messageBody'])){
$messageTo = mysql_real_escape_string($_POST['messageTo']);
$messageBody = mysql_real_escape_string($_POST['messageBody']);
$query= "INSERT INTO inbox (`msgTo`, `msgFrom`, `msgBody`)
VALUES('$messageTo', '$username', '$messageBody')";
if(mysql_query($query))
echo "done.";
else
echo "Problem with Query";
}
?>
<form method="POST">
<div class="searchContain">
<input name="textfield" type="text" name="messageTo" class="input search"><br />
<textarea placeholder="Your message..." name="messageBody" class="input sendmsg" ></textarea><br />
<button class="input" name="sendMessage">Send Message</button>
</div>
</form>
Settings.php:
<?php
session_start();
include_once "../more/config/connect.php";
// Settings //
function logincheck(){
if (!isset($_SESSION['username'])){
header("location: ../index.php");
}
}
logincheck();
$username=$_SESSION['username'];
$gatherInfo=mysql_query("SELECT * FROM users WHERE username='$username' LIMIT 1");
$fetch=mysql_fetch_object($gatherInfo);
?>
connect.php:
<?php
// Connect to the server //
date_default_timezone_set('Europe/London');
mysql_connect("localhost", "root", "connected") or die (mysql_error ());
mysql_select_db("ts") or die(mysql_error());
?>
If anyone could help me fix this rather basic rookie error I'd be very grateful!
UPDATE:
Basically after changing the code. I've gone through the MAMP panel and changed the errors so they display. It's giving me the following error message:
Warning: mysql_connect(): Can't connect to local MySQL server through socket '/Applications/MAMP/tmp/mysql/mysql.sock' (2)
in I've never come across this error before, any ideas? It seems to fetch data from the database just fine, so I'm not sure why.
try changing your query to
$query= "INSERT INTO `inbox` (`msgTo`, `msgFrom`, `msgBody`)
VALUES('$messageTo', '$username', '$messageBody')";
you can try the following
if (isset($_POST['sendMessage']) && isset($_POST['messageTo']) && isset$_POST['messageBody'])){
$messageTo = mysql_real_escape_string($_POST['messageTo']);
$messageBody = mysql_real_escape_string($_POST['messageBody']);
$query= "INSERT INTO inbox ('msgTo', 'msgFrom', 'msgBody')
VALUES('$messageTo', '$username', '$messageBody')";
if(mysql_query($query))
echo "done.";
else
echo "Problem with Query";
}
Column names should be in single inverted commas
You should check for the mysql_query to give success response.
do not call the same function again and again i.e mysql_real_escape_string was called 2 times for the same thing. Alternatively assign that to a variable, although you need not have escaped the values to check in if condition
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
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')";