I'll be honest in saying I'm a rookie coder who knows the basics but is trying to learn more, this issue is also the reason I made an account as well as it's really stumped me. Lots of my code is temporary and I'm planning to streamline it later as well as adding features such as asterisks replacing the password input.
The desired outcome of my code is that the value of the variables below should be compared against those in my database table depending on the value of $type. The problem I'm encountering is that no entries are added to my database table. I'm unsure of where the problem lies within my code and I could do with a point in the right direction, this is my first application of prepared statements so I might be using them incorrectly
Main script:
<?php
include connect.db;
//These are normally user inputs from a form in another file.
$type = "students";
$username = "usernametest";
$password = "passwordtest";
$email = "emailtest";
//the connect global initilizes a connection between my database.
$query = $GLOBALS["conn"]->query("SELECT * FROM '$type' WHERE (username = '$username') OR (password = '$password') OR (email = '$email')");
if (mysqli_num_rows($query) == false) {
$stmt = $GLOBALS["conn"]->prepare("INSERT INTO ? (username, password, email) VALUES (?,?,?)");
$stmt->bind_param("ssss", $type, $username, $password, $email);
$stmt->execute();
$stmt->close();
echo "User Registered";
}
else {
echo "Username, password or email are already used";
}
?>
Connection Script:
<?php
//Identifies the databases details.
//Identifies the servername the database is created in
$servername = "localhost";
//Identifies the databases username
$username = "htmltes7";
//Identifies the database password
$password = "(mypassword)";
//Identified the afformentioned databasename
$dbname = "htmltes7_dbname";
/*Creates a new global variable which opens a connection between my database
using the variables above */
$GLOBALS["conn"] = new mysqli($servername, $username, $password, $dbname);
/*IF the connection cannot be made then the equilivent of exit() occours
in the form of die(). An error message is displayed containing information
on the error that occoured using mysqli_connect_error.*/
if (!$GLOBALS["conn"]) {
die("Connection failed: " . mysqli_connect_error());
}
?>
edit: Sorry about my poor formatting and incorrect tag usage first time round, like I said I'm new to both sql and stack overflow and kinda jumped the gun to ask my question. I've made changes based on the feedback and won't reproduce the same mistake in future.
Try to see the errors
error_reporting(E_ALL);
ini_set('display_errors', 1);
if (!$stmt) {
echo "\nPDO::errorInfo():\n";
print_r($dbh->errorInfo());
}
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I'm just trying to store the integer (with id as id) that is entered by the user through html form, in database of phpmyadmin using php and mysql . I'm new to mysql and php. I'm sure that something wrong with the database connection code of php only or mysql queries. Database name is testdb and the table name is testdbtable.
My code is below.
<?php
if (isset($_POST['id'])) {
$integ = $_POST['id'];
}
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "testdb";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO testdbtable (id)
VALUES ('$integ')";
$conn->close();
?>
<!DOCTYPE html>
<html>
<head>
<title>SAMPLE TEST2</title>
</head>
<body>
<form method="post">
<label >Enter your integer:</label>
<input type="number" id="id" name="id">
<br>
<br>
<button type="submit">Submit</button>
</form>
You're defining the query but never run it.
Try this:
$sql = "INSERT INTO testdbtable (id) VALUES ('$integ')";
$conn->query($sql);
As Paul T. said, move the } to the end of the script. Otherwise, even if condition is false, You will just prevent definig $integ, but still running all the rest of the code.
Also, user Prepared Statements to make it more secure.
if (isset($_POST['id'])) {
$integ = $_POST['id'];
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "testdb";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Use prepared statements to make it more secure
$sql = "INSERT INTO testdbtable (id) VALUES (?)";
// Prepare statement and bind params
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $integ);
// Execute statement
$stmt->execute();
$conn->close();
}
Take a look at Should we ever check for mysqli_connect() errors manually? as #Dharman commented to stop manually error checking.
Before
$conn->close();
you need to run
$conn->query($sql);
This will actually execute the query.
But this is not the end of the story. You have other issues:
Your code is vulnerable to SQL injection attack. Consider changing the line:
$integ = $_POST['id'];
to
$integ = (int)$_POST['id'];
or (better!) learn how to work with prepared statements.
The query will still be invalid. I bet that the datatype of the column "id" in the "testdbtable" is INT and therefore you should not put quotes around its value. So the $sql variable should be:
$sql = "INSERT INTO testdbtable (id) VALUES ($integ)";
And one more thing - move all query-related code inside the if statement. You should not execute the query if the POST variable is not set.
Your <form> tag has no "action" attribute. You should include it so it do an actual post...
I have a game where you can submit your score to a database, but for some reason the submission keeps getting triggered twice. Every entry is doubled. I've seen similar problems posted here, and the solution had to do with the if/else check at the end, but I don't see a problem.
Is it my PHP code that's duplicating the entries or my game application?
<?php
$servername = "xxx";
$username = "xxx";
$password = "xxx";
$dbname = "xxx";
$port = "xxx";
$link = mysqli_connect($servername, $username, $password, $dbname, $port);
// Security
$playerInitials = mysqli_real_escape_string($link,$_REQUEST['initials']);
$playerEmail = mysqli_real_escape_string($link,$_REQUEST['email']);
$playerScore = mysqli_real_escape_string($link,$_REQUEST['score']);
// Convert Initials to Upper Case
$playerInitialsUC = strtoupper($playerInitials);
$sql = "INSERT INTO xmas (initials, email, score)
VALUES ('$playerInitialsUC', '$playerEmail', '$playerScore')";
if(mysqli_query($link, $sql)){
echo "Records added successfully.";
} else{
echo "ERROR: " . mysqli_error($link);
}
mysqli_close($link);
?>
You can try this in your sql query:
REPLACE does exactly what INSERT does but it won't let sql query double a record.
REPLACE into xmas (initials, email, score) values('$playerInitialsUC', '$playerEmail', '$playerScore')
You can tell me if it didn't work or it's not what you want :)
Or you can add this query to the end of your code to make the rows unique:(not sure about this one):
ALTER TABLE xmas ADD UNIQUE( `initials`, `email`, `score`)
Yeah, turns out the my submit button was a little too sensitive and clicks were registering multiple times. Thanks everybody.
I made a procedure in mySql. It looks like this.
I called this procedure from php.
After this call the table still remains empty and I do not know why.
Problems that I have checked:
variable names
connection
syntax (I think is the right syntax)
UPDATE: Php code
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbName = "shoppingcartdb";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbName);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO address (Address, PostalCode, City, County, Phone, Fax)
VALUES ('".$_POST["address"]."', '".$_POST["p_code"]."', '".$_POST["city_sector"]."', '".$_POST["county"]."', '".$_POST["phone"]."', '".$_POST["fax"]."')";
$conn->query($sql);
$sql = "CALL Insert_User('".$_POST["username"]."', '".$_POST["f_name"]."', '".$_POST["l_name"]."', '".$_POST["psw"]."', '".$_POST["email"]."')";
if(!$conn->query($sql))
echo "failed";
$conn->close();
?>
UPDATE: Procedure
Code ScreenShot
You have mixed up the input and local variables with session variables. #id_add is not the same as id_add, nor is #f_name the same ad f_name. Therefore you are trying to insert empty values into your table.
I cannot see on the screenshot if the delimiter was appropriatly set before and after the query. Pls check that.
Check the stored proc by testing it from phpmyadmin.
I have this form:
<form action="contactus.php" method="post">
<select name="formTitle">
<option value="">Select...</option>
<option value="M">Mr</option>
<option value="F">Mrs</option>
</select>
<p><b>Name</b></p>
<input type="text" name="formName" maxlength="50"/>
<p><b>Enquiry</b></p>
<input type="text" name="formEnquiry" maxlength="500"/>
</select>
<p><input type="submit" name="formSubmit" value="Submit"/></p>
And I have a MySQL database (called 'contacts') with a table (called 'enquiries') with three columns; 'Title', 'Name', 'Enquiry'.
The database has no password or anything. It's just a localhost with a 'root' password.
What kind of PHP would I need to send the data from this HTML form to the MySQL database?
I can help you in this problem.
So, just add the following code to your php file contactus.php.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "contacts";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(isset($_POST['formSubmit'])) {
$formTitle = $_POST['formTitle'];
$formName = $_POST['formName'];
$formEnquiry = $_POST['formEnquiry'];
$sql = "INSERT INTO enquiries (Title, Name, Enquiry) VALUES ('$formTitle', '$formName', '$formEnquiry')";
$conn->query($sql);
?>
I hope this will solve your problem.
SIMPLE ANSWER: MySQL
A LITTLE BIT MORE DEVELOPED ANSWER:
MySQL is in basic terms the combination of PHP and SQL to create an easy way to do various actions to a database, which include:
Create table
Query table
Update table
and much more
There are variations of MySQL, including MySQLi and MySQL (PDO).
an example of connecting to your database via MySQL (PDO) would be:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$myDB = "databasename";
try {
$conn = new PDO("mysql:host=$servername;dbname=$myDB", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
//insert code there that you want to execute...
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?>
you mentioned that you don't have a password, so you might just leave the "password" slot empty ("") I suppose, though this is very insecure and I recommend you place a password.
In the code above, there is a comment that says:
//insert code there that you want to execute...
Here you would include code that would probably do actions similar to the ones mentioned above (query table, update table, etc). An example of code similar to that would be:
//htmlspecialchars takes out special characters that might
//exist in the posted information if someone were trying
//to hack your site via sql injection
$formTitle = htmlspecialchars($_POST['formTitle']);
$formName = htmlspecialchars($_POST['formName']);
$formEnquiry = htmlspecialchars($_POST['formEnquiry']);
$sql = "INSERT INTO enquiries (Title, Name, Enquiry) VALUES (formTitleBinded, formNameBinded, formEnquiryBinded)";
$sqlPrepared = $conn->prepare($sql);
$sqlPrepared->bindParam(':formTitleBinded',$formTitle);
$sqlPrepared->bindParam(':formNameBinded',$formName);
$sqlPrepared->bindParam('formEnquiryBinded',$formEnquiry);
$sqlPrepared->execute();
The previous code both sanitizes your input and inserts a row into your table with that information.
Let me know if that helped!
EDITED: My answer has been edited with parameter binding included to prevent SQL Injection.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
So trying to insert some data from a PHP page into my SQL database. This page is ONLY accessible via myself so I'm not worried about it being accessed or SQL injectable etc. My issue is no matter what code I use it doesn't go into the database. I've tried coding it myself, using template codes, taking from php.net etc nothing has worked!
It now redirects me with the success message but still nothing in the database.
Code will be put below and I'll edit some of my details for privacy reasons.
<?php
require connect.php
// If the values are posted, insert them into the database.
if (isset($_POST['username']) && isset($_POST['password'])){
$username = $_POST['username'];
$isadminB = $_POST['isadmin'];
$password = $_POST['password'];
$query = "INSERT INTO `users` (user_name, password, isadmin) VALUES ('$username', '$password', '$isadminB')";
$result = mysql_query($query);
if($result){
$msg = "User Created Successfully.";
}
}
$link = mysql_connect("localhost", "root", "password");
echo mysql_errno($link) . ": " . mysql_error($link). "\n";
The echo mysql_errno($link) . ": " . mysql_error($link). "\n"; was the code that gave me error code 0?
As requested the code for the form from my previous page.
<form action="account_create_submit.php" method="post">
Username: <input type="text" name="username" id="username"> <br /><br />
Password: <input type="password" name="password" id="password"> <br /><br />
<span id="isadmin">Is Admin: Yes<input type="radio" name="isadmin" id="1" value="1"> | No<input type="radio" name="isadmin" id="0" value="0"><br /></span>
<span id="submit"><input type="submit" value="Create Account"></span>
</form>
Ok so changed the form code so method is now POST. Great! All data is being read correctly although that wasn't my issue as even typing in hard data for the code to submit wasn't working at least its a future issue resolved already. The new error code is no longer 0 but rather the following:
1064: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''user_name', 'password', 'isadmin') VALUES ('testZ', 'lol', '1')' at line 1
Connect.php
<?php
$connection = mysql_connect('localhost', 'root', 'password');
if (!$connection){
die("Database Connection Failed" . mysql_error());
}
$select_db = mysql_select_db('Default_DB');
if (!$select_db){
die("Database Selection Failed" . mysql_error());
}
Firstly, for those of you getting the misconception about password for a column name:
Sure, it's MySQL "keyword", but not a "reserved" word; more specifically, it is a function (see ref). Notice there is no (R) next to the "function (keyword) name": https://dev.mysql.com/doc/refman/5.5/en/keywords.html therefore it's perfectly valid as a column name.
Ref: https://dev.mysql.com/doc/refman/5.1/en/encryption-functions.html#function_password
Ticks are only required if it is used in order to prevent it from being recognized as a "function", which it clearly is not in the OP's case. So, get your information and facts straight.
More specifically, if a table named as PASSWORD and without spaces between the table name and the column declaration:
I.e.: INSERT INTO PASSWORD(col_a, col_b, col_c) VALUES ('var_a', 'var_b', 'var_c')
which would throw a syntax error, since the table name is considered as being a function.
Therefore, the proper syntax would need to read as
INSERT INTO `PASSWORD` (col_a, col_b, col_c) VALUES ('var_a', 'var_b', 'var_c')
(Edit:) To answer the present question; you're using $connection in your connection, but querying with $link along with the missing db variables passed to your query and the quotes/semi-colon I've already outlined here.
That's if you want to get that code of yours going, but I highly discourage it. You're using a deprecated MySQL library and MD5 as you stated. All old technology that is no longer safe to be used, nor will it be supported in future PHP releases.
You're missing a semi-colon here require connect.php and quotes.
That should read as require "connect.php";
You should also remove this:
$link = mysql_connect("localhost", "root", "password");
echo mysql_errno($link) . ": " . mysql_error($link). "\n";
you're already trying to include a connection file.
Use this in your connection file: (modified, using connection variable connection parameter)
$connection = mysql_connect('localhost', 'root', 'password');
if (!$connection){
die("Database Connection Failed" . mysql_error());
}
$select_db = mysql_select_db('Default_DB', $connection);
if (!$select_db){
die("Database Selection Failed" . mysql_error());
}
and pass the $connection to your query as the 2nd parameter.
$result = mysql_query($query, $connection);
Add error reporting to the top of your file(s) right after your opening PHP tag
for example <?php error_reporting(E_ALL); ini_set('display_errors', 1); then the rest of your code, to see if it yields anything.
Also add or die(mysql_error()) to mysql_query().
If that still gives you a hard time, you will need to escape your data.
I.e.:
$username = mysql_real_escape_string($_POST['username'], $connection);
and do the same for the others.
Use a safer method: (originally posted answer)
May as well just do a total rewrite and using mysqli_ with prepared statements.
Fill in the credentials for your own.
Sidenote: You may have to replace the last s for an i for the $isadminB that's IF that column is an int.
$link = new mysqli('localhost', 'root', 'password', 'demo');
if ($link->connect_errno) {
throw new Exception($link->connect_error, $link->connect_errno);
}
if (!empty($_POST['username']) && !empty($_POST['password'])){
$username = $_POST['username'];
$isadminB = $_POST['isadmin'];
$password = $_POST['password'];
// now prepare an INSERT statement
if (!$stmt = $link->prepare('INSERT INTO `users`
(`user_name`, `password`, `isadmin`)
VALUES (?, ?, ?)')) {
throw new Exception($link->error, $link->errno);
}
// bind parameters
$stmt->bind_param('sss', $username, $password, $isadminB);
if (!$stmt->execute()) {
throw new Exception($stmt->error, $stmt->errno);
}
}
else{
echo "Nothing is set, or something is empty.";
}
I noticed you may be storing passwords in plain text. If this is the case, it is highly discouraged.
I recommend you use CRYPT_BLOWFISH or PHP 5.5's password_hash() function. For PHP < 5.5 use the password_hash() compatibility pack.
You can also use this PDO example pulled from one of ircmaxell's answers:
Just use a library. Seriously. They exist for a reason.
PHP 5.5+: use password_hash()
PHP 5.3.7+: use password-compat (a compatibility pack for above)
All others: use phpass
Don't do it yourself. If you're creating your own salt, YOU'RE DOING IT WRONG. You should be using a library that handles that for you.
$dbh = new PDO(...);
$username = $_POST["username"];
$email = $_POST["email"];
$password = $_POST["password"];
$hash = password_hash($password, PASSWORD_DEFAULT);
$stmt = $dbh->prepare("insert into users set username=?, email=?, password=?");
$stmt->execute([$username, $email, $hash]);
And on login:
$sql = "SELECT * FROM users WHERE username = ?";
$stmt = $dbh->prepare($sql);
$result = $stmt->execute([$_POST['username']]);
$users = $result->fetchAll();
if (isset($users[0]) {
if (password_verify($_POST['password'], $users[0]->password) {
// valid login
} else {
// invalid password
}
} else {
// invalid username
}
You are using "get" as your form submission method. "post" variables won't be recognized.
Also...
It looks like you're missing the second parameter of your mysql_query() function which is your link identifier to the MySQL connection. I'm assuming you've created the connection in connection.php.
Typically, the mysql_query() function would be
$result = mysql_query($query, $conn);
with $conn having been pre-defined in your connection.php file.
password is a special word in MySQL, and it might be necessary to put the word in quotes like `password`.
Why are you putting all the information from the form in the link on submit? ex: account_create_submit.php?username=myusername&password=mypassword&isadmin=0
I can see that $username = $_POST['username']; doesn't match the username in your query string.
$query = "INSERT INTOusers(user_name, password, isadmin) VALUES ('$username', '$password', '$isadminB')";
While your fixing that why don't you just make $isadminB and $_POST['isadmin'] the same. Use 'isadminB' in both places.
Check that out and see what happens!