I've set up a form to insert data into a database. It's connected to it fine and can display records with no issues. However, when I want to insert data I click the submit button it removes it from the form but doesn't insert it into the db. I've tried rewriting it about 3 times now using 2 different databases but just can't figure out where I'm going on.
<html>
<head>
</head>
<body>
<form action="input.php" meathod="post">
Username: <input type="text" name="username"><br>
Password: <input type="text" name="password"><br>
<input type="submit" name="submit">
</form>
<?php
if( isset($_POST['submit'])){
//connecting to a databse
$conn = mysqli_connect("localhost","root","");
mysqli_select_db("test",$conn);
if($conn){
echo 'connected';
}
else {
die('failed to connect');
}
$sql="INSERT INTO users(username,password) VALUES ('$_POST[username]','$_POST[password]')";
mysql_query($sql,$conn);
mysqli_close($conn);
};
?>
</body>
</html>
You have few typos "meathod=post" should be method="post",mysql_query($sql,$conn) should be mysqli_query($conn,$sql) and mysqli_select_db("test",$conn) should be mysqli_select_db($conn,"test")
<html>
<head>
</head>
<body>
<form action="input.php" method="post">
Username: <input type="text" name="username"><br>
Password: <input type="text" name="password"><br>
<input type="submit" name="submit">
</form>
<?php
if( isset($_POST['submit'])){
//connecting to a databse
$conn = mysqli_connect("localhost","root","");
mysqli_select_db($conn,"test");
if($conn){
echo 'connected';
}
else {
die('failed to connect');
}
$sql="INSERT INTO users(username,password) VALUES ('" . $_POST['username'] . "','" . $_POST['password'] . "')";
mysqli_query($conn,$sql);
mysqli_close($conn);
};
?>
</body>
</html>
you have written "meathod=post" instead of "method=post"
also I have changed
$sql="INSERT INTO users(username,password) VALUES ('$_POST[username]','$_POST[password]')";
to
$sql="INSERT INTO users(username,password) VALUES ('" . $_POST['username'] . "','" . $_POST['password'] . "')";
this style much more better
<html>
<head>
</head>
<body>
<form action="lol.php" method="post">
Username: <input type="text" name="username"><br>
Password: <input type="text" name="password"><br>
<input type="submit" name="submit">
</form>
<?php
if( isset($_POST['submit'])){
//connecting to a databse
$conn = mysqli_connect("localhost","root","");
mysqli_select_db("test",$conn);
if($conn){
echo 'connected';
}
else {
die('failed to connect');
}
$sql="INSERT INTO users(username,password) VALUES ('" . $_POST['username'] . "','" . $_POST['password'] . "')";
mysql_query($sql,$conn);
mysqli_close($conn);
};
?>
</body>
</html>
I think problem is here
mysql_query($sql,$conn);
Replace with
mysqli_query($conn,$sql);
I hope this code will help you
<html>
<head>
</head>
<body>
<form action="input.php" method="post">
Username: <input type="text" name="username"><br>
Password: <input type="text" name="password"><br>
<input type="submit" name="submit">
</form>
<?php
if( isset($_POST['submit'])){
//connecting to a databse
$conn = mysqli_connect("localhost","root","");
mysqli_select_db("test",$conn);
if($conn){
echo 'connected';
}
else {
die('failed to connect');
}
$sql="INSERT INTO users(username,password) VALUES (".$_POST["username"].",".$_POST["password"].")";
mysqli_query($conn,$sql);
mysqli_close($conn);
?>
</body>
</html>
Related
Im trying to upload an image to a mysql database, but when I upload the image I receive the message of confirmation, but when i check my database the image row is empty, what am I doing wrong?
<?php include "connection.php"; ?>
<?php
$n=$_POST["num"];
$t=$_POST["texto"];
$i=$_POST["imagem"];
$image = addslashes(file_get_contents($_FILE['$i']['tmp_name']));
if ($connect->connect_error){
die("Connection failed: " . $connect->connect_error);
}
$sql = "UPDATE servicos SET texto='$t', imagem='{$image}' where nmr=$n" ;
if ($connect->query($sql) === TRUE) {
echo "informação atualizada";
} else {
echo "Error: " . $sql . "<br>" . $connect->error;
}
$connect->close();
?>
<html>
<body>
<div class="formulario" style="width: 100%; height: 100%;">
<form enctype="multipart/form-data" name="form1" target="apresenta" method="post" action="menu2.php" style="position:absolute; top:70;left:10
border:thin; border-style:none;">
<label> Atualizar dados </label><br>
Numero: <input type="text" name="num" value=""><br>
Texto: <input type="text" name="texto" value=""><br>
Imagem: <input type="file" name="imagem" value=""><br>
<input type="submit" name="submit" value="enviar">
<input type="reset" value="limpar">
</form>
</div>
</body>
</html>
Besides all the comments stating "You shouldn't store files in tables because...", this is what works (with PHP 7):
<?php
if(isset($_POST['submit'])) {
var_dump($_FILES);
$dbh = new PDO("mysql:host=127.0.0.1;dbname=test", "root", "");
$stm = $dbh->prepare("INSERT INTO test_img (cont) VALUES (?)");
$stm->execute(array(file_get_contents($_FILES['fileinput']['tmp_name'])));
}
?>
<form method="post" enctype="multipart/form-data">
File: <input type="file" name="fileinput"><br>
<button name="submit">Upload</button>
</form>
Possible error sources:
$connect->query($sql) === TRUE should be $connect->query($sql) !== false
The entry you want to UPDATE does not exist
imagem='{$image}' is a rather "hacky" way do insert variables, use concatenation: $sql = "UPDATE servicos SET texto='".$t."', imagem='".$image."' where nmr=".$n;
Hope this helps.
I've created simple code that has to add user on mysql through PHP, but it doesn't. Here is the code.
<form action='' method='post'>
Login: <input type='text' name='login' /> <br/>
Pass: <input type='pass' name='pass' /> <br/>
<input type='submit'>
</form>
<?php
$c=mysql_connect('localhost','test','test');
$login=$_POST['login'];
$pass=$_POST['pass'];
$t="CREATE USER '".$login."'#'localhost' IDENTIFIED BY PASSWORD '".$pass."';";
if($login!=NULL){
if($q=mysql_query($t,$c))
{
echo "CREATED!";
}else{
die('ERROR: ' . mysql_error());
}
}
?>
Error: Password hash should be a 41-digit hexadecimal number
Whats wrong with it?
Take out the word PASSWORD. By using that keyword, it suggests you're providing the hash. dev.mysql.com/doc/refman/5.5/en/create-user.html
You want this:
$t="CREATE USER '".$login."'#'localhost' IDENTIFIED BY '".$pass."';";
Try this :
<?php
$host="localhost";
$user="root";
$password="";
$con = mysqli_connect("localhost","root","","mydb");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
<!DOCTYPE html>
<head>
<title>MyExample</title>
<meta charset="UTF-8"/>
</head>
<body>
<h1>Create user in MySQL by FORM</h1>
<form action="<?php $_SERVER['PHP_SELF']?>" method="POST">
<label for="username">Username</label>
<input type="text" id="username" name="username" />
<label for="password">Password</label>
<input type="password" id="password" name="password"/>
<button type="submit" name="send">Send</button>
</form>
</body>
</html>
<?php
if (isset($_POST['send'])) {
$username = $_POST['username'];
$password = $_POST['password'];
mysqli_query($con,"CREATE USER '".$username."'#'".$host."' IDENTIFIED BY '".$password."'");
mysqli_close($con);
}
?>
I have a form page
<html>
<body>
<form action="insert.php" method="post">
App Name: <input type="text" name="fname" /><br><br>
App ID: <input type="text" name="lname" /><br><br>
<input type="submit" name="SubmitButton"/>
</form>
</body>
</html>
And this is the php page:
<html>
<body>
<?php
$con = mysql_connect("xxx","xxx","xxx");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("db", $con);
$sql="INSERT INTO app (fname, lname) VALUES('$_POST[fname]','$_POST[lname]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con)
?>
</body>
</html>
Now, I want it to display 1 record added on the same page as the form and not have the form send me to a new insert.php page with it. Basically, I want the submit form to stay in the same page with maybe a a new message popping up to show that it has worked.
I have already looked through some answers on stackoverflow like using
if(isset($_POST['SubmitButton']))
but it doesn't work. Maybe I placed it wrong or used it incorrectly but could someone help me figure it out?
Just make it an action to itself, and set an if $_POST['submit'] to add the records, and you can have both in the same file. If you wish to do so without refreshing the page, you'll need to use AJAX.
<html>
<body>
<?php
if (isset($_POST['SubmitButton'])) {
$con = mysql_connect("xxx","xxx","xxx");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("db", $con);
$sql="INSERT INTO app (fname, lname)
VALUES
('$_POST[fname]','$_POST[lname]')";
if (!mysql_query($sql,$con)) {
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con)
}
?>
<form action="" method="post">
App Name: <input type="text" name="fname" /><br><br>
App ID: <input type="text" name="lname" /><br><br>
<input type="submit" name="SubmitButton"/>
</form>
</body>
</html>
Also, mysql_* is deprecated, so you should consider converting to PDO or MySQLi to avoid SQL injection!
For learning purposes, I am creating a password manager on my local system. However there is a problem when it comes to inserting data into the database and I'm not sure why it isn't working.
My entire document can be the found below.
<?php
$user = 'root';
$pass = '';
$db = 'accounts';
$server = 'localhost';
$db_handle = mysql_connect($server, $user, $pass);
if (!$db_handle) {
echo "Unable to connect to DB: " . mysql_error();
exit;
}
$db_found = mysql_select_db($db, $db_handle);
if ($db_found) {
if (isset($_POST['type'])) {
$getOrSet = $_POST['type'];
$site = $_POST['site'];
$login = $_POST['login'];
if ($getOrSet == 'get') {
$pass = mysql_fetch_assoc(mysql_query("SELECT password FROM manager WHERE site = '$site' AND username = '$login'"))['password'];
} else if ($getOrSet == 'set') {
$url = $_POST['url'];
$pass = $_POST['pass'];
mysql_query("INSERT INTO manager (site, url, username, password) VALUES ('$site', '$url', '$login' '$pass')");
}
}
} else {
echo "Unable to select database: " . mysql_error();
}
mysql_close($db_handle);
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
#left,#right{width:50%;margin:0;padding:0;float:left;text-align:center}
form{width:300px;margin:0 auto}
label{width:300px;display:block;line-height:1.65em}
input{float:right}
#pass{width:300px}
#pass>span{float:right}
</style>
</head>
<body>
<h1>Password Manager</h1>
<div id="left">
<h2>Get Password</h2>
<form action="index.php" method="post">
<label>Site: <input type="text" name="site" /></label>
<label>Email/Username: <input type="text" name="login" /></label>
<input type="hidden" name="type" value="get" />
<?php if(isset($_POST['type'])){if ($getOrSet == 'get') {echo "<span id=\"pass\">Password: <span>$pass</span></span>";}} ?>
<input type="submit" value="Submit" />
</form>
</div>
<div id="right">
<h2>Set Password</h2>
<form action="index.php" method="post">
<label>Site: <input type="text" name="site" /></label>
<label>URL: <input type="text" name="url" /></label>
<label>Email/Username: <input type="text" name="login" /></label>
<label>Password: <input type="password" name="pass" /></label>
<input type="hidden" name="type" value="set" />
<input type="submit" value="Submit" />
</form>
</div>
</body>
</html>
Can someone please tell me why this code doesn't work?
mysql_query("INSERT INTO manager (site, url, username, password) VALUES ('$site', '$url', '$login' '$pass')");
use escapes before insert like
$site = mysql_real_escape_string($site);
$url = mysql_real_escape_string($url);
$login = mysql_real_escape_string($login);
$pass = mysql_real_escape_string($pass);
// now insert
mysql_query("INSERT INTO manager (site, url, username, password) VALUES ('$site', '$url', '$login', '$pass')");
Note : mysql_* is deprecated. use mysqli_* or PDO
The problem is that there is a missing , after '$login' so
mysql_query("INSERT INTO manager (site, url, username, password) VALUES ('$site', '$url', '$login' '$pass')");
should have been
mysql_query("INSERT INTO manager (site, url, username, password) VALUES ('$site', '$url', '$login', '$pass')")
Tried figuring this out on my own using previous threads, but other peoples' examples didn't quite help me figure out what I need. The stand-alone files themselves work, data gets inserted into the DB just fine... but I'm trying to adapt these documents a bit to work as an all-in-one, single PHP document.
I figure I'll just throw out what I'm trying to do and the code I have so far, and maybe someone will understand what I'm trying to accomplish and be able to explain how to do it.
I basically have an PHP document with form (form.php) that uses POST to send the form data to a second PHP document, which in turn sends the form data to a MySQL database. I want the user to be able to post the data using the same document and have the data fields reset so that the user and submit enter more information through the form. I would like the make the user aware of errors due to incomplete fields, and I would like the user to be made aware of successful entries (which I will do using the echo function).
form.php is as follows:
<html>
<head>
<link rel="stylesheet" type="text/css" href="form.css">
<title>MySQL Database Creation System</title>
<script src="jquery-1.11.0.min.js"></script>
</head>
<body>
<div class="wrapper">
<img src="eris.png" align="middle">
<form action="insert.php" method="post">
Firstname: <input type="text" size="16" name="firstname">
Lastname: <input type="text" size="16" name="lastname">
Age: <input type="text" size="1" maxlength="3" name="age">
<input type="submit" class="button">
</form>
</div>
</body>
insert.php is as follows:
<html>
<head>
<link rel="stylesheet" type="text/css" href="insert.css">
<title>MySQL Database Creation System</title>
</head>
<body>
<div class="wrapper">
<img src='eris.png' align='middle'>
<?php
if ( (trim($_POST['firstname']) == "") || (trim($_POST['lastname']) == "") || (trim($_POST['age']) == "") )
{
echo "<p>ERROR: All fields must be completed</p>";
echo "<p><a href='form.php'>Return to Form</a></p>";
}
else
{
$con=mysqli_connect("localhost","test","test","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "<br>Failed to connect to MySQL: " . mysqli_connect_error();
}
// escape variables for security
$firstname = mysqli_real_escape_string($_POST['firstname']);
$lastname = mysqli_real_escape_string($_POST['lastname']);
$age = mysqli_real_escape_string($_POST['age']);
$sql="INSERT INTO Persons (FirstName, LastName, Age)
VALUES ('$firstname', '$lastname', '$age')";
if (!mysqli_query($con,$sql))
{
die('<br>Error: ' . mysqli_error($con));
}
mysqli_close($con);
echo "<p>New item added.</p>";
echo "<p><a href='form.php'>Return to Form</a></p>";
}
?>
</div>
</body>
Thanks in advance for any assistance you can give.
I hope I get the point. In this case you are near. Just merge your scripts like this:
<?php
// check if there is a post request ...
// if not - nothing happens
if(!empty($_POST))
{
if ( (trim($_POST['firstname']) == "") || (trim($_POST['lastname']) == "") || (trim($_POST['age']) == "") )
{
echo "<p>ERROR: All fields must be completed</p>";
echo "<p><a href='form.php'>Return to Form</a></p>";
}
else
{
// your inser code
$con=mysqli_connect("localhost","test","test","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "<br>Failed to connect to MySQL: " . mysqli_connect_error();
}
// escape variables for security
$firstname = mysqli_real_escape_string($_POST['firstname']);
$lastname = mysqli_real_escape_string($_POST['lastname']);
$age = mysqli_real_escape_string($_POST['age']);
$sql="INSERT INTO Persons (FirstName, LastName, Age)
VALUES ('$firstname', '$lastname', '$age')";
if (!mysqli_query($con,$sql))
{
die('<br>Error: ' . mysqli_error($con));
}
mysqli_close($con);
echo "<p>New item added.</p>";
echo "<p><a href='form.php'>Return to Form</a></p>";
}
}
?>
<html>
<head>
<link rel="stylesheet" type="text/css" href="form.css">
<title>MySQL Database Creation System</title>
<script src="jquery-1.11.0.min.js"></script>
</head>
<body>
<div class="wrapper">
<img src="eris.png" align="middle">
<!-- change insert.php to form.php -->
<form action="form.php" method="post">
Firstname: <input type="text" size="16" name="firstname">
Lastname: <input type="text" size="16" name="lastname">
Age: <input type="text" size="1" maxlength="3" name="age">
<input type="submit" class="button">
</form>
</div>
I hope that is near your expectations.
Restore your form.php like below -
What have I done here -
1) <form action="insert.php" method="post">
TO
<form action="" method="post">
2) Added all of your php code in form.php
<?php
if ( (trim($_POST['firstname']) == "") || (trim($_POST['lastname']) == "") || (trim($_POST['age']) == "") )
{
echo "<p>ERROR: All fields must be completed</p>";
echo "<p><a href='form.php'>Return to Form</a></p>";
}
else
{
$con=mysqli_connect("localhost","test","test","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "<br>Failed to connect to MySQL: " . mysqli_connect_error();
}
// escape variables for security
$firstname = mysqli_real_escape_string($_POST['firstname']);
$lastname = mysqli_real_escape_string($_POST['lastname']);
$age = mysqli_real_escape_string($_POST['age']);
$sql="INSERT INTO Persons (FirstName, LastName, Age)
VALUES ('$firstname', '$lastname', '$age')";
if (!mysqli_query($con,$sql))
{
die('<br>Error: ' . mysqli_error($con));
}
mysqli_close($con);
echo "<p>New item added.</p>";
echo "<p><a href='form.php'>Return to Form</a></p>";
}
?>
<html>
<head>
<link rel="stylesheet" type="text/css" href="form.css">
<title>MySQL Database Creation System</title>
<script src="jquery-1.11.0.min.js"></script>
</head>
<body>
<div class="wrapper">
<img src="eris.png" align="middle">
<form action="" method="post">
Firstname: <input type="text" size="16" name="firstname">
Lastname: <input type="text" size="16" name="lastname">
Age: <input type="text" size="1" maxlength="3" name="age">
<input type="submit" class="button">
</form>
</div>
</body>
Then Your form page should like this.
<html>
<head>
<link rel="stylesheet" type="text/css" href="form.css">
<title>MySQL Database Creation System</title>
<script src="jquery-1.11.0.min.js"></script>
</head>
<body>
<div class="wrapper">
<img src="eris.png" align="middle">
<form action="" method="post">
Firstname: <input type="text" size="16" name="firstname">
Lastname: <input type="text" size="16" name="lastname">
Age: <input type="text" size="1" maxlength="3" name="age">
<input type="submit" class="button">
</form>
</div>
</body>
<?php
if ( (trim($_POST['firstname']) == "") || (trim($_POST['lastname']) == "") || (trim($_POST['age']) == "") )
{
echo "<p>ERROR: All fields must be completed</p>";
echo "<p><a href='form.php'>Return to Form</a></p>";
}
else
{
$con=mysqli_connect("localhost","test","test","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "<br>Failed to connect to MySQL: " . mysqli_connect_error();
}
// escape variables for security
$firstname = mysqli_real_escape_string($_POST['firstname']);
$lastname = mysqli_real_escape_string($_POST['lastname']);
$age = mysqli_real_escape_string($_POST['age']);
$sql="INSERT INTO Persons (FirstName, LastName, Age)
VALUES ('$firstname', '$lastname', '$age')";
if (!mysqli_query($con,$sql))
{
die('<br>Error: ' . mysqli_error($con));
}
mysqli_close($con);
echo "<p>New item added.</p>";
echo "<p><a href='form.php'>Return to Form</a></p>";
}
?>
Thanx