Cannot submit a form on php and mysqli_query - php

I have a html form that i want to submit its data into a specific database in wamp using phpmyadmin, the connection is successfully done. However, the data cannot be submitted. I get this message after submitting the data in the form :
Successful connection
( ! ) Warning: mysqli_query() expects parameter 1 to be mysqli, resource given in C:\wamp\www\Ex\insert-data.php on line 11
Call Stack
# Time Memory Function Location
1 0.0005 136600 {main}( ) ..\insert-data.php:0
2 0.0023 144480 mysqli_query ( ) ..\insert-data.php:11
Error inserting new records!
My Code in 'insert-data.php' is:
<?php
if(isset($_POST['submitted'])){
include('connect.php');
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$sqlinsert=
"INSERTINTO`test`(`FName`,`LName`)VALUES('$fname','$lname')";
if(!mysqli_query($dbconn,$sqlinsert)){
die('Error inserting new records!');
}
echo "1 record added to database";
}
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<h1>Insert Data into DB</h1>
</head>
<body>
<form method="post" action="insert-data.php" >
<input type="hidden" name="submitted" value="true" />
<label>First Name</label>
<input type="text" name="fname" />
<label>last Name</label>
<input type="text" name="lname" />
<input type="checkbox" name="check" />
<input type="radio" name="radios" />
<input type="submit" value="submit"></button>
</form>
</body>
</html>
Any idea? ....Thanks

you posted your connection codes in comments (which belongs in your question I might add) being mysql_ based.
You need to use mysqli
those different MySQL APIs do not intermix. You must use the same one from connection to query.
http://php.net/manual/en/function.mysqli-connect.php
Example pulled from the manual:
<?php
//conection:
$link = mysqli_connect("myhost","myuser","mypassw","mybd")
or die("Error " . mysqli_error($link));
and remember to replace $link with $dbconn and your own credentials.
This doesn't help you:
die('Error inserting new records!');
this does:
or die(mysqli_error($dbconn));
Since you seem new to this, use prepared statements right away.
References:
http://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php
http://php.net/pdo.prepared-statements
Your present code is open to SQL injection.
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Displaying errors should only be done in staging, and never production.
Just for argument's sake, put a space between INSERT and INTO:
$sqlinsert= "INSERT INTO `test` (`FName`,`LName`) VALUES ('$fname','$lname')";
You seem to have made a reference to that in comments that they are seperated, but I said it anyway.
Plus, try putting your connection/include on top of your conditional statement.
Connection:
Your connection should be this and replacing the xxx with your own credentials.
$db_host = "xxx";
$db_username = "xxx";
$db_pass = "xxx";
$db_name = "xxx";
$dbconn = mysqli_connect("$db_host","$db_username","$db_pass","$db_name")
or die("Error".mysqli_error($dbconn));
and nothing else. No instances of mysql_ at all.
Sidenote: # symbols are error suppressors. You can add them back in once everything is working.
Closing notes:
Kudos to Liam (Sorsby).

Use separated words like,
INSERT INTO `test` (`FName`,`LName`) VALUES ('$fname','$lname')";

Related

Why I can not upload file to my database?

I need to create a form about companies with couple of information (as you can see down below), but every time I want to upload a new row I get 1's in every column.
So, I want to know what should I do with my code?
<?php
include('mysql.php');
if ($_POST) {
$companyName = isset($_POST['cname']);
$address = isset($_POST['address']);
$phoneNubmber = isset($_POST['phoneNubmber']);
$result = $connection->query("INSERT INTO `companies`
(`name`, `email`, `phone`) VALUES('$cegnev ',
'$address', '$pn')");
header('Location: http://localhost/phptest/test.php');
mysqli_close($connection);
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Form</title>
<meta charset="UTF-8">
<link rel="stylesheet" tpe="text/css" href="urlapcss.css">
</head>
<body>
<div id="container">
<form id="reg" action="test.php" method="post">
<fieldset>
<legend>Form</legend>
<ol>
<li>
<label for="cname">Name of the company<em>*</em></label>
<input id="cname" type="text" name="cname"/>
</li><li>
<label for="address">Email<em>*</em></label>
<input id="address" type="text" name="address"/>
</li><li>
<label for="phoneNubmber">Phone number<em>*</em></label>
<input id="phoneNubmber" type="text" name="phoneNubmber" />
</li>
</ol>
</fieldset>
<input type="submit" value="OK"/>
</form>
</div>
</body>
</html>
Here is the table.
Btw, the mysql.php, if you wondering what this .php file contains :
<?php
$host = "localhost";
$userName = "root";
$password = "";
$DBname = "hgeza06";
$connection = new mysqli($host, $userName, $password, $DBname);
if ($connection->connect_error) {
die("Error");
} else {
echo "Succes!";
}
?>
isset($_POST['cname']) - will return 1 if you have $_POST['cname'] or 0 if you don't have it.
A better way will be :
$companyName = isset($_POST['cname']) ? $_POST['cname'] : '' ; //add a empty value if is not filled
$address = isset($_POST['address']) ? $_POST['address'] : '';
$phoneNubmber = isset($_POST['phoneNubmber']) ? $_POST['phoneNubmber'] : '';
For starters, your variable names are inconsistent. You create a variable called $companyName and then try to use it as $cegnev. Same problem with your $phoneNubmber variable (which itself also contains a typo). Use the variables that you define.
Once that's corrected... This return a boolean (true/false) value:
isset($_POST['cname'])
So you're literally inserting true and false values into your database, which get interpreted as 1 and 0. Get the actual values:
$companyName = $_POST['cname'];
Use isset() to determine conditionally what you want to do if the value is or is not set, but don't use it to try and get the value itself.
Finally, and this is important, your code is wide open to SQL injection. (Or is about to be anyway, and it's by coincidence and error alone that it isn't currently open to it.) There is great information here on what to do about that. This is important because SQL injection vulnerabilities are both a major security hole (and thus a bad habit to allow to continue) but also a very common source of bugs and unexpected behavior in code.

Inserting input field value to database and displaying result on same page

I am starting to learn the basics of SQL and PHP codes.
I am trying to create a simple newsletter subscription page. this would require the user to enter their email and submit. That will then get added to my database.
Now, this works well when the HTML and PHP code are separate and the submission occurs but redirects to the PHP page with the echo.
I want to get the message on the same page and I tried merging the PHP code in the page as below
<?php
if($_SERVER['REQUEST_METHOD'] === 'POST'){
mysql_connect("hostname", "username", "password");
mysql_select_db("db name");
$user = $_POST['email'];
$query = "INSERT INTO tablename(columname)VALUES('$email')";
echo "inserted";
}
?>
<html>
<form method="POST" action="" >
<label>Email:</label> <input name="email" type="text"/>
<input type="submit" name="submit" value="Insert" /> <br>
</form>
</html>
Hoever with this code it just doesnt do anything.
What have am I doing wrong here? Appreciate your expert advice.
There are few mistakes in the code, you can fix them by doing the following:
Save the file as a php file first. For example name it "email.php".
Make the form action="email.php"
Don't write two complete separate codes in the same file, one for php file and the other for html file like you did. You can include the html code inside the php code using heredoc syntax which allows you to include a long html code like the following:
echo<<<_HTMLCODE
<form method="POST" action="" >
<label>Email:</label> <input name="email" type="text"/>
<input type="submit" name="submit" value="Insert" /> <br>
</form>
_HTMLCODE;
In the query syntax, add $user instead $email because the variable $user contains the value submitted by the form.
Add a code to excute the inserted query. for example:
mysql_query($query);
So your final code will be like this:
<?php
if($_SERVER['REQUEST_METHOD'] === 'POST'){
mysql_connect("hostname", "username", "password");
mysql_select_db("db name");
$user = $_POST['email'];
$query = "INSERT INTO tablename VALUES('$user')";
mysql_query($query);
echo "inserted";
}
echo<<<_HTMLCODE
<form method="POST" action="email.php" >
<label>Email:</label> <input name="email" type="text"/>
<input type="submit" name="submit" value="Insert" /> <br>
</form>
_HTMLCODE;
?>
I have tried the code above after I added the data of my database on the localhost and after I created a table for the emails and it worked. Here is the edited code with my database access info and the table name in my code editor:
When i opened the table emails in my database, I found the email that I had submitted using the form (your modified code):
(advice: use mysqli instead of mysql)
Please use prepare statements to prevent Sql Injections.
Here is sample code try this.
ini_set('display_errors', 1);
ini_set('log_errors', 1);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$connect = new mysqli ("localhost", "root", "usbw", "test");
if (mysqli_connect_errno()) {
echo 'Failed to connect to MySQL:' . mysqli_connect_error();
}
if (isset($_POST['submit'])) {
$email = filter_input(FILTER_VALIDATE_EMAIL, $_POST['email']);
$sql = "INSERT INTO table (email) VALUES (?)";
$stmt = $connect->prepare($sql);
$stmt->bind_param('s', $email);
$result = $stmt->execute();
if ($result) {
$msg = 'Succesfully added';
} else {
$msg = 'OOPS Error Occured';
}
}
?>
<html>
<form method="POST" action="" >
<label>Email:</label> <input name="email" type="text"/>
<input type="submit" name="submit" value="Insert" /> <br>
</form>
</html>

Writing to database from CKEDITOR

I'm trying to write to a database using CKEditor.. when I press submit it dies and says localhost is currently unable to handle this request.
HTTP ERROR 500
I only want to save the textarea into a row in database so I can then read the row on to another page.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="robots" content="noindex, nofollow">
<title>Classic editor replacing a textarea</title>
<script src="http://cdn.ckeditor.com/4.6.0/standard-all/ckeditor.js"></script>
</head>
<body>
<form id="editor1" action="save.php" method="post" >
<textarea cols="80" id="editor1" name="editor1" rows="10">
</textarea>
<p>
<input type="submit" value="Submit">
</p>
</form>
<script>
CKEDITOR.replace( 'editor1' );
</script>
</body>
</html>
PHP script
<?php
if(isset($_POST['submit']))
{
// Putting data from form into variables to be manipulated
$text = $_POST['editor1'];
$conn = mysql_connect("localhost","root","root") or die ("Can't connect");
mysql_select_db("managerMessage",$conn);
// Getting the form variables and then placing their values into the MySQL table
mysql_query("INSERT INTO text (textarea) VALUES ("mysql_real_escape_string($text)");
}
?>
You are not concatenating the value correctly in this statement and also text data in a query like this should be wrapped in quotes
mysql_query("INSERT INTO text (textarea) VALUES ("mysql_real_escape_string($text)");
This is a corrected verion of your code
mysql_query("INSERT INTO text
(textarea)
VALUES ('" . mysql_real_escape_string($text) . "')");
A simpler piece of code would be to read and probably maintain would be
$t = mysql_real_escape_string($text);
mysql_query("INSERT INTO text (textarea) VALUES ('$t')");
I would be remiss if I did not remind you that
Every time you use the mysql_
database extension in new code
a Kitten is strangled somewhere in the world it is deprecated and has been for years and is gone for ever in PHP7.
If you are just learning PHP, spend your energies learning the PDO or mysqli database extensions.
Start here
EDIT RE: not saving the data to the database
Add some error checking to your code like so:
$t = mysql_real_escape_string($text);
$result = mysql_query("INSERT INTO text (textarea) VALUES ('$t')");
if ( ! $result ) {
echo mysql_error();
exit;
}
Once you know the error, if one exists, you can start work on fixing it.

Inserting form information with php to mysql does not work

I have a problem inserting information into a sql database.
The user needs to answer a question and submit that.
<!DOCTYPE html>
<html>
<head>
<title>Some title</title>
</head>
<body>
<form action="neg.php" method="post">
<b>Enter a title:</b><br /><input type="text" name"title" /><br />
<input type="submit" value="I !" />
</form>
</body>
</html>
The php page looks like this:
<?php
/* get all input*/
$connection = mysqli_connect("localhost","X","Y","Z") or die("Some error occurred during connection " . mysqli_error($connection));
$sql="INSERT INTO xyz (title)
VALUES
('$_POST[title]')";
if (!mysqli_query($connection,$sql))
{
die('Error: ' . mysqli_error($connection));
}
echo "1 record added";
?>
Can anyone please help me out here? I'm really stuck, tried a million things, but simply do not see what went wrong. I also do not get an error, so I'm unsure what the problem is. Can anyone please help me out here?
Thanks in advance!
EDIT
OP changed INSERT INTO dislike to INSERT INTO xyz from an edit after my submitting this answer, including changing value="I don't want to see this show ever again!" to value="I !"
Original answer from original question:
The reason why your query is not working is because the = is missing in name"title"
Change it to name="title"
You should also consider using prepared statements or PDO.
The method you're using now, is open to SQL injection
I've made it a bit more safer for you doing it the following way:
<?php
/* get all input*/
$connection = mysqli_connect("localhost","X","Y","Z") or die("Some error occurred during connection " . mysqli_error($connection));
$title=mysqli_real_escape_string($connection,$_POST['title']);
$sql="INSERT INTO dislike (title) VALUES ('$title')";
if (!mysqli_query($connection,$sql))
{
die('Error: ' . mysqli_error($connection));
}
echo "1 record added";
?>
HTML rewrite:
<!DOCTYPE html>
<html>
<head>
<title>Dislike series</title>
</head>
<body>
<form action="neg.php" method="post">
<b>Enter a title:</b><br /><input type="text" name="title" /><br />
<input type="submit" value="I don't want to see this show ever again!" />
</form>
</body>
</html>
Here are a few tutorials on prepared statements that you can study and try:
Tutorial one
Tutorial two
Tutorial three
Here are a few tutorials on PDO:
PDO tutorial one
PDO tutorial two
PDO tutorial three

PHP/MySQL error for a simple form i made for testing (i'm trying to teach myself some MySQL/PHP)

OK, so, first of all, i'm new to PHP and MySQL so i'm sorry if i'm going to ask some stupid questions:
The page i am trying to create has 4 forms, and a submit button, and i want to send all this info to the database when i click submit, but i have these errors:
Notice: Undefined index: submit in C:\XAMPP\htdocs\SQLtesting\index.php on line 37
Notice: Undefined variable: sql in C:\XAMPP\htdocs\SQLtesting\index.php on line 45
Warning: mysqli_query(): Empty query in C:\XAMPP\htdocs\SQLtesting\index.php on line 45
Here is the code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
<meta name="author" content="abcde" />
<title>Untitled 2</title>
</head>
<body>
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>" name="User">
First Name:
<input type="text" name="firstName" /> <br />
Last Name:
<input type="text" name="lastName" /> <br />
E-mail:
<input type="text" name="email" /> <br />
Phone Number:
<input type="text" name="phoneNumber" /> <br />
<input type="submit" name="submit" />
</form>
<?php
$con=mysqli_connect("localhost","root",'',"test_1");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if(isset($_POST['submit'])){
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$email = $_POST['email'];
$phoneNumber = $_POST['phoneNumber'];
}
if($_POST['submit'])
{
$sql="INSERT INTO test_1_1(id,firstName, lastName, email, phoneNumber)
VALUES
('','$_POST[firstName]','$_POST[lastName]','$_POST[email]', '$_POST[phoneNumber]')";
echo "1 record added";
}
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
mysqli_close($con);
?>
</body>
</html>
I also noticed that if i write the
$sql="INSERT INTO test_1_1(id,firstName, lastName, email, phoneNumber)
VALUES
('','$_POST[firstName]','$_POST[lastName]','$_POST[email]', '$_POST[phoneNumber]')";
simply without an if conditional i won't get the
Warning: mysqli_query(): Empty query in C:\XAMPP\htdocs\SQLtesting\index.php on line 45
error but the code would add an empty row at the beginning.
I am using XAMPP for running this on local machine.
You have to make sure that $_POST['submit'] is set before you attempt to run the query. Try:
if(isset($_POST['submit'])){
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$email = $_POST['email'];
$phoneNumber = $_POST['phoneNumber'];
$sql = "INSERT INTO test_1_1 (id,firstName, lastName, email, phoneNumber)
VALUES ('','$firstName','$lastName','$email', '$phoneNumber')";
if (!mysqli_query($con,$sql)){
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
}
By the way, your code is open to SQL injection. You can solve this security flaw by getting yourself familiar with prepared statements.
Chances are high that the:
if($_POST['submit']) {}
return false and your $sql var isn't filled
Try to add
var_dump($sql);
right before the
if (!mysqli_query($con,$sql))
Everything is related to everything. At first - use function such as var_dump to dump the content of $_POST.
I don't see the reason why $_POST['submit'] is empty, but I'd add some value to it:
<input type="submit" name="submit" value="Hey!" />
Check the condition and the brackets, it doesn't make sense. See Wayne Whitty's answer is correct.
Personally I'd recommend you using some php framework although you spend more time on it. They usually contain a lot of examples, documentation and they are very often aiming to learn you some good habits (coding style, ...).
Notice: Undefined index: submit in C:\XAMPP\htdocs\SQLtesting\index.php on line 37
This means $_POST['submit'] does not exist. You should check if it exists using isset(...) instead of using it directly if you don't want to get the warning.
Notice: Undefined variable: sql in C:\XAMPP\htdocs\SQLtesting\index.php on line 45
Since $_POST['submit'] does not exist, the if clause is not executed and $sql is not filled, the error is self explanatory here.
Warning: mysqli_query(): Empty query in C:\XAMPP\htdocs\SQLtesting\index.php on line 45
This means query string ($sql is not defined and therefore defaulted to an empty string) is empty.

Categories