Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I'm trying to code an order process. I have 3 different tables (orders, product, users) in a single database (dbphesemaas).
What I've tried so far doesn't work:
<?php
$link = mysql_connect('localhost', 'root', '');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('dbphesemaas');
$username=$_POST["username"];
$area=$_POST["area"];
$product=$_POST["product"];
$address=$_POST["address"];
$dol_quantity=$_POST["quantity"];
$query="INSERT INTO orders (id, product_id, address, quantity) VALUES ('$id', '$id2', '$address', '$dol_quantity')";
mysql_close();
?>
Can someone make this code work, the id is a foreign key from users, while the product_id is a foreign key of product?
1. Error handling
You just connect and execute the query.
Well yeah nope - how are you making sure that everything worked?
Let's start off with error handling.
<?php
$link = mysql_connect('localhost', 'root', '');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('dbphesemaas');
?>
Is the connection working? Did the database get selected successfully?
You can use the if module to check if it worked.
<?php
// IF $link = mysql_connect('localhost', 'root', '') did not work (note the ! in front of it)
if(!$link = mysql_connect('localhost', 'root', '')){
die('Could not connect to localhost'); // The message displayed. die() will prevent the rest of the script from executing.
}
// IF database "dbphesemaas" did not get selected succesfully (note the ! in front of it)
if(!mysql_select_db('dbphesemaas', $link)){
die('Could not select the database "dbphesemaas"'); // The message displayed. die() will prevent the rest of the script from executing.
}
?>
Now we have the connection working. If something goes wrong, the script will stop being executed and throw a custom error.
2. Unnecessary variables
$username=$_POST["username"];
$area=$_POST["area"];
$product=$_POST["product"];
$address=$_POST["address"];
$dol_quantity=$_POST["quantity"];
Now is my question, why? There is nothing wrong with just using them inside the query. The only reason why you only would make variables is if the old variable is very long (so the chance of typo's are bigger) and/or if the code is too messy in your opinion. Since there is no problem in this code to use the $_POST variable, we're going to scratch this piece of code.
3. The actual query
$query="INSERT INTO orders (id, product_id, address, quantity) VALUES ('$id', '$id2', '$address', '$dol_quantity')";
There are a few problems here:
You wrote the query, but you aren't executing it.
You are using variables ($id, $id2 etc) inside quotes. In the wrong scenario, it's gonna insert $id in the database instead of the actual value.
Once again, no error handling.
No untainting at all. The user can add on into your query and alter the query, making a possible leak and the chance of being hacked bigger. We're going to prevent this with mysql_real_escape_string: http://php.net/manual/en/function.mysql-real-escape-string.php
Looks kinda messy, but that's just a visual problem.
Let's fix these problems:
$query="
INSERT INTO
orders
(
id,
product_id,
address,
quantity
)
VALUES
(
'". mysql_real_escape_string($_POST['id']) ."',
'". mysql_real_escape_string($_POST['id2']) ."',
'". mysql_real_escape_string($_POST['adress']) ."',
'". mysql_real_escape_string($_POST['quantity']) ."'
)
";
if(mysql_query($query)){
echo 'Succesfully executed the query.';
}
else
{
echo 'Query not executed - MySQL error. <br>';
echo '<pre>'. mysql_error() .'</pre>';
}
Using '". (random php code) ."' allows php code to be executed within a string. For example:
$variable = 'This is text '. strtoupper('this is capitalized since strtoupper makes this capital. note that this is inside the string.') .' and this is once again lowercase.';
4. Keep this for the future
The way I wrote these codes are useful for the future. Keep the use tabs every time you open/add a new bracket ({).
Further info - the default mysql_* functions are going to be deprecated as of PHP 5.5 - Use MySQLi in the future, it's the improved version. Info: http://www.php.net/manual/en/book.mysqli.php
5. For your actual problem
One mysql_query can only execute one query. You can do this:
$queries = array();
$errors = array();
$queries[] = 'INSERT INTO ... '; // using $variable[] will add another entry to the $variable array.
$queries[] = 'INSERT INTO ... ';
$queries[] = 'UPDATE bla SET ...';
foreach($queries as $query){
// Foreach will seperate the entries in an array
// IF mysql query failed
if(!mysql_query($query)){
$errors[] = mysql_error(); // We'll add the errors to an array aswell.
}
}
// Check if there are entries in the $failures array.
if(count($errors) > 0){
echo 'We had some MySQL errors.';
echo '<ul>';
foreach($errors as $failure){
echo '<li>'. $failure .'</li>';
}
echo '</ul>';
}
else
{
echo 'No errors - MySQL queries executed succesfully.';
}
Hope this helps you on your way.
Related
I installed MySql on my Raspberry Pi 2 Model B+ a few days ago to see if I could use it, PHP, phpmyadmin, and Apache to make an accessible database to organize and catalog books that are around the house. I have a table in a MySQL database set up as a prototype with three columns; Booknumber (set to auto-increment), title, and authorLastName. I'm trying to use a form to insert books into table beta, in database bookProof.
Here's the code for the form:
<html>
<body>
<form action="catalog.php" method="POST">
<p>Book Title: <input type="text" name="title"></p>
<p>Author's Last Name: <input type="text name="authorlastname"></p>
</form>
</body>
</html>
Which links to "catalog.php", which is:
<?php
define('DB_NAME', 'bookProof');
define('DB_USER', 'root');
define('DB_PASSWORD', 'root');
define('DB_HOST', 'localhost');
$conn = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if ($conn->connect_error) {
die("Could not connect: " . $conn->connect_error);
}
$value = $_POST["title"]
$value2 = $_POST["authorlastname"]
$sql = "INSERT INTO beta ('title', 'authorLastName') VALUES ('".$value."', '".$value2."')"
$query = mysqli_query($conn,$sql);
if ($conn->($sql) === TRUE) {
echo "New entry completed successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
When demoform.php is opened, it functions normally, but when the "Add Books" button is clicked, it goes to catalog.php as intended, but the catalog.php page is blank, the table is unchanged, and Google Chrome's "Inspect" tool gives the error:
POST http://192.168.254.11/Library/catalog.php 500 (Internal Server Error) catalog.php:1
If anyone knows how to get the input to the database, please let me know.
Note: This is just a home system, so security is not a priority (I don't need SQL code injection protection).
Your note, "...security is not a priority (I don't need SQL code injection protection)" - you might think that, but you should do it anyways. Not only does it protect your database should your system be exposed (or made public at a later time), it will handle strings automatically for you, so that your query won't break if your strings have quotes ' in them.
One issue is that you're using singlequotes around column and table names. This should be backticks, or none at all. Then you were missing a semicolon ; after defining your $value, $value2 and $sql strings.
Then you're doing something a bit odd - which is also causing a parse-error (Had you enabled error-reporting and checked your logs, you'd see a "Parse error: syntax error, unexpected (" error in your logs), you're querying the table with mysqli_query(), but then you try to do it again - except you're trying to query on the querystring, and not the query method. Note the comments I've added in the code below.
// Don't use singlequotes ' for columns and table-names
// Use backticks ` - quotes are for strings
$sql = "INSERT INTO beta (`title`, `authorLastName`) VALUES ('".$value."', '".$value2."')"; // You were also missing a semicolon here!
// $query = mysqli_query($conn,$sql); // Remove this line, as you're attempting to query it twice
if ($conn->query($sql) === TRUE) { // You're missing the query() method here
echo "New entry completed successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
Using prepared statements won't be that much of a difference, and you really should do it. There's absolutely no reason to not use prepared statements! Look how little changes that have to be made!
$sql = "INSERT INTO beta (title, authorLastName) VALUES (?, ?)";
if ($stmt = $conn->prepare($sql)) {
$stmt->bind_param("ss", $value, $value2);
$stmt->execute();
$stmt->close();
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
You've also got some invalid HTML which would cause issues - the following line had a missing quote to close off the type attribute.
<input type="text" name="authorlastname">
I suggest you read the following documentation and articles
When to use single quotes, double quotes, and backticks in MySQL
How can I prevent SQL injection in PHP?
PHP manual on mysqli_stmt::bind_param
How to get useful error messages in PHP?
PHP Parse/Syntax Errors; and How to solve them?
As a final note, you should check that the form was submitted and that it has values before inserting into the database. Also, using variable-names like $value and $value2 are not really descriptive - you should avoid it and use proper names for your variables.
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 6 years ago.
Improve this question
For some reason I can't connect to database. Here's my code:
<?php
//only process form if $_POST isnt empty
if ( ! empty( $_POST ) ) {
// Connect to MySQL
$mysqli = new mysqli( 'localhost', 'username', 'password', 'database' );
//Check connection
if ( $mysqli->connect_error ) {
die( 'Connect Error: ' . $mysqli->connect_errno . ': ' . $mysqli- >connect_error );
}
//Insert form data
$sql = "INSERT INTO user ( Name, Username, Password, Email ) VALUES
( '{mysqli->real_escape_string($_POST['Name'])}',
('{mysqli->real_escape_string($_POST['Lastname'])}',
('{mysqli->real_escape_string($_POST['Username'])}',
('{mysqli->real_escape_string($_POST['Password'])}' )
('{mysqli->real_escape_string($_POST['Email'])}' )";
//Print response from MySQL
if ( $insert ) {
echo "Success! Row ID: {$mysqli->insert_ID}";
}else{
die("Error: {$mysqli->errno} : {$mysqli->error}");
}
//Close our connection
$mysqli->close();
}
?>
Warning: your code is susceptible to SQL Injection!
Never use $_POST[] or any user submitted data directly in a SQL Insert.
Use Prepared Statements instead!
Regarding the code just prints on the screen:
If the PHP Code is printing on to the screen instead of being interpreted by the server; first make sure that the PHP file is using a valid PHP extension such as .php and not just .html
Also make sure that the php module is installed for your web server (this would be different instructions for IIS then for Apache).
Also your code is missing the actual query itself which is done using the following code:
$insert = $mysqli->query($sql) // do the insert
Then the rest of your code will start to function:
if ( $insert ) {
echo "Success! Row ID: {$mysqli->insert_ID}";
}else{
die("Error: {$mysqli->errno} : {$mysqli->error}");
}
$mysqli->close();
Without the $mysqli->query($sql) your hitting the else and die()
See query for more info.
The sql should be executed to return a result $insert
Example: $insert = $mysqli->query($sql)
(And, as mentioned it's much safer to use prepared statements.)
well, you wrote
if ( $insert ) {
echo "Success! Row ID: {$mysqli->insert_ID}";
That echoes exactly what is between the subsequent quotation marks (as a string)...
The script will keep hitting the die statement because $insert hasn't been set. So you are right: it just prints to the screen.
When you copied and pasted the code from "The Internet" you forgot one line - as Philip pointed out:
$insert = $mysqli->query($sql)
Without it, the only thing that your script would do is create a connection and close it again - or, most likely: not even managing to close it because it would die before it reached that line. :)
The line you forgot is supposed to be inserted just after the $sql string but before the conditional using $insert.
I am not sure what I am doing wrong, can anybody tell me?
I have one variable - $tally5 - that I want to insert into database jdixon_WC14 table called PREDICTIONS - the field is called TOTAL_POINTS (int 11 with 0 as the default)
Here is the code I am using. I have made sure that the variable $tally5 is being calculated correctly, but the database won't update. I got the following from an online tutorial after trying one that used mysqli, but that left me a scary error I didn't understand at all :)
if(! get_magic_quotes_gpc() )
{
$points = addslashes ($tally5);
}
else
{
$points = $tally5;
}
$sql = "INSERT INTO PREDICTIONS ".
"(TOTAL_POINTS) ".
"VALUES('$points', NOW())";
mysql_select_db('jdixon_WC14');
I amended it to suit my variable name, but I am sure I have really botched this up!
help! :)
I think you just need to learn more about PHP and its relation with MYSQL. I will share a simple example of insertion into a mysql database.
<?php
$con=mysqli_connect("localhost","peter","abc123","my_db");
// Check for errors in connection to database.
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query = "INSERT INTO Persons (FirstName, LastName, Age) VALUES ('Peter', 'Griffin',35)";
mysqli_query($con, $query);
mysqli_close($con); //Close connection
?>
First, you need to connect to the database with the mysqli_connect function. Then you can do the query and close the connection
Briefly,
For every PHP function you use, look it up here first.
(You will learn that it is better to go with mysqli).
http://www.php.net/manual/en/ <---use the search feature
Try working on the SQL statement first. If you have the INSERT process down, proceed.
You need to use mysql_connect() before using mysql_select_db()
Once you have a connection and have selected a database, now you my run a query
with mysql_query()
When you get more advanced, you'll learn how to integrate error checking and response into the connection, database selection, and query routines. Convert to mysqli or other solutions that are not going to be deprecated soon (it is all in the PHP manual). Good luck!
if(! get_magic_quotes_gpc() )
{
$points = addslashes ($tally5);
}
else
{
$points = $tally5;
}
mysql_select_db('jdixon_WC14');
$sql = "INSERT INTO PREDICTIONS (TOTAL_POINTS,DATE) ". //write your date field name instead "DATE"
"VALUES('$points', NOW())";
mysql_query($sql);
I've figured out how to display info submitted into mysql, but I haven't figured out how to keep the past info there. It's going to show the current post on top and keep adding on top everytime new info is submitted but only display like 10 posts at a time. I hope I am explaining this well.
How to go about doing this, I am completely lost. I've connected to the database and everything and now im to:
echo $hit, $amount, $category;
and stuck. that is displaying the info submitted, but when i submit new info, that info changes and the past info is gone. My question is, how would i get the past info to stay and get the new info to build on top of past info?
Thanks.
Edit: here's more of the code. also, ive been told about mysqli. i just havent changed it yet.
if(!$link){
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db(DB_NAME, $link);
if(!$db_selected){
die('can not use' . DB_NAME . ': ' . mysql_error());
}
$hit = $_POST['hit'];
$amount = $_POST['amount'];
$category = $_POST['category'];
$sql = "INSERT into hit (hit, amount, category) VALUES ('$hit', '$amount', '$category')";
$result = mysql_query($sql);
if(!mysql_query($sql)){
die('Error: ' . mysql_Error());
}
echo $hit, $amount, $category;
mysql_close();
?>
After the insert sql you need to do a select query to retrieve all the rows from the database as you are only echoing the currently set values.
You need to also be mindful of sql injection as the values you're adding to the database are not sanitised in any way. Use a command such as mysql_real_esape_string or htmlentities for this.
Before the line echoing the results...
echo $hit, $amount, $category;
You need to have a select query combined with a while loop and the mysql_fetch_array or mysql_fetch_assoc commands to output the rows from the database. A first check is to see if the records are being added to the table.
At no point in your code are you fetching data from the database. You're simply submitting the data from the form to mysql, and displaying it at the same time.
You can fetch data from mysql by doing something like this:
$data = mysql_query("SELECT hit, amount, category FROM hit");
// Adding MYSQL_ASSOC as a second argument tells mysql_fetch_array that
// we want an associative array (we can refer to fields by their name, not just by number)
while($row = mysql_fetch_array($data, MYSQL_ASSOC)) {
echo '<p>'
.'Hit: ' . $row['hit']
.', Amount: ' . $row['amount']
.', Category: ' . $row['category']
.'</p>';
}
Keep in mind this is all a simplified version of things, and it needs more work, especially on security. I should probably be using htmlentities() here, depending on the data. And you should definitely be protecting against SQL injection if that data is coming directly from a user.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
PHP / MYSQL Add button to column
Please correct any mistakes throughout this question - I am very new to both PHP and MYSQL.
My goal is to create a table, that I will display onto a web page that looks something like this:
I have done the following. Any help on where I go wrong is much appreciated.
Created a MYSQL Table named "CustomerInformation"
Added five columns to the table, identical to the five columns in the picture above; (id, name, email, is_admin, Action).
I made four $POST text boxes whose data will be passed into each column (other than the last one as I want an "action" button to appear there).
Below I will show my full code for which I used in order to populate a new row in my CustomerInformation table.
<?php
// Connect to the database
mysql_connect ("localhost","username","password") or die ('Error: ' . mysql_error());
echo "connected to database!";
mysql_select_db ("database");
// Create variables to retrieve the POST data
$ID= $_POST['textbox1'];
$C_ID= $_POST['textbox2'];
$Value= $_POST['textbox3'];
$Count= $_POST['textbox4'];
$action = ' "<input type="submit" name="AddRow" value="Add New Row" />"';
// Insert data into table
$query = "INSERT INTO CustomerInformation (ID,C_ID,Value,Count,Action)
VALUES(
'".$ID."', '".$C_ID."', '".$Value."', '".$Count."','".$action."')";
mysql_query($query) or die ('Error updating database');
echo "Database updated successfully!";
?>
The only problem occurs when I include the line: $action = ' "<input type="submit" name="AddRow" value="Add New Row" />"';
I am clearly butchering this line, and I would greatly appreciate any help at all on this one!
The answer to your question is quite simply mysql_real_escape_string. Apply it on each string variable before you intermingle it with the SQL command.
It's simpler however not to bother with the old mysql_ API. You can keep the query separate from the data and avoid the effort with:
$db = new PDO('mysql:host=hostname;dbname=db', 'username', 'pwd');
$db->prepare(" INSERT INTO CustomerInformation
(ID,C_ID,Value,Count,Action) VALUES (?,?,?,?,?) ")
->execute(array($ID, $C_ID, $Value, $Count, $action));