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.
Related
I want to set a url parameter by using uniqid function in php, I get the unique numbers and place them in my database by useing them in a hidden input form. I try to make it so, at the start of the script $number is set to a uniqid which I placed in the hidden input so it will be posted into the database and I can use the same variable to create a href link.
The problem I'm having is that the value stored in my database is not the same as the value stored in the number variable used in the href link which renders the link useless. How do I get both the values equal is there a better way to do what I'm trying to do?
I have tried putting uniqid() in a function
<?php
$servername = "localhost";
$username = "root";
$password = "";
$homeDB = "homeDB";
$conn = new mysqli($servername, $username, $password, $homeDB);
if($conn->connect_error) {
die("failed to connect to server".$conn->connect_error);
}
$number = uniqid();
if(isset($_POST["namn"])) {
$sql = "INSERT INTO information (firstname, lastname, urlID)
VALUES ('".$_POST["namn"]."','".$_POST["efternamn"]."',
'".$_POST["hide"]."')";
if($conn->query($sql)== TRUE){
$link = "http://localhost/sqltutorial/execute.php?id=".$number;
} else {
echo "failed";
}
echo $link;
}
html
<html>
<body>
<form method="post" action="home.php">
<input type="text" name="namn"> <br>
<input type="text" name= "efternamn"><br>
<input type="hidden" value="<?php $number ?>" name="hide">
<input type="submit" >
</form>
<br>
</body>
</html>
I get different values on the link that is echoed and the value stored in my database ( I know this form is not secure )
I think you just need to use the $_POST['hide'] value on the link.
It would also be better to echo the link only if it has been created.
Where you have the echo currently, it is possible to echo the $link variable even if it was not been created!
<?php
$servername = "localhost";
$username = "root";
$password = "";
$homeDB = "homeDB";
$conn = new mysqli($servername, $username, $password, $homeDB);
if($conn->connect_error) {
die("failed to connect to server".$conn->connect_error);
}
$number = uniqid();
if(isset($_POST["namn"])) {
$sql = "INSERT INTO information (firstname, lastname, urlID)
VALUES ('".$_POST["namn"]."','".$_POST["efternamn"]."',
'".$_POST["hide"]."')";
if($conn->query($sql)== TRUE){
$link = "http://localhost/sqltutorial/execute.php?id=$_POST[hide]";
// line moved to here
echo $link;
} else {
echo "failed";
}
}
The problem is that when the postback runs, you also run the line $number = uniqid(); again. So the final number which is output is not the one you placed in the hidden field.
Now, you could write
$link = "http://localhost/sqltutorial/execute.php?id=".$_POST["hide"];
and it would output the number which was passed in the POST variable.
Or you could just wait until the postback has happened to generate the unique ID, and use that in both the database call and the output. This saves a) a round-trip for the variable to the browser and back to the server, and b) anyone trying to tamper with the form data. So move the number creation code inside the if:
if(isset($_POST["namn"])) {
$number = uniqid();
...and then replace both references to $_POST["hide"] with $number instead. You can also remove the hidden field from your form.
One final alternative suggestion: Do you even need to do this? I assume your database table has an auto_increment integer field as the primary key? Why not just use the value already being generated by the database as the value for your link?
if($conn->query($sql)== TRUE){
$link = "http://localhost/sqltutorial/execute.php?id=".$conn->insert_id;
would get the auto-generated ID of the last row you inserted and use that in the link instead. See also documentation
I don't see any great purpose in creating a second ID for your row (especially since uniqid() does not promise to always give you a completely unique value), unless you have some specific reason?
So, you want to create a row and redirect on that link after creating.
Steps:
1) First get the next auto increment value for this informations table by this function and store it in $number.
$stmt = $this->db->prepare("SHOW TABLE STATUS LIKE 'informations'");
$stmt->execute();
$result = $stmt->fetchAll();
foreach ($result as $row) {
$number = $row[10];
}
2) Now do inserting, and after insert you'll get the same autoincrement ID and do everything with that.
Hope, it will help.
NB: You can make a function to grab that auto Increment ID for any table also.
** EDIT: I resolved the issue on my own. Thanks for all your help. **
I'm trying to insert image files to my database for testing, and found that my code stopped working (it was able to do what it did before).
When I submit the image to the database it appends the image id, but not the 'username' and 'img_name'(filename) fields - these two fields just show up as empty strings. Can you tell me what's wrong with my code and how I can fix this? Your help is very appreciated
This is a summary of my database:
Database Name: photos
Table Name: images
Row Names: id[primary key], username, img_name
And my HTML and PHP codes for uploading image file to the database:
<form method="post" action="uploadindex5.php" enctype="multipart/form-data">
<input type="file" name="membimg">
<input type="submit" name="membupload">
</form>
if (isset($_POST['membupload'])) {
$username = $_SESSION['username'];
$membupload = $_POST['membupload'];
$membimg = $_POST['membimg']['name'];
$membtarg = "images/".basename($_FILES['membimg']['name']);
$membmuf = move_uploaded_file($_FILES['membimg']['tmp_name'], $membtarg);
$servername = "localhost";
$sroot = "root";
$password = "";
$dbname = "photos";
$conn = mysqli_connect($servername,$sroot,$password,$dbname);
if (mysqli_connect_errno()) {
throw new Exception(mysqli_connect_error(), mysqli_connect_errno());
}
$sql = "INSERT INTO images (username, img_name) VALUES ('$username', '$membimg')";
$result = mysqli_query($conn, $sql);
if ($membmuf) {
$msg = "Image uploaded";
} else {
$msg = "Upload failed";
}
}
I'd put dummy values in for the session and post values just hard code it and see if the PHP code is working and then determine if those variables are even set once i verified my php code works properly. Once you hard code those questionable variables then you can run the PHP page without submiting it with the form or ajax or however you are calling it. The PHP page will report the errors if you have PHP error reporting on. Javascript console may even tell you if there is a 500 internal server error which indicates the PHP script isn't working.
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.
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 a MySQL database with a user called admin (and password admin). I am using this to test my configuration. When I click login, nothing happens. Can anyone see if I've done something wrong?
Here is my logon form:
<form action="loginProcess.php" method="POST">
Username: <input type='text' name='username'></br>
<!-- input type password makes the password hidden as it is typed -->
Password: <input type='password' name='password'></br>
<input type='submit' value='Login'/>
</form>
</br>
</br>
<!-- Register New User -->
<form action="register.php" method="POST"> </br>
Not Registered?<input type='submit' value='Click Here To Register'/>
</form>
This form takes you to this loginProcess.php file:
<?php
ob_start();
session_start();
// Include database connection and select database UFPProducts
include "./shopdb/connection.php";
?>
<?php
//
// (2) Collect data from form and save in variables
// real escape string to protect from SQLi attacks
$username=mysql_real_escape_string(htmlentities($_POST['username']));
$password=mysql_real_escape_string(htmlentities($_POST['password']));
// (3) Create query of the form below to search the user table
// "SELECT * FROM Users WHERE UserName='$username' AND Password='$password'"
$query = "SELECT * FROM USERS where Username='$username' AND Password='$password'";
$result = mysql_query($query) or die (mysql_error());
// (3) Run query through connection
// (4) Check result of query using code below
// if rows found set authenticated user to the user name entered
if (mysql_num_rows($result) > 0) {
$_SESSION["authenticatedUser"] = $username;
// Relocate to the logged-in page
header("Location: ./login/loggedOn.php");
}
else
// login failed redirect back to login page with error message
{
$_SESSION["message"] = "Could not connect as $username " ;
header("Location: login.php");
}
?>
And here is my connection.php file just incase anyone wants to see:
<?php
//*** "die()" will exit the script and show an error if something goes wrong with the "connect" or "select" functions.
//*** A "mysql_connect()" error usually means your connection specific details are wrong
//*** A "mysql_select_db()" error usually means the database does not exist.
// Place db host name. Usually is "localhost" but sometimes a more direct string is needed
$db_host = "localhost";
// Place the username for the MySQL database here
$db_username = "root";
// Place the password for the MySQL database here
$db_pass = "";
// Place the name for the MySQL database here
$db_name = "UFPProducts";
$connect = mysql_connect("$db_host","$db_username","$db_pass") or die(mysql_error());
mysql_select_db("$db_name") or die("there is no database with that name");
// echo "<center>You are successfully connected to the Under5Pounds database.</center><br>";
?>
I'm not getting any error messages right now, it just doesn't do anything once I type in the username + password and click login.
try this code in loginProcess.php
$username=$_POST['username'];
$password=$_POST['password'];
I think you should remove
ob_start();
from the first line of loginProcess.php file, it has nothing to do there (unless tell me the good reason) and it blocks data to be sent to the browser