I need to do an school assigment and I have run into quite few problems, but I don't understand why the code below gives empty values to the table. Only NOW() gets inserted into
the table, otherwise it says Query Empty or something like that. I had the same code on different page and with different table and it worked like a charm.
Regards,
Werner.
<?php
$dbhost = 'localhost';
$dbuser = '';
$dbpass = '';
$pnimi =$_REQUEST['pitsa_nimi'];
$id =$_REQUEST['pitsatyybinimi'];
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$sql = 'INSERT INTO tellimused_pitsad '.
'(pitsa_nimi,aeg,toidutyybi_id)'.
"VALUES ( '$pnimi', NOW(), '$id' )";
mysql_select_db('carl.reinomagi');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
}
echo mysql_error();
echo "Entered data successfully\n";
mysql_close($conn);
header("location:tellimine.php");
?>
This is the previous page ( ordering ) code :
<?php
$tulemus = mysql_query("SELECT * FROM pitsad, pitsatyybid WHERE pitsad.toidutyybi_id = pitsatyybid.id", $dbhandle);
while ($row = mysql_fetch_assoc($tulemus))
{
?>
<tr><form action="telli.php">
<td><? echo $row['pitsa_nimi']; ?></td>
<td><? echo $row['hind']; ?></td>
<td><? echo $row['valmimisaeg']; ?> Minutit</td>
<td><? echo $row['pitsatyybinimi']; ?></td>
<td>
<input type="submit" value="TELLI"/>
</form></td>
</tr>
<?php
}
?>
</table>
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
Here's a better example using PDO. This code is completely safe against SQL Injection, and is better than using mysql_* functions.
Make sure to read the comments and understand the code.
This is not copy/paste ready code!!
<?php
# Database Connection #
try {
$conn = new PDO("mysql:host=localhost;dbname=carl.reinomagi", "root", ""); //Please consider having different credentials.
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); //Throw Exceptions on errors - This disables the need to check for errors, see the catch block below.
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); //True prepared statements.
## Prepreations ##
$pnimi = $_POST["pitsa_nimi"];
$id = $_POST["pitsatyybinimi"]; //Please use $_POST or $_GET rather than $_REQUEST
## Data validation ##
if (empty($pnimi) || empty($id)) {
//One of the variables is empty, return an error to the user.
}
//Few things about this:
//Note the `backticks` around table and column names. This helps readability.
//Also note the placeholders :pnimi and :id, those placeholders for the prepared statement.
$query = "INSERT INTO `tellimused_pitsad` (`pitsa_nimi`, `aeg`, `toibutyybi_id`) VALUES (:pnimi, NOW(), :id);";
$statement = $stmt->prepare($query);
$statement->bindValue(":pnimi", $pnimi); //Bind the values to the placeholders
$statement->bindValue("id", $id);
$statement->execute();
header("Location: tellimine.php");
}
catch (PDOException $e) {
echo "An error has occured! " . $e->getMessage(); //Echo a generic error to all mysql error messages.
}
Related
I have been breaking my head around this html/php/mysqli thing and I can't get it to work. I used several echo statements to see what type of error I am facing but nothing shows up when I am trying to post data into my database.
I have used echo $_POST['name of input']; , print_r($_POST); and only on the 1st one I can see my post. So I think it is posting correctly, right?!
I for some strange reason can't find the problem in my code. I have searched for quiet some time on the web but with little to no result.
This is my HTML:
<html>
<head><title>Test2017</title></head>
<body>
<form action="insert.php" method="post">
<table width="400" border="0" cellspacing="10">
<tr>
<td>voornaam:</td>
<td><input type="text" name="voornaam"></td>
</tr>
<tr>
<td>roepnaam</td>
<td><input type="text" name="roepnaam"></td>
</tr>
<tr>
<td>tussenvoegsel</td>
<td><input type="text" name="tussenvoegsel"></td>
</tr>
<tr>
<td>achternaam</td>
<td><input type="text" name="achternaam"></td>
</tr>
<tr>
<td><input type="submit" value="registreren!"></td>
</tr>
</table>
</form>
</body>
</html>
and this my insert.php, and also at the VALUES i have tried "''",'' and "" but non of that worked.
<?php
$connect=mysqli_connect("localhost","root","usbw","test");
//check connection
if (mysqli_connect_errno()){
echo 'Failed to connect to MySQL:' . mysqli_connect_error();
}
$voornaam= mysqli_real_escape_string($connect, $_POST['voornaam']);
$roepnaam= mysqli_real_escape_string($connect, $_POST['roepnaam']);
$tussenvoegsel= mysqli_real_escape_string($connect, $_POST['tussenvoegsel']);
$achternaam= mysqli_real_escape_string($connect, $_POST['achternaam']);
$sql="INSERT INTO user (voornaam,roepnaam,tussenvoegsel,achternaam) VALUES ('$voornaam','$roepnaam','$tussenvoegsel','$achternaam')";
if (!mysqli_query($connect,$sql)) {
die('Error: ' . mysqli_error($connect));
}
echo "1 record added";
mysqli_close($connect);
?>
You guys are my only help, because I am pulling my hair out for this.
Thank you in advance!
I have typed the HTML code first and I have pasted it everywhere else even in the database. So I would not have a problem like that. It is all lowercase.
I reformatted your original example to use a prepared statement, as this is safer for handling user generated input. I added a try catch around your code to attempt to raise visibility on whatever error you are running into
<?php
// ensure reporting for mysql is on.
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
try {
// Subbing out what you had for db connection to illustrate what each
// of those parameters should point to on your local db
$database = new mysqli('host', 'user', 'password', 'db_schema');
// guessing on whether these are strings.
$voornaam = filter_input(INPUT_POST, 'voornaam', FILTER_SANITIZE_STRING);
$roepnaam = filter_input(INPUT_POST, 'roepnaam', FILTER_SANITIZE_STRING);
$tussenvoegsel = filter_input(INPUT_POST, 'tussenvoegsel', FILTER_SANITIZE_STRING);
$achternaam = filter_input(INPUT_POST, 'achternaam', FILTER_SANITIZE_STRING);
// Formatting for readability, parameterized query
$query = "INSERT INTO user (
voornaam,
roepnaam,
tussenvoegsel,
achternaam
) VALUES ( ?, ?, ?, ?)";
// prepare query statement
$stmt = $database->prepare($query);
// bind parameters and types to statement
$stmt->bind_param('ssss', $voornaam, $roepnaam, $tussenvoegsel, $achternaam);
// execute
$stmt->execute();
echo 'Records added: ' . $stmt->affected_rows;
$stmt->close();
$database->close();
} catch (Exception $e) {
// basic print error to screen error handling, not ideal for
// anything other than testing :)
echo $e->getCode() . ' - ' . $e->getMessage();
}
Ok, we have probably totally confused you now, so try this
<?php
ini_set('display_errors', 1);
ini_set('log_errors',1);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$connect=mysqli_connect("localhost","root","usbw","test");
if (mysqli_connect_errno()){
echo 'Failed to connect to MySQL:' . mysqli_connect_error();
}
// using 4 ? one for each column value in the query
$sql="INSERT INTO user
(voornaam,roepnaam,tussenvoegsel,achternaam)
VALUES (?,?,?,?)";
$stmt = $connect->prepare($sql);
// pass the actual data for each parameter, in order
// the 'ssss' in this case denotes that all 4 params are strings
// they can be s=string, i=integer,b=blob, d=decimal
$stmt->bind_param('ssss',
$_POST['voornaam'],
$_POST['roepnaam'],
$_POST['tussenvoegsel'],
$_POST['achternaam']
);
$result = $stmt->execute();
if ( $result ) {
echo "1 record added";
} else {
echo $connect->error;
}
}
?>
I have a problem when i try to check if email is alredy registered. can someone help? I have this error:
mysql_fetch_array(): supplied argument is not a valid MySQL result resource in line...
($record =mysql_fetch_array($result); )
<?php
$nome = $_REQUEST["nome"];
$cognome = $_REQUEST["cognome"];
$psw = $_REQUEST["psw"];
$email = $_REQUEST["email"];
$nikName = $_REQUEST["nikName"];
$conn = mysql_connect("host,name","userName","Password","databaseName");
if(!$conn) {
echo "connessione non satabilita";
} else {
if(!mysql_select_db("databaseName",$conn)) {
echo "database non trovato";
} else {
$sql = "select * from utenti where User='$email'"; //costruzione comando di ricerca
$result = mysql_query($sql,$conn); //assegnazione risultati
$record =mysql_fetch_array($result); //estrazione primo risultato
if(!$record) {
$sql = "INSERT INTO User (UserId, Nome, Cognome, Email, Username, Password, TimeStamp) VALUES (NULL,'$nome','$cognome','$email','$nikName','$psw', NULL)";
$result=mysql_query($sql);
if($result) {
echo "utente registrato correttamente";
} else {
//Error
echo "errore registrazione, riprovare più tardi";
}
echo "<br />";
echo "utente registrato";
} else {
echo "utente gia registrato";
}
}
}
?>
Before this gets out of hand.
$conn = mysql_connect("host,name","userName","Password","databaseName");
You're using 4 parameters rather than 3.
Sidenote: 4 parameters is mysqli_ syntax http://php.net/manual/en/function.mysqli-connect.php
Be careful though, those different MySQL APIs do not intermix. So you cannot have mysql_ with mysqli_ should you decide to change it to that.
The manual http://php.net/manual/en/function.mysql-connect.php states:
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
the fourth is for something else.
If a second call is made to mysql_connect() with the same arguments, no new link will be established, but instead, the link identifier of the already opened link will be returned. The new_link parameter modifies this behavior and makes mysql_connect() always open a new link, even if mysql_connect() was called before with the same parameters. In SQL safe mode, this parameter is ignored.
So, just remove the 4th parameter.
Sidenote: This is questionable "host,name" (with the comma). Double check it as to what your host (if hosted) has provided you with. Most of the time, that should read as "localhost".
As stated, you're open to SQL injection.
Use a prepared statement:
https://en.wikipedia.org/wiki/Prepared_statement
As for the rest of your code:
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Displaying errors should only be done in staging, and never production.
Also add or die(mysql_error()) to mysql_query().
About you're wanting to check if an email exists; you may be better off using mysql_num_rows().
I.e.:
$sql = "select * from utenti where User='$email'";
$result = mysql_query($sql,$conn) or die(mysql_error($conn));
if(mysql_num_rows($result) > 0)
{...}
else {...}
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.
Also, this doesn't help you:
if(!mysql_select_db("databaseName",$conn)){
echo "database non trovato";
}
This does:
if(!mysql_select_db("databaseName",$conn)){
die ('Can\'t use the database : ' . mysql_error());
}
In order to get the real error, should there be one.
Reference:
http://php.net/manual/en/function.mysql-select-db.php
As mentioned above there is a syntax error with mysql_connect(); where you're trying to use invalid number of params. The best way is to make a config.php file and then use it whenever you need it. This is a basic connection code in PDO.
<?php
$host = "localhost";
$database = "yourdbnamehere";
$username = "yourusernamehere";
$password = "yourpasswordhere";
try {
$dbo = new PDO('mysql:host='.$host.';dbname='.$database, $username, $password);
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
?>
You will need a solution like this. But you must switch towards PDO or MySQLi to ensure that your code stays valid in long run as well as you will be able to write secure and stable code.
Go through these at first:
http://php.net/manual/en/book.pdo.php
http://php.net/manual/en/book.mysqli.php
An example code for you solving your current problem:
<?php
$nome = $_REQUEST["nome"];
$cognome = $_REQUEST["cognome"];
$psw = $_REQUEST["psw"];
$email = $_REQUEST["email"];
$nikName = $_REQUEST["nikName"];
try{
$pdo = new PDO('mysql:dbhost=hostname; dbname=databaseName', 'userName', 'Password');
} catch (PDOException $e) {
echo "Error connecting to database with error ".$e;
die();
}
// check for email
$sql = $pdo->prepare("select * from utenti where User= ?");
$sql->bindParam('1', $email);
$sql->execute();
/* if you aren't hashing the password,
then do it first
$psw = PASSWORD_HASH($psw, PASSWORD_DEFAULT);
*/
// Insert if email not registered
if($sql->rowCount() == 0) {
$insert = $pdo->prepare("INSERT INTO User (Nome,Cognome,Email,Username,Password) VALUES (?, ?, ?, ?, ?)");
$insert->bindParam('1', $nome);
$insert->bindParam('2', $cognome);
$insert->bindParam('3', $email);
$insert->bindParam('4', $nikName);
$insert->bindParam('5', $psw);
$insert->execute();
if($insert->rowCount() > 0) {
echo "utente registrato correttamente";
} else {
echo "errore registrazione, riprovare più tardi";
}
} else {
echo "utente gia registrato";
}
?>
Referring to this topic: Display error message if value not found mysql,
I tried to understand what's the correct method to achieved it, my current code show's me the result from database query but when I put some value that not in database, it just doesn't show the error message or any php coding error.
Here is my php code:
error_reporting(E_ALL); ini_set('display_errors', 1);
require_once 'dbconnect.php';
$name = $_POST['name'];
try {
$conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT *
FROM customer
WHERE lname LIKE :name OR
fname LIKE :name OR
number LIKE :name";
$q = $conn->prepare($sql);
$q->execute(array('name' => $name));
$q->setFetchMode(PDO::FETCH_ASSOC);
} catch (PDOException $pe) {
die("Could not connect to the database $dbname :" . $pe->getMessage());
}
and here is my html view:
<tbody>
<?php
$cs = $q->fetchAll();
if ( $cs === FALSE ) {
echo "The search of $name return no result";
} else {
foreach($cs as $r): ?>
<tr>
<td><?php echo htmlspecialchars($r['fname']), ' ', htmlspecialchars($r['lname']) ?></td>
<td><?php echo htmlspecialchars($r['number']) ?></td>
<td>View Profile</td>
</tr>
<?php endforeach;
} ?>
</tbody>
Kindly advise where did I go wrong?
Technically, nothing is failing with the query itself, so fetchAll() won't return false. What it will do, when you run a query that returns no results, is return an empty array.
In this case, you can alter your if statement to read: if ($cs === false || empty($cs)) {. Alternatively, you can use if (!$cs) { to allow PHP to interpret falsey values, like an empty array.
Source: PDOStatement::fetchAll()
This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 9 years ago.
Good morning all,
I recently made a post on this website regarding a login page for a website. It was pointed out to me that I was very vulnerable to an SQL injection. I have spent the past weekend researching into SQL injections and I am getting a bit of a better idea about how they function, however I am still very new to PHP (I taught myself the basics in a day). I was wondering if anyone could help me with my code please.
I have read every link that people posted and researched it till my head exploded (no need to edit, its not literal), but I am still struggling as to the code itself.
Here is my code:
<?php
session_start();
// dBase file
include "dbConfig.php";
if ($_GET["op"] == "login")
{
if (!$_POST["username"] || !$_POST["password"])
{
die("You need to provide a username and password.");
}
// Create query
$q = "SELECT * FROM `dbusers` "
."WHERE `username`='".$_POST["username"]."' "
."AND `password`=PASSWORD('".$_POST["password"]."') "
."LIMIT 1";
// Run query
$r = mysql_query($q);
if ( $obj = #mysql_fetch_object($r) )
{
// Login good, create session variables
$_SESSION["valid_id"] = $obj->id;
$_SESSION["valid_user"] = $_POST["username"];
$_SESSION["valid_time"] = time();
// Redirect to member page
Header("Location: members.php");
}
else
{
// Login not successful
die("Sorry, could not log you in. Wrong login information.");
}
}
else
{
//If all went right the Web form appears and users can log in
echo "<form action=\"?op=login\" method=\"POST\">";
echo "Username: <input name=\"username\" size=\"15\"><br />";
echo "Password: <input type=\"password\" name=\"password\" size=\"8\"><br />";
echo "<input type=\"submit\" value=\"Login\">";
echo "</form>";
}
?>
Now I know it needs validation AND sanitisation in PDO, am just struggling as to what to actually write in my code. I am hoping that someone could help rather than just link me to another page please
as an edit, if anyone has a link to a tutorial about logins which are SQLinjection safe that could help me/other people looking to protect against that would be much appreciated. Thanks
Well you can use PDO or mysqli. The most interesting point is that you can use prepared statements with both.
If you used mysql before, as in your code, then mysqli is easier to understand for you.
The manual page of PHP has good examples for mysqli with prepared statements.
First of all you need a mysqli connection:
$mysqli = new mysqli("host", "user", "password", "database");
When you got your query, replace all external inputs with a ?.
$q = "SELECT * FROM `dbusers` "
."WHERE `username`=? "
."AND `password`=PASSWORD(?) "
."LIMIT 1";
And create a prepared statement:
$stmt = $mysqli->prepare($q);
Then you can easily bind your params. Because in your case both are strings, you have to use a s for each param.
$mysqli->bind_param('ss', $_POST['username'], $_POST['password']);
And then just execute the statement:
$stmt->execute();
With methods like fetch() you can get the result(s).
As you're using the old mysql_* API, you could just use the mysql_real_escape_string function which does exactly what you need.
Use it like this :
$q = "SELECT * FROM `dbusers` "
."WHERE `username`='".mysql_real_escape_string($_POST["username"])."' "
."AND `password`=PASSWORD('".mysql_real_escape_string($_POST["password"])."') "
."LIMIT 1";
try this function to pass every POST variable
function mysql_string($str)
{
$str = stripslashes($str);
$str = mysql_real_escape_string($str);
return $str;
}
now use it as follows
$username = mysql_string($_POST["username"]);
$password = mysql_string($_POST["password"]);
$q = "SELECT * FROM `dbusers` "
."WHERE `username`='".$username."' "
."AND `password`=PASSWORD('".$password."') "
."LIMIT 1";
no use $username in your query to prevent mysql injection
Just as an example here is a PDO INSERT statement
$dbHost = "";
$dbName = "";
$dbUser = "";
$dbPass = "";
$dsn = 'mysql:host=' . $dbHost . ';dbname=' . $dbName;
$options = array(
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
try {
$dbh = new PDO($dsn, $dbUser, $dbPass, $options);
$db = $dbh->prepare('INSERT INTO db_table (column_one, column_two, column_three)
VALUES (:column_one, :column_two, :column_three)');
$db->bindParam(':column_one', $dataForColumnOne);
$db->bindParam(':column_two', $dataForColumnTwo);
$db->bindParam(':column_three', $dataForColumnThree);
$db->execute();
} catch (PDOException $e) {
echo $e->getMessage();
}
An example here is a PDO multiple row fetch statement
try {
$dbh = new PDO($dsn, $dbUser, $dbPass, $options);
$db = $dbh->prepare('SELECT * FROM db_table');
$db->execute();
$rows = $db->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows as $row) {
print_r($row);
}
} catch (PDOException $e) {
echo $e->getMessage();
}
As a rule never trust user input,
Notice that the data is added via "->bindParam" and not directly inserted into the "->prepare" statement
Please refer to PHP PDO
I am trying to write some information into an SQL database from my website using PHP. I can access the database to login, however I can not write anything to it from my website. Also, I can not view any connection errors.
Form Page:
<?php
$dbh = new PDO('mysql:host='.$hostname.';dbname='.$dbname, $user, $pass);
if (!$dbh) { die('Could not connect: ' . mysql_error()); }else echo 'connected';echo '<br>';
if(isset($_COOKIE['username']))
?>
<div id="imagel">
<img class="imagel" src="../images/logos/logo2.jpg" width="300" height="300" alt="studio table" />
</div>
<div id="textr">
<form name="tableofevents" method="post" action="adminhome.php">
Name of Event(Maximum of 83 characters): <input type="text" name="noe"/>
<br>
Event Description (Maximum of 288 characters): <input type="text" name="eventdescription"/>
<br>
Date of Event: <input type="text" name="date"/>
<br>
Ticket Price: <input type="text" name="price"/>
<br>
<input type="submit" name="submit" text="submit"/>
</form>
Processing Page:
<?php
$hostname = 'localhost';
$user='******';
$pass='***********';
$dbname='sth420';
$handler = new PDO('mysql:host='.$hostname.';dbname='.$dbname,$user,$pass);
$dbh = mysql_connect ($hostname.';dbname='.$dbname, $user, $pass);
if (!$dbh) { die('Could not connect: ' . mysql_error()); }
else echo 'connected';echo '<br>';
if(isset($_COOKIE['username']))
{
$username=$_COOKIE['username'];
$password=$_COOKIE['password'];
$sql='SELECT * FROM Users WHERE ID=:id';
$results = $handler->prepare($sql);
$results->execute([':id' => $username]);
$row = $results->fetch();
if($row!=null)
{
$pword = $row['Password'];
if($pword == $password)
{
if(isset($_POST['submit']))
{
$noe=$_POST['noe'];
$ed=$_POST['eventdescription'];
$date=$_POST['date'];
$price=$_POST['price'];
$sql='INSERT INTO ismievents ( title, evtdesc, dandt, price ) VALUES(0, :noe, :eventdescription, :date, :price)';
mysql_error()
$results = $handler->prepare($sql);
$results->execute([':noe' => $noe, ':eventdescription' => $ed, ':date' => $date, ':price' => $price]);
$handler = null;
header('Location: events.html');
}
}
}
}
if (!mysql_query($sql,$dbh))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($dbh);
require_once('adminhome.html');
?>
You are mixing PDO and mysql_connect(). That is invalid, as they are incompatible APIs. Remove all references to mysql_*() and stick only with your PDO statements. You have basically duplicated every PDO statement with an incorrect call to mysql_query() but you should have none of mysql_connect(), mysql_query(), mysql_error(), mysql_fetch_*().
Refer to the manual on PDO prepared statements to see the many examples.
I see a mismatch between column counts here. You list 4 columns, but the VALUES () list contains 5:
// Prepared statemetn looks ok...
$sql='INSERT INTO ismievents ( title, evtdesc, dandt, price ) VALUES(0, :noe, :eventdescription, :date, :price)';
// But this is meaningless here...
mysql_error()
I note also that you are using PHP 5.4 array literals like:
$results->execute([':noe' => $noe, ':eventdescription' => $ed, ':date' => $date, ':price' => $price]);
Hopefully you are actually running this code in PHP 5.4.
Really, you need to take this code back to the drawing board to purge it of the incompatibilities between PDO and mysql_*(). After that, you will be able to narrow down other problems with it.
A final note here, it is really inadvisable to store a password in $_COOKIE. On a successful login, instead store a logged in state in $_SESSION.