So, I have a form with some field in my page. For example - auth.php. The data in fields of this form recieved by calling some php function, that gives this data from MySQL DB. The code:
<?php
include 'functions.php';
$result=array();
$result = GetEntries();
$json = json_encode($result);
?>
The data inserting in fields by this code:
<script type="text/javascript">
function nextFunc(){
var name2 = <?php echo $json;?>;
document.getElementById("rname").value = name2[currententry]['Name'];
}
</script>
But how to realize mechanism of insertion some entry to my MySQL DB. For example, user pressed the ADD button on my Form, fill the field "Name" by his own data and press SAVE button - i want to save this user data directly in my MySQL DB.
Please help!
To achieve this, you'll need to follow a few steps:
create the html form
form.html
<form action="submit.php" method="post">
<label>
Name <input type="text" name="name" />
</label>
<input type="submit" value="Save" />
</form>
create submit page
submit.php
<?php
$name = strip_tags($_POST['name']);
// connect to database
$con = new mysqli('localhost', 'db_username', 'db_password', 'db_name');
if ($con->connect_errno) {
printf("Failed to connect to mysql: %s", $con->connect_error);
}
// prepare the query
$sql = sprintf("INSERT INTO my_table SET name = '%s'", $name);
// insert into database
$query = $con->query($sql) or die($con->error);
// view ID of last inserted row in the database
print_r('Last inserted ID: '.$con->insert_id);
Now you should be able to have your data in database.
Please have a look at this example on how to connect to database http://docs.kisphp.net/database-connect/
Instead of mysqli you may/should use PDO.
P.S.
In your code:
include 'functions.php';
$result=array(); // this line should not be here
$result = GetEntries(); // is overwritten by this one
$json = json_encode($result);
Is always a good practice to follow some principles:
function names starts with lowercase
class names starts with uppercase
do not use ?> in php files that contains only PHP code
indentation of all code is not necessary.
and so on.
you may find here more details http://www.php-fig.org/psr/psr-2/
P.P.S.
This is basic usage. Once you understand the principle you can extend it to ajax. Create an ajax function that will submit the form data to submit.php file.
Related
I built an html page with some options to insert details for a friends club.
I used an INSERT query and it worked. I want to add other queries like an UPDATE, DELETE, SELECT etc.
this is the php file:
<?php
//Input posted data.
$Fname = $_POST["Fname"];
$Lname = $_POST["Lname"];
$Date = $_POST["Date"];
$Mail = $_POST["Mail"];
$Pass = $_POST["Pass"];
// Create connection
$conn = mysqli_connect('localhost','root',"");
//Check if the connection was opened, if not prompt the error to the page.
if (!$conn)
{
die('Could not connect: ' . mysqli_error());
}
//Select the data base.
mysqli_select_db($conn, "club");
//Set the character set to utf-8 to allow hebrew.
mysqli_query($conn, "SET NAMES 'utf8'");
//SQL query - user Details
$sql = "INSERT INTO customers (Fname, Lname, Mail, Date, Pass)
VALUES('$Fname','$Lname','$Mail','$Date','$Pass')";
//Run SQL query
$results = mysqli_query($conn, $sql) or die (mysqli_connect_errno());
//Close the SQL connection.
mysqli_close($conn);
?>
I want to use those queries in the same file.
how can I do that?
Should I add a new form on the same page?
For example <form name="input" action="Update.php" method="POST"> to direct it to the Update.php file?
can I use more than one form at the same html file?
I've created this form for the Update button on the page to Update.php file but it doesn't work. It just adds the details and does not update them, although I used the UPDATE query.
You take all your PHP code and put it in the head of the form's page, then wrap it all inside
if(isset($_POST['submit-button-name'])){
//YOUR PHP CODE
}
Now you for each submit-button-name you make an if statement with it, for example
if(isset($_POST['insert'])){
//YOUR INSERT QUERY
}
if(isset($_POST['update'])){
//YOUR UPDATE QUERY
}
if(isset($_POST['delete'])){
//YOUR DELETE QUERY
}
That if you for example have 3 buttons like the following
<button type='submit' name='insert'>INSERT</button>
<button type='submit' name='update'>UPDATE</button>
<button type='submit' name='delete'>DELETE</button>
Inside the form, of course the UPDATE & DELETE queries require an identifier to find the row
WHERE id = $id
So it depends how you will implement the buttons in one form.
I'm learning PHP and SQL by running MAMP on my Mac, and accessing the database through phpMyAdmin.
I've made one PHP script to add a new user to a table, one for comparing inputted data with the table (login) and one to close an account. All of the scripts are very basic and the data isn't sanitized at all, as I'm just getting used to the basics of PHP.
I've noticed that after I run the script for account creation (inserting data), a few seconds after the script is run, a new row is added to the table with an id (which I've set to auto increment) but no other data.
I'm just wondering if the reason for this is something obvious in MySQL that I'm just missing.
The following is the account creation script:
<?php
//Get values from HTML form
$varUsername = $_POST['username'];
$varPassword = $_POST['password'];
$varPasswordHash = password_hash($varPassword, PASSWORD_DEFAULT);
//Establish connection to database
$server = "localhost";
$username = "root";
$password = "root";
$database = "members";
$connection = mysqli_connect($server, $username, $password, $database);
if(!$connection)
{
die("Connection failed: " . mysqli_connect_error());
}
//Send data to database
$action = "INSERT INTO details (USERNAME, PASSWORD) VALUES ('$varUsername', '$varPassword')";
if(mysqli_query($connection, $action))
{
echo 'Account created.';
}
else
{
echo 'Account creation failed: ' . mysqli_error($connection);
}
mysqli_close($connection); //End connection to database
?>
and the HTML form to go with it:
<html>
<body>
<form action="sign_up.php" method="post">
<input type="text" name="username">
<input type="text" name="password">
<input type="submit">
</form>
</body>
</html>
I'm making a guess right now...
I would add an extra if-statement to the script itself. Like this:
if (isset($_POST['submit-form'])) {
// All the above to insert the data into the script...
}
It would make sense if you visit the sign_up.php itself and notice there is a new entry made into your database.
You'll have to modify your HTML a little, to make the if-statement work.
Just add name='submit-form' to the submit button: <input type="submit" name="submit-form">
This will make the script more complete.
Also a little update on the matter as I just read that it adds an empty row after you submit an empty form.
You can check wether the fields are filled in with, guess what, another if-statement:
if (empty($_POST['username'])) {
echo 'Please enter your username...';
} else
if (...)
You do not verify if the POSTed values have anything in them, thus submitting an empty form results in an empty entry in the DB with just the ID.
I would like to know how to make a text box for the user to type and then create a database named after this input.
<?php
/*
code to connect and make a mysql database named after the user input
*/
?>
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<form action=<?php $_SERVER['PHP_SELF']; ?>>
<input type="text" name="databasename">
<input type="submit" name="submit">
</form>
</body>
</html>
It technically depends on the DBMS you use, but just make a SQL query (using MySQL) of "CREATE DATABASE databasename" would do it.
However, unless you're creating a database management tool like PhpMyAdmin, don't do this. You're just asking for users to run amok in your system.
And that's just the basics. I implore you to read the documentation on MySQL
You absolutely have to make sure the user's input is useable and not a hacking attempt or a mistake. So, first you check the input, and then if it's okay, you create a database.
This is assuming you add action="post" in the form. I don't like putting inputs into "get" because then your variable's part of the URL, and some people might try to set bookmarks with it there.
if(isset($_POST['databasename'])) { //this lets us know the form has posted
// 1. Check for acceptable name
$name = $_POST['databasename'];
$name = strtolower($name); //all lowercase (makes things easier to deal with)
$name = preg_replace("/[^a-z]/", '', $name); //get rid of things that aren't letters
if($name != '') {
// 2. Create the database
$mysqli = new mysqli('localhost', 'my_user', 'my_password');
if ($mysqli->connect_error) {
throw new Exception("Connect Error ($mysqli->connect_errno) $mysqli->connect_error");
}
$query = "CREATE DATABASE `$name`";
$mysqli->query($query);
if($mysqli->errno) {
throw new Exception("Error creating database: $mysqli->error");
// I am pretty sure this is enough to catch the error of the database already existing
}
echo "Database $name created.";
} else {
throw new Exception("Invalid name");
}
}
If I were you, I would put this in a try-catch to catch the exceptions and handle them.
As you haven't declared a method for your form it defaults to GET.
$db_name = $_GET['databasename'];
$host="localhost";
$user="username";
$password="pa55word";
$con=mysqli_connect($host,$user,$password);
// Create database
$query="CREATE DATABASE `$db_name`";
if (mysqli_query($con,$query))
{
echo "Database created";
}
else
{
echo "Error creating database...";
}
If the user isn't root though, you need to make sure you have granted the user enough privileges to create a database.
You can use this method to check if there exists a database with same name and through an error else create it and display created successfuly
<?php
if(isset($_POST['submit'])){ //check for the submit button pressed
$dbname=$_POST['db']; //store the database name in php variable
$query= mysqli_connect('localhost','root','')or die("Error establishing connection"); //check for database connectivity
$a="CREATE DATABASE IF NOT EXISTS ".$dbname; //create a database if it doesn't already exist
$q= mysqli_query($query, $a) or die("Database already exist.. please try different name");
echo "Your database ".$dbname." is successfully created";
}
?>
for the html form refer the code below:-
<form method="post" action="">
Enter database name: <input type="text" name="db" /><br/>
<input type="submit" name="submit" value="submit"/>
</form>
I have troubles about php & mysql. I've to retrieve all records from DB1's table and then I have to insert them again to DB2's table.
<?php
require_once 'includes/config.php';
include 'includes/header.php';
if(isset($_POST['go'])){
$query = mysql_query("SELECT id,username,password FROM $db_database1.account")
or die(mysql_error());
echo "Record ".mysql_num_rows($query)." retrieve";
while($result_row = mysql_fetch_array($query, MYSQL_ASSOC)){
$account_ID = $result_row['id'];
$username = $result_row['username'];
$password = $result_row['password'];
$query = mysql_query("INSERT INTO $db_database2.account(uid,username,password) VALUES('$account_ID','$username','$password')")
or die(mysql_error());
$selectId = mysql_insert_id();
}
}
mysql_close($conn);
?>
<div class="wrapper">
<div class="content">
<form method="post" action="<?PHP $_SERVER['PHP_SELF'];?>">
<input type="submit" name="go" value="Go" />
</form>
</div>
<?php include 'includes/footer.php';?>
According to this code just one record was inserted. How can I insert all retrieved records?
To insert records into another table you need one single query, run from mysql console without PHP:
INSERT INTO db_database2.account SELECT id,username,password FROM db_database1.account
Notes on your code
you have to escape strings you are adding to the query
for some reason you are inserting into the same database
asking for the mysql_insert_id() makes no sense as you are apparently inserting a_i id already
there is no use for storing second mysql_query result into variable
yet this variable gets overwritten <- here is the reason your code runs once.
there is no use for echoing $_SERVER['PHP_SELF'] here. just leave form action blank.
yet you are actually leaving form action blank as you just forgot to echo this variable
I see no use for all the form and HTML here. Can't you just run this code without forms?
as it seems that whole mess is just to hash passwords, you need no extra tables then
just simple
UPDATE account SET password = md5(concat(id,username,password));
always have a database backup before such manipulations
I made a small database(1 table) in phpMyAdmin. One of the fields I want to check is "Name".
I want to verify through PHP if a name that user types in a form exists in the database. In the html a list of names from DB appears, but the user might type wrong the name in the form.
The problem is the answer whether it exists or not varies.
I have 2 PHP files:
Connection.php and welcome.php
Connection
<html>
<head>
<title>Project</title>
</head>
<body>
<?php
mysql_connect("localhost","root","");
mysql_select_db("e-card");
$sql=mysql_query("SELECT * FROM person");
$dbname="name";
#$formula_adr="formula_adr";
#$adress="adr";
$line=mysql_fetch_assoc($sql);
echo'Choose a name to whom you send e-card:<br/><br/>';
echo $line[$dbname].'<br/>';
while($line=mysql_fetch_assoc($sql))
echo $line[$dbname].'<br/>';
?>
<form action="welcome.php" method="POST">
Nume: <input type="text" name="fname" />
<input type="submit" value="Verify existance in DB"/>
</form>
</body>
</html>
And welcome:
<?php
mysql_connect("localhost","root","");
mysql_select_db("e-card");
$sql=mysql_query("SELECT * FROM persoana");
$dbname="name";
$formula_adr="formula_adr";
$adresa="adr";
$linie=mysql_fetch_assoc($sql);
if ($_SERVER['REQUEST_METHOD']=='POST' and isset($_POST['fname']))
{
$name = $_POST['fname'];
while($line=mysql_fetch_assoc($sql))
{
if(strcmp($name,$line[$dbname]))
{
echo 'Found';
}
else
{
echo 'This name doesn't exist in DB';
}
}
}
?>
THANK YOU IN ADVANCE ^_-
<?php
mysql_connect(HOST, USERNAME, PASSWORD);
mysql_select_db(DB_NAME);
if($_POST) {
$name = $_POST['fname'];
// check if name exists in db
$sql = "SELECT name FROM person WHERE name=' . mysql_real_escape_string($name) . '";
$query = mysql_query($sql);
if(mysql_num_rows($query) > 0) {
// user exists
} else {
// user does not exist
}
}
The above script will work and will also protect your script against SQL injection by using the built-in mysql_real_escape_string method. I would also recommend against using a wildcard (*) selector when verifying data in this manner as it's a waste of resources to query any additional information that is unused.
Don't get all data from the table to compare for a name.
Do it this way:
$sql=mysql_query("SELECT * FROM persoana where name like '$name%'");
You will get result only if you have a match
I would follow these steps high level steps.
1 - use javascript to initially check on client side that something was entered BEFORE calling the DB. You can use a filter in your javascript to check that form field.
2 - If you verify that something *useful was entered - pass the form field value to another page or object that will parse the value and then query the table.
3 - Use the parsed value against the db table column that contains your data. If records are found, return them.
Use a SQL injection technique to prevent malicious intend by users who may type something evil into your form field.