HTML form not populating MySQL DB as expected - php

When I save a form from html to php and finally store it in MySQL somewhere in that line it save the var= including what comes after the =
Here is my html:
<form action="searchResultsSave.php" method="POST">
What are we looking for? <input type="text" name="searchVar" />
<input type="submit" value="Submit">
</form>
Php:
$searchVar = file_get_contents('php://input');
$sql = "INSERT INTO g_information(searchVar) VALUES ('$searchVar')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
Finally my output in mysql is: "searchVar=cars" when it should just be "cars".
Where do you think I went wrong?

$searchVar = file_get_contents('php://input');
should be
$searchVar = $_POST['searchVar'];
This way you get the value of the search term.

You should read input variable from the form
<?php
$_POST["searchVar"];
?>
Then do some validation on the input, making sure no illegal characters are entered and data is safe to store in MySQL database
<?php
$_POST['searchVar'] = filter_var($_POST['searchVar'], FILTER_SANITIZE_STRING);
$sql = "INSERT INTO g_information(searchVar) VALUES ("'.$_POST['searchVar'].'")";
?>

Related

PHP/HTML forms and database inserting

I am going to start this off by saying -- yes I know there are other links similar to this and topics similar to this and I have read all of them and incorporated them into my code. However, I cannot figure it out and have tried everything I can.
Basically my goal is to take a users input from an html form called socialmedia.html:
<html>
<body>
<h1> Pulse submission page </h1><br>
<form action="action.php" method="post">
Title: <input type="text" name="posttitle"><br><br>
Content: <input type="text" name="content"><br><br>
<input type="submit">
</form>
</body>
</html>
and then send it to a php file called action.php:
<?php
$mysqli = new mysqli("DB HOST IP", "USER", "PASS", "DB NAME");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
echo $mysqli->host_info . "\n";
$posttitle = $_POST["posttitle"];
$content = $_POST["content"];
if(isset($_POST['submit'])){
$sql = "INSERT INTO `posts` (posttitle, content) VALUES ('$posttitle', '$content')";
echo 'post added to database';
}
if($sql){
echo 'success';
}
else{
echo 'failure';
}
$sql = "SELECT * FROM `posts`";
$res = $mysqli->query($sql);
if($res->num_rows > 0){
while($row = $res->fetch_assoc()){
echo "ID". $row["id"]. "<br/>";
echo "Title". $row["posttitle"]. "<br/>";
echo "Content". $row["content"]. "<br/>";
}
}
else
{
echo "No Record Found!";
}
?>
This file is SUPPOSED to insert the user's form values into the table posts:
this is the table posts
and then print the whole table to a webpage-- action.php this is what it prints (with the error checks and all):
this is the page, I blurred out the IP
NOTE: I manually inserted the first title and content to see if the code could read from the database (which it can)
honestly, I do not know where I went wrong and I have die extensive research at this point. It's probably going to end up being a syntax error and I'm gonna be kicking myself. It could have something to do with me using a Godaddy server and the phpMyAdmin and database being through there. I am using mysqli instead of PDO because PLESK and Godaddy do not support PDO yet.
<input type="submit" name="submit" /> try with this
if(isset($_POST['submit'])){
$sql = "INSERT INTO `posts` (posttitle, content) VALUES ('$posttitle', '$content')";
$save = $mysqli->query($sql);
if($save)
echo 'success';
else
echo 'failure';
}
several things to get you started
1) missing quote after PASS
mysqli("DB HOST IP", "USER", "PASS, "DB NAME");
2) you are not executing your INSERT query, missing $mysqli->query($sql);
if(isset($_POST['submit'])){
$sql = "INSERT INTO `posts` (posttitle, content) VALUES ('$posttitle',
'$content')";
echo 'post added to database';
}
You have to give name of the submit butto as
input type="submit" name="submit"
"INSERT INTO posts (posttitle, content) VALUES ('$posttitle', '$content')"

Form content as PostGre query parameter

So, I'm pretty new to web. I'm always fiddling with HTML and SQL, but recently I started working on a project. This project is basically creating a database with all employees contact data (name, email, phone number, etc) and show it on web. Database is set, web page is connecting normally to DB (I can call PHP and send a query, results are shown perfectly). BUT I don't know how to use a <form> content (text written by user) as a Query Parameter. I want to send the parameter when Enter or the 'busca' button are pressed.
Here is the form
<form id="searchbox" >
<label for="sectname">
</label>
<input id="sectname" name="sectname" type="search" placeholder="Busca" list="setor" class="searchbox"/>
<div style="text-align:center">
<input id="submit" type="button" class="button" value="BUSCA"/>
</div>
</form>
And here is the PHP with query
$host = "host=localhost";
$port = "port=5432";
$dbname = "dbname=Cards";
$creds = "user=postgres password=12345678";
$db = pg_connect( "$host $port $dbname $creds" );
if(!$db){
echo nl2br ("Unable to open database\n");
}
$sql =<<<EOF
SELECT * from Cards where nome='Diego Teste';
EOF;
$ret = pg_query($db, $sql);
if(!$ret){
echo pg_last_error($db);
exit;
}
while($row = pg_fetch_assoc($ret)){
echo "<div>";
echo "<img src='".$row['pic']."'class='cardcontent2'/>";
echo "<div class='carddata'>";
echo nl2br ("\nNome: ".$row['nome'] . "\n");
echo nl2br ("Email: ".$row['email'] . "\n");
echo nl2br ("Ramal: ".$row['ramal'] . "\n");
echo nl2br ("NĂºmero: ".$row['numero'] . "\n");
echo nl2br ("Setor: ".$row['setor'] . "\n\n");
echo "</div>";
echo "</div>";
}
pg_close($db);
I want 'nome="Diego Teste"' to be 'nome= %var%' and the %var% value should be text written by user.
The trick is to use prepared statements: (ref)
$basequery =<<<EOF
SELECT * from Cards where nome = $1;
EOF;
pg_prepare($db, "my_query", $basequery);
$results = pg_execute($db, "my_query", array($_GET["nome"]));
...
Prepared statements take care of escaping any values you will pass to SQL, so you do not have to do it yourself. It protects you from SQL injection; some people will fill form fields with malicious content that can trip up your SQL statement if you just put the field's text in-place.
My PHP might be a bit rusty, so please forgive me if I made minor mistakes.

Make html text input php variable

I want a html text input with name="input1" become a php variable called $value. I tried doing:
<html>
<form action="added.php" method="post" />
<p>Send a message to JANNES database: <input type="text" name="input1" />
</p>
<input type="submit" value"Submit" />
</form>
</html>
<?php
$value = $_POST["input1"];
$sql = "INSERT INTO janne (String) VALUES ('$value')";
if(!mysql_query($sql)){
die('vajsing: ' . mysql_error());
}
?>
And it is working, but I get this annoying error when I visit the website:
"Notice: Undefined index: input1 in C:\wamp\www\added.php on line 26
Call Stack
Time Memory Function Location
1 0.0008 250336 {main}( ) ..\added.php:0"
Notice that i didn't post the whole code. My php file is called added.php.
By default, $_POST["input1"] is empty as you have not submitted your form yet. You should check whether the form is submitted or not, like below:
if(isset($_POST["input1"])){
//rest of code
}
Check if the form is submitted or not. If you load the page directly, there's nothing inside $_POST['input1'].
<?php
if(isset($_POST['submit']))
{
$value = $_POST["input1"];
$sql = "INSERT INTO janne (String) VALUES ('$value')";
if(!mysql_query($sql)){
die('vajsing: ' . mysql_error());
}
}
?>
Change it to this:
<?php
if(isset($_POST["input1"])){
$value = $_POST["input1"];
$sql = "INSERT INTO janne (String) VALUES ('$value')";
if(!mysql_query($sql)){
die('vajsing: ' . mysql_error());
}
}
?>
The problem is: You weren't checking to see if it was set before trying to use it, so when you visit it without the post data being set then it gives you an error.

Taking data from a sql query in php and sending it to another php

So, i have a php page that makes a combobox by taking data from a database. After i interrogate the database i want to save the selection and send it to another php page. But, the problem is it doesn't reach it.
<form action ="sending.php" method="POST" >
<?php
$link = mysql_connect('localhost', 'root', '','printers');
mysql_select_db("printers", $link);
$query = "SELECT name_printer FROM insurers";
// Execute it, or return the error message if there's a problem.
$result = mysql_query($query) or die(mysql_error());
$dropdown = "<select name='users' class='dropdown-menu'>";
while($row = mysql_fetch_assoc($result)) {
$dropdown .= "\r\n<option value='{$row['name_printer']}'>
{$row['name_printer']}</option>";
}
$dropdown .= "\r\n</select>";
echo $dropdown;
?>
<br><br>
<input type="hidden" name="selected_text" id="selected_text" value="" />
<input type="submit" name="search" value="Search"/>
</form>
And the sending.php
<?php
if(isset($_POST['search']))
{
$makerValue = $_POST['users']; // make value
$maker = mysql_real_escape_string($_POST['selected_text']); // get the selected text
var_dump( $maker);
}
?>
What it prints is string(0) "".
Your issue is with the $maker variable, it is set from an escaped $_POST['selected_text'] which if you look in the html the value is set to value="", so by var_dumping it you would not receive any output.
What you should do instead is use mysql_real_escape to escape the $makerValue rather than $_POST['selected_text'].
That way it will dump the data received from the database.
Actually you are already getting selected_text from bellow statement :
$makerValue = $_POST['users'];
So you can use bellow code directly :
$maker = mysql_real_escape_string($_POST['users']);
One more thing,
mysql_real_escape_string()
is deprecated as of PHP 5.5.0

send array[] from php to mysql

im working on a project but first i would to understand one thing.
i have 2 input type text field with name="firstname[]" as an array (in the example im working with no jquery but it will be generated dinamically with it) and cant make it to mysql.
here is what i have: index.php
<html>
<body>
<form action="insert.php" method="post">
Firstname: <input type="text" name="firstname[]"> <br>
Firstname 2: <input type="text" name="firstname[]">
<input type="submit">
</form>
</body>
</html>
insert.php
<?php
$con=mysqli_connect("localhost","inputmultiplicad","inputmultiplicado","inputmultiplicado");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO input_field (firstname)
VALUES
('$_POST[firstname]')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
?>
the question is: how can i send the firstname[] array to the mysql database?
thanks for your time
This should work:
//Escape user input
$names = array_map('mysql_real_escape_string', $_POST[firstname]);
//Convert array to comma-delimited list
$names = rtrim(implode(',', $names), ',');
//Build query
$sql="INSERT INTO input_field (firstname) VALUES ('$names')";
Note: In general, it's better to use parameterized queries than mysql_real_escape_string(), but the latter is much safer than no escaping at all.
The following should generate the SQL statement you need. Remember to use mysql_escape_string before putting it into your database, though! Or even better, use PDO and bind the values. :)
$values = array();
$sql = "INSERT INTO table (firstname) VALUES ";
foreach ($_POST['firstname'] as $name) {
$values[] = "('".mysql_real_escape_string($name)."')";
}
$sql .= implode(",", $values);

Categories