Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I wrote the below script as my very first ever php mysql application. I am self taught and the code works as intended. My host thinks it may be vulnerable to sql injection attacks but cannot tell me why or what I should change to make it better. I'm sure it's not as clean as it could be but if anyone has any suggestions or insight I would certainly appreciate it.
<form method="post" action="search.php?go" id="searchform">
<?php
$db=mysql_connect ("server", "*", "*") or die ('I cannot connect to the database because: ' . mysql_error());
$mydb=mysql_select_db("*");
$category_sql="SELECT distinct category FROM Members";
$category_Options="";
$category_result=mysql_query($category_sql) or die ('Error: '.mysql_error ());
while ($row=mysql_fetch_array($category_result)) {
$category=$row["category"];
$category_Options.="<OPTION VALUE=\"$category\">".$category.'</option>';
}
?>
<p>
<SELECT NAME="category"><OPTION VALUE=0>Choose<?=$category_Options?></SELECT>
</p>
<input name="submit" "id="submit" type="submit" value="submit" />
</form>
<?php
if(isset($_POST['submit'])){
if(isset($_GET['go'])){
$category=$_POST['category'];
$category=mysql_real_escape_string($category);
$sql="SELECT category, company, address, city, state, zip, phone, web, addescription, image
FROM Members
WHERE category LIKE '$category'";
$result=mysql_query($sql);
while($row=mysql_fetch_array($result)){
$category2=$row["category"];
$company=$row["company"];
$address=$row["address"];
$city=$row["city"];
$state=$row["state"];
$zip=$row["zip"];
$phone=$row["phone"];
$web = $row["web"];
$addescription = $row["addescription"];
$image = $row["image"];
echo "<blockquote>";
if(#file_get_contents($image))
{
echo "<img src='".$image ."' class='image'/>\n";
}
else
{
}
echo "<p>\n";
echo "</br>".$category2 . "\n";
echo "</br><b>".$company . "</b>\n";
echo "</br>".$address . "\n";
echo "</br>".$city . ", ".$state. " ".$zip . "\n";
echo "</br>".$phone . "\n";
echo "</br>".$web ."\n";
echo "</br>".$addescription . "\n";
echo "</br><a href=http://www.printfriendly.com style=color:#6D9F00;text-decoration:none; class=printfriendly onclick=window.print();return false; title=Printer Friendly and PDF><img style=border:none; src=http://cdn.printfriendly.com/pf-button.gif alt=Print Friendly and PDF/></a>\n";
echo "</p>";
echo "</blockquote>"
;
}
}
else{
echo "<p>Please select a Category</p>";
}
}
mysql_close($db)
?>
The MySQL functions are deprecated. Using the MySQLi functions, and prepared statements, are a better way to protect against sql injection attacks.
$stmt = $mysqli->prepare('SELECT category, company, address, city, state, zip, phone, web, addescription, image FROM Members WHERE category LIKE ?');
$stmt->bind_param('s', $category);
I'll show the implementation of a PDO connection and how to query with it. Here it goes!
First we create the connection variable with your database credentials. We'll store this connection in $db.
$username = "root";
$password = "";
$host = "localhost";
$dbname = "my_database";
$options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
try{
$db = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8"; $username, $password, $options);
}catch(PDOException $ex){
die("Failed to connect: ".$ex->getMessage());
}
Now you have a PDO connection stored in $db which you can query through. You may want to account for magic quotes if you're not using PHP 5.4, so keep that in mind.
Otherwise, create your query statement like so..
$query = "SELECT category, company, address, city, state, zip, phone, web, addescription, image FROM Members WHERE category LIKE :category"
Afterwards, you want to bind the value from the $_POST['category'] variable (or $category since you created that) to the parameter :category. Do that like so:
$query_params = array( ':category' => $category);
Finally, now that you have the statement and the parameters, use the previously created $db variable to prepare and execute the statement.
$statement = $db->prepare($query);
$result = $statement->execute($query_params);
Since we're SELECTing data where it could return multiple rows (assuming you have multiple rows within a category), we need to account for that. Grab the rows that the statement returns like so:
$rows = $statement->fetchAll();
And now you could refer to column headers within each $row of the database table by utilizing a foreach statement.
$citiesArray = array();
foreach($rows as $row){
if(isset($row['city'])){
$citiesArray[] = $row['city'];
}
}
Hope that helps out!
Just remember the golden rule of never trusting your users. Never take any raw user input and insert it into a database, as there's a chance that you have left yourself wide open for a security issue.
Your code seems fine. However, do note that MySQL is deprecated as of PHP 5.5.0, and instead you should use MySQLi or PDO extension which provide more security.
Maybe that's the reason your host said such thing, but from a quick look on your code it seemed fine to me.
Cheers.
The problem is the follwoing part in your code
$sql = "SELECT category, company, address, city, state, zip,
phone, web, addescription, image
FROM Members
WHERE category LIKE '$category'";
$result=mysql_query($sql);
If the parameter $category is read from the GET or POST parameters, it should be escaped:
$sql = "SELECT category, company, address, city, state, zip,
phone, web, addescription, image
FROM Members
WHERE category LIKE '" . mysql_real_escape_string($category) . "';";
If you are doing it this way, the variable cannot be used for SQL Injection
By the way (like Matthew Johnson said), the procedural mysql extension is deprecated since PHP 5.5. You should better use Mysqli or PDO.
The OOP way (strongly recommended) would look like:
$pdo = new PDO($dsn, $user, $password, $options);
$statement = $pdo->prepareStatement(
"SELECT category, company, address,
city, state, zip, phone, web,
addescription, image
FROM Members
WHERE category LIKE :category;");
$statement->bindParam(':category', $category, PDO::PARAM_STR);
$statement->execute();
$categories = $statement->fetchAll();
Related
I'm a beginner when it comes to the topic. I've followed this tutorial to connect one form to a database and it worked well. Now I'd like to add another form and my questions are:
do I create separate function in connection.php?
do I create a separate table in the same database?
how do I generate a separate thank you message?
The other form is a contact form.
connection.php:
<?php
function Connect()
{
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "root";
$dbname = "responses";
// Create connection
$conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname) or die($conn->connect_error);
return $conn;
}
?>
thankyou.php
<?php
require 'connection.php';
$conn = Connect();
$email = $conn->real_escape_string($_POST['u_email']);
$query = "INSERT into newsletter (email) VALUES('" . $email . "')";
$success = $conn->query($query);
if (!$success) {
die("Couldn't enter data: ".$conn->error);
}
echo $_GET["form"];
echo "Thank you for subscribing to our newsletter. <br>";
$conn->close();
?>
The second form would look like this:
$name = $conn->real_escape_string($_POST['name']);
$email = $conn->real_escape_string($_POST['email']);
$message = $conn->real_escape_string($_POST['message']);
$query = "INSERT into contactForm (name,email,message) VALUES('" . $name . "','" . $email . "','" . $message . "')";
$success = $conn->query($query);
I've created two tables: newsletter and contactForm. Now, how do I direct form input to the right table?
1 - You can "require"/"include" the same connection.php wherever it suit you / need it
2 - you can create on the same Database a new table and do action on this new on your query example:
$query = "INSERT into newsletter (email) VALUES('" . $email . "')";
$success = $conn->query($query);
$query = "INSERT into newsletter_schedule (email,schedule_date) VALUES('" . $email . "', NOW())";
$success = $conn->query($query);
or you can create in a different db and change db name connected(more complex but sometimes needed)
3 - you can do in separate static file and redirect to using (PHP function)
header("location: tankyou.html");//put your file name/must be the first output, even a space before can throw a error
leave more details about the 3rd if is not what you are looking for
Unfortunately, your question, "How do I...?" is a bit broad in this case. Any number of ways. The only real way to get a sense for these things is to try a number of times. You may fail, but that's where the most learning happenings.
Your specific questions:
do I create separate function in connection.php?
Depends on what you need. I might include a 'CloseConnection' or 'TearDown' function, but doing so is not strictly necessary in PHP. (PHP does it's best to close down and stop using any resources you still have open at the end of your script.)
However, if you want to edge toward better practices, get in the habit now of always cleaning up after yourself. What you learned in kindergarten applies: if you opened it, close it. If you created it, dispose of it. If you allocated it, deallocate it. etc.
do I create a separate table in the same database?
Yes. This question is related to schema design, and again, you will just have to try things out and see what works for your situation and thought processes. You will know that things are not right when the logic gets really convoluted. But knowing that comes with nothing other than experience.
how do I generate a separate thank you message?
The same way you generate any other HTML. Some version of echo, print, or include/require. Given your current setup, I might create a separate function for this logic.
One thing which is not what you asked for, but which I feel compelled to point out: heavily consider prepared statements for your SQL, rather than string interpolation. That is ...
BAD:
$query = "INSERT into newsletter (email) VALUES('" . $email . "')";
$success = $conn->query($query);
BETTER/GOOD:
$sql = "INSERT INTO newsletter (email) VALUE ( ? )";
$statement = $conn->prepare( $sql );
$statement->bind_param('s', $email);
$statement->execute();
This is perhaps slightly more complicated, but also precludes any need for sanitization like real_escape_string.
For more information, read the documentation and google prepared statements, but the gist is this: for security reasons now, and higher performance later. By telling the database what will be coming, you preclude someone from injecting something you didn't expect or want.
Here's my code:
<?php
//recently added
$result = mysql_query("SELECT background FROM " . $shadowless_background_table . " WHERE id = 1");
if ($result == 1){
?>
<script>
jQuery(document).ready(function(){
jQuery(".eltdf-psc-slide").addClass("no-background");
});
</script>
<?php
}
//=============
?>
Basically what I'm trying to do is checking and see if the value stored in the $shadowless_background_table "DB" is == 1 and I only want that column (background). I have browse the web, but what I see are examples with while loops which I was wondering if I could do something like this instead.
If you want to fetch a single record based on a condition you can do this -
$result = mysql_query("SELECT background FROM " . $shadowless_background_table . " WHERE id = 1");
if (mysql_num_rows($result)>0){
$fetchedColum = mysql_result($result, 0, 'COLUMN_NAME');
}
There are couple of issues with your code.The first thing that i have noticed is that you are using mysql API instead of PDO.I don't blame you since the internet is full of old tutorials and you probably didn't have a chance to get some guidance.
MySql is getting old It doesn't support modern SQL database concepts such as prepared statements, stored procs, transactions etc... and it's method for escaping parameters with mysql_real_escape_string and concatenating into SQL strings is error prone and old fashioned.
Organize your project better.
As i have seen from this example you probably have a poor project organization.You should consider reading about PSR Standards
And to go back to your question ,and to update it a bit.
Instead of doing
mysql_query("SELECT background FROM " . $shadowless_background_table . " WHERE id = 1");
I would do it this way:
<?php
$host = "localhost";
$username = "user name of db";
$password = "password of db";
$dbname = "database name ";
try {
$conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//your data
$id = 1; // id
$stmt = $conn->prepare("SELECT background FROM database_name WHERE id=:id");
$stmt->bindParam(':id', $id);
$stmt->execute();
$data = $stmt->fetchAll();
foreach ($data as $row) {
echo $row["row_name"];
}
}
catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
Go read more about PHP in general ,it will help you out a lot.The biggest problem is that there are so much wrong tutorials and references or they are just old.And people learn from wrong sources.
I had the same problem ,but thanks to right people on this site i have managed to learn more.
My suggestion is that you read about PSR,PDO and PHP in general!!!
Also a thing you should consider reading about is security in php.
Good luck mate :D
I have a problem displaying my information in the database using phpmyadmin. I have 2 files (form.php and connect.php), it says it's connected to the database but nothing shows up in my database.
Is there any solution for that? I spent almost a whole day trying to resolve that.
Here's connect.php:
<?php
$mysql_host='localhost';
$mysql_user='root';
$mysql_password=''; **i don't have a password.
mysql_connect($mysql_host,$mysql_user,$mysql_password)
echo"connection sucess";
$link = mysqli_connect("localhost","root","") or die ("Couldn't not connect");
mysqli_select_db($link, "cooperative_db");
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo "Successfully connected \n";
$FIRST_NAME = $_POST['FIRST_NAME'];
$LAST_TIME = $_POST['LAST_NAME'];
$CIVIC_NUMBER = $_POST['CIVIC_NUMBER'];
$STREET = $_POST['STREET'];
$CITY = $_POST['CITY'];
$PROVINCE = $_POST['PROVINCE'];
$POSTAL_CODE = $_POST['POSTAL_CODE'];
$COUNTRY = $_POST['COUNTRY'];
//$TELEPHONE = $_POST['TELEPHONE'] . $_POST['TELEPHONE'] . $_POST['TELEPHONE'];
$INCOME = $_POST['INCOME'];
//$INCOME_SOURCE = $_POST['element_6_1'] . $_POST['element_6_2'] . $_POST['element_6_3'] . $_POST['element_6_4'] .
//$_POST['element_6_5'];
$sql = "INSERT INTO candidat(FIRST_NAME, LAST_NAME, CIVIC_NUMBER, STREET, CITY, PROVINCE, POSTAL_CODE, COUNTRY, INCOME) VALUES ('$FIRST_NAME', '$LAST_TIME', '$CIVIC_NUMBER', '$STREET','$CITY', '$PROVINCE', '$POSTAL_CODE', '$COUNTRY', '$INCOME')";
?>
It seems like you may have many issues in your code. Let's start step by step.
I am not sure if that: "**i don't have a password." is actually inside your code, so change it first of all to //i don't have a password..
Now, in the second picture you showed us, it only echo 1 line instead of two, and inside your code you actually have two lines that should echo a result.
echo"connection sucess"; and echo "Successfully connected \n";
This could be due to the fact that you forgot a ; in the line right before the first echo.
mysql_connect($mysql_host,$mysql_user,$mysql_password);
May I ask you why are you using both mysql, and mysqli? If it's just for testing, there's no harm in it, plus you should know that mysql is deprecated and no longer supported or updated, you better just use mysqli, please refer to this post Why shouldn't I use mysql_* functions in PHP?.
The first picture shows that you don't have a table named candidat, yet in your code you have this: INSERT INTO candidat. Maybe you wanted this to be INSERT INTO cooperative_table instead?
Please make those small fixes, and tell us your result.
Edit: I forgot to mention, just like tadman commented, you better be aware of the SQL Injection bugs you have and fix them accordingly.
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!
I'm trying to make my first registration script using PHP/SQL. Part of my code isn't working:
if(!$errors){
$query = "INSERT INTO users (email, password) VALUES ($registerEmail, $registerPassword)";
if(mysqli_query($dbSelected, $query)){
$success['register'] = 'Successfully registered.';
}else{
$errors['register'] = 'Registration did not succeed.';
}
}
When I test my code I get the error 'Registration did not succeed.' For reference, $errors and $success are arrays. Is there anything wrong with this part of my script?
$dbSelected is:
$dbLink = mysqli_connect('localhost', 'root', 'PASSWORD');
if (!$dbLink) {
die('Can\'t connect to the database: ' . \mysqli_error());
}
$dbSelected = mysqli_select_db($dbLink, 'devDatabase');
if (!$dbSelected) {
die('Connected database, but cannot select
devDatabase: ' . \mysqli_error());
}
I'm sure I am connecting and selecting the database.
Any help would be greatly appreciated! I am very new to PHP/SQL so forgive me for any noob mistakes.
Quote the string like below
$query = "INSERT INTO users (email, password) VALUES ('$registerEmail', '$registerPassword')";
You can also do
echo $query;
and take the output on the browser, copy and paste into PHPMyAdmin and execute it from there. It should tell you what is wrong with the query.
I suggest you to use prepared statement as using string concatenation in SQL Statement is prone to SQL injection attack. Refer the example PHP mysqli prepare
First off, PHP is deprecating mysql_ functions, you should migrate to PDO instead.
Also, make sure since you're using the older mysql_ functions to sanitize your entries using mysql_real_escape_string
Also, your entries need to be quoted. Here's a redo of your query string:
$query = "INSERT INTO users (email, password) VALUES ('{$registerEmail}', '{$registerPassword}')";