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.
Related
I have just started learning PHP and I am facing this issue when using $_SERVER["PHP_SELF"] to redirect to the same page after user clicks Submit in the form. The problem are the $_POST[] variables I have used in my PHP script in the page, which I need to access AFTER user clicks Submit and the page reloads. But on the first run, when the the user hasn't clicked Submit, the $_POST variables are empty and I am getting errors displayed on the page itself. Of course, there are no errors after the user click Submit and page reloads. I don't want to redirect to another page after Submit. How do I circumvent these errors on the first run?
Is there a better approach for what I am trying to do?
The code for my page is here:
<!DOCTYPE html>
<html>
<head>
<title>Welcome!</title>
</head>
<body>
<h3> Welcome!</h3>
</br></br>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" >
First Name: <input type="text" name="fname"> </br></br>
Last Name: <input type="text" name="lname"> </br></br>
Age: <input type="number" name="sage"> </br></br>
<input type="submit" value="Submit"></br></br>
</form>
<?php
$servername = "localhost";
$username = "user1";
$password = "abcd123";
$dbname = "myDbFromPhp";
$fname = $_POST["fname"]; /*Lines responsible for the errors, I think*/
$lname = $_POST["lname"];
$sage = $_POST["sage"];
if($fname != "" and $lname != "") /*Checking for empty vars*/
{
$conn = new mysqli($servername, $username, $password, $dbname);
if($conn->connect_error)
{
die("Connection failed: ".$conn->connect_error);
}
echo "<h4>Connected successfully</h4>";
$sql = "INSERT INTO Students
(fname, lname, sage)
VALUES
('".$fname."','".$lname."',".(string)$sage.");" ;
if($conn->query($sql) === TRUE)
{
echo "<h4>Value entered successfully</h4>";
}
else
{
echo "</br>Error creating record</br>".$conn->error;
}
$conn->close();
}
?>
</body>
</html>
The page simply takes some input from the user (Student: first name, last name, age), and when user clicks Submit, reloads and saves them to a database.
First time of page load post value not exists so use isset to check that like this
<input type="submit" name="submit" value="Submit"></br></br>
if(isset($_POST['submit']))
{
//all of your db insertion related codes all here
$fname = $_POST["fname"]; /*Lines responsible for the errors, I think*/
$lname = $_POST["lname"];
$sage = $_POST["sage"];
......................
......................
header('Location:samepage.php');
// redirect the page to avoid the duplicate insertion by pressing F5 or reload .
}
your code looks sql injection attack . try to use prepared statement or PDO
In your first loading, that variable does not have values, therefore php genarate a error, therefore you can use isset() to check whether data assigned or not
if(isset($_POST["fname"])){
$fname = $_POST["fname"];
$lname = $_POST["lname"];
$sage = $_POST["sage"];
}
you can do all functionalities inside the if(isset($_POST["fname"])){ }
This one is leaving me scratching my head. I'm sure I'm missing something simple, but for the life of me I can't see what when I compare it to other INSERT statements I've written that work just fine. The parameters are being passed when I check the network tab in developer, but it won't forward to the page specified in the header, and the table is not updated with information when I fill in the form.
Here is the function I wrote in the model layer:
function add_yarn($yarnbrand, $yarnamount, $yarnweight, $yarncolor) {
global $db;
$query = 'INSERT INTO yarn
(yarnbrand, yarnamount, yarnweight, yarncolor)
VALUES
(:yarnbrand, :yarnamount, :yarnweight, :yarncolor)';
$statement = $db->prepare($query);
$statement->bindValue(':yarnbrand', $yarnbrand);
$statement->bindValue(':yarnamount', $yarnamount);
$statement->bindValue(':yarnweight', $yarnweight);
$statement->bindValue(':yarncolor', $yarncolor);
$statement->execute();
$statement->closeCursor();
}
Here is the control layer in for the action associated with that function in index.php:
case 'yarn_add' :
$yarnbrand = filter_input(INPUT_POST, 'yarnbrand');
$yarnamount = filter_input(INPUT_POST, 'yarnamount', FILTER_VALIDATE_INT);
$yarnweight = filter_input(INPUT_POST, 'yarnweight');
$yarncolor = filter_input(INPUT_POST, 'yarncolor');
if ($yarnbrand == NULL || $yarnamount == NULL ||
$yarnweight == NULL || $yarncolor == NULL) {
echo 'Empty or invalid data input.';
} else {
add_yarn($yarnbrand, $yarnamount, $yarnweight, $yarncolor);
header('Location: index.php?action=view_yarn');
}
break;
and here is the view layer with the add form:
<?php include '../view/header.php'; ?>
<main>
<h1>Add Yarn</h1>
<form action="index.php" method="post" id="add_yarn_form">
<input type="hidden" name="action" value="yarn_add">
<label>Brand:</label>
<input type="text" name="yarnbrand"> <br>
<label>Weight:</label>
<input type="text" name="yarnweight"><br>
<label>Amount:</label>
<input type="text" name="yarnamount"><br>
<label>Color:</label>
<input type="text" name="yarncolor"><br>
<label> </label>
<input type="submit" value="Save Changes"><br>
</form>
<div class="bottomtext">
View Yarns
View Supplies
</div>
</main>
<?php include '../view/footer.php'; ?>
I appreciate any help!
Maybe a variable with an illegal caracter ? You don't use filters in your filter_input, expected for the integer variable.
Take a look on the manual :
If omitted, FILTER_DEFAULT will be used, which is equivalent to FILTER_UNSAFE_RAW. This will result in no filtering taking place by default.
Not really secure :/
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')";
I have 3 files.
1st one :
<html>
<form action="employeeDel.php" method ="post">
Enter Ssn To Delete Employee:<br>
<input type="number" name="ssnDel">
<br>
<br>
<input type="submit" value="Submit">
</form>
</html>
This form sends data to employeeDel.php.
employeeDel.php :
<html>
<form action ="employeeDelFinal.php" method="post">
<input type="hidden" name="ssn" value="ssnDel">
<?php
$ssnDel = $_POST ["ssnDel"];
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "company";
$conn = mysqli_connect ( $servername, $username, $password, $dbname );
// Check connection
if (! $conn) {
die ( "Connection failed: " . mysqli_connect_error () );
}
$sql = "SELECT * from employee WHERE ssn=".$ssnDel;
<input type="submit" name="Delete?">
</form>
</html>
From here, when user clicks on submit button, I want html form to send ssnDel value to employeeDelFinal.php file.
employeeDelFinal.php :
<?php
$ssnDel = $_POST ["ssn"];
echo ssnDel;
?>
That value never reaches here. I got an error on employeeDel.php file, it says value of ssnDel is null. I guess in the beginning of form in employeeDel file, I create ssnDel again, so it becomes null.
Is there a way to send a data from html form to employeeDel.php, from employeeDel.php to employeeDelFinal.php by using form? I tried hidden text but it didn't solve my problem as seen.
The line
<input type="hidden" name="ssn" value="ssnDel">
should be something like
<input type="hidden" name="ssn" value="<?php echo(intval($_POST['ssnDel'])); ?>">
(Assuming that ssnDel is an ID-Number.)
Otherwise that hidden variable will have the string-value ssnDel, not the value of the variable $_POST['ssnDel'].
And as already mentioned, echo ssnDel; should be echo $ssnDel; and you should use less spaces (e.g. no spaces after $_POST or function names).
There are couple of things I noticed. You have
employeeDelFinal.php :
<?php
$ssnDel = $_POST ["ssn"];
echo ssnDel;
?>
You don't have a dollar sign in your echo statement ssnDel.
And why do you have spaces in between $_POST ["ssnDel"] make it
$_POST["ssnDel"]
So I am building a simple question form that allows a user to submit a question and once the question is submitted it is sent to the database. I can't figure out why it isn't working. Here is my code, first one is the ask.html and the second is the ask.php.
<form action="ask.php" method="POST">
Name: (not your real name)<br/>
<input type="text" name="name" id="name"/>
<br/>
<br/>
Question: <br/>
<textarea name="question" cols="60" rows="10" id="question">
</textarea>
<br/>
<input type="submit" />
</form>
<?php
include('config.php');
include('open_connection.php');
if ((!$_POST[name]) || (!$_POST[question]))
{
header ("Location: ask.html");
exit;
}
//Select database and table
$db_name = "questionme";
$table_name = "questions";
//Insert data into database
$sql = "INSERT INTO $table_name
(name, question) VALUES
('$_POST[name]', '$_POST[question]')";
$result = #mysql_query($sql, $connection) or die(mysql_error());
?>
<html>
<head>
<title>Ask</title>
<head>
<body>
<h1>Question Submitted</h1>
<p><strong>Name:</strong>
<?php echo "$_POST[name]"; ?></p>
<p><strong>Question:</strong>
<?php echo "$_POST[question]"; ?></p>
</body>
</html>
The following is certainly generating warnings:
if ((!$_POST[name]) || (!$_POST[question]))
replace with
if (!isset($_POST[name]) || !isset($_POST[question]))
then absolutely take into consideration what the other dudes answered. On your INSERT:
('$_POST[name]', '$_POST[question]')";
would be better off as (they're also triggering warnings):
('{$_POST['name']}', '{$_POST['question']}')";
And on these
<?php echo "$_POST[name]"; ?></p>
...
<?php echo "$_POST[question]"; ?></p>
have them as
<?php echo $_POST['name']; ?></p>
...
<?php echo $_POST['question']; ?></p>
Check your post variables with isset() and use quotes for the hashes you're checking:
if (!isset($_POST['name']) || !isset($_POST['question']))
Also, never insert the values of your $_POST variables directly - do something like this instead:
$name = mysql_real_escape_string($_POST['name']);
$question = mysql_real_escape_string($_POST['question']);
Have you show_errors PHP configuration enabled?
Try placing some lines like
echo "[1]";
echo "[2]";
etc to discover where your script terminates (debug a bit);
AND NEVER, NEVER USE _POST and _GET variables in SQL queries directly (use mysql_real_escape_string to escape their values)... or your script will be vulnerable to SQL injection attacks!!!
if you are using tables like $_POST['name'] in a string you have to wrap them with a {}
$sql = "INSERT INTO $table_name
(name, question) VALUES
('{$_POST[name]}', '{$_POST[question]}')";
<?php echo "{$_POST[name]}"; ?>
also