Why does my code not insert the data into the database? - php

<?php
require 'connect.inc.php';
$food= $_POST['food'];
$cost= $_POST['cost'];
$sqlinsert = "INSERT INTO test (eat, pay) VALUES ('$food','$cost')";
?>
<form method = "POST" action = "index.php">
Food: <input type = "text" name = "food">
<br/>
Cost: <input type = "text" name = "cost">
<br/>
<input type = "submit" value = "order">
</form>
Why does my code not work? index.php is fine, it connects well, but no output is shown in my database when I run this code.

You appear to be new at databases, seeing your other questions and this being the only one related to doing db work.
This line never gets executed:
$sqlinsert = "INSERT INTO test (eat, pay) VALUES ('$food','$cost')";
We don't know which MySQL API you are using to connect with; if it's mysql_, or mysqli_ or PDO, or other since you did not mention that in your question.
Depending on the API used, you need to run mysql_query(), or mysqli_query() or query()/execute() in PDO.
Consult the following links on how to do this:
http://php.net/manual/en/function.mysql-query.php
http://php.net/manual/en/mysqli.query.php
http://php.net/manual/en/pdo.query.php / http://php.net/manual/en/pdostatement.execute.php
Check for errors also using the same API you connected with, and seeing that you're more than likely running this code inside the same file, you need to use a conditional statement around your POST arrays to check if they're empty, and/or use an isset() on the submit button and giving it a "name" attribute.
I.e.: <input type = "submit" name = "submit" value = "order">
with if(isset($_POST['submit'])) {...}
Otherwise, you stand at getting errors thrown back.
If empty reference:
http://php.net/manual/en/function.empty.php
Note: Different MySQL APIs do not intermix, so you can't connect with mysql_ and query with mysqli_query() or PDO, keep this in mind.
Another thing is to make sure that data going into the database doesn't contain characters that MySQL will complain about such as apostrophes.
Therefore you will need to escape that data. This is good for another reason, avoiding a possible SQL injection; you should use a prepared statement for it.
References:
https://en.wikipedia.org/wiki/SQL_injection
https://en.wikipedia.org/wiki/Prepared_statement
Footnotes:
If you are using the mysql_ API to connect with, that API is deprecated and has been removed in PHP 7.0. If this is the case, then you will need to use either the mysqli_ or PDO API.

Related

Not giving the wanted output

So I'm having this issue with showing the output of a query. I will show my code and try to explain the best I can.
<?php
include_once('ligacao.php');
if (mysqli_connect_errno())
{
echo "Falha ao conectar à Base de Dados: ".mysqli_connect_error();
}
$pesq = $_POST['id'];
echo $pesq;
$sqlveri = "SELECT * FROM distrito WHERE iddistrito LIKE '12'";
$result = mysql_query ($ligar,$sqlveri);
echo $resul;
mysqli_close ($ligar);
?>
The only thing that appears when I submit is the number that is kept on the variable $pesq. Help me out here guys I have been grinding for an answer for 2 straight days with no luck at all
Thank you for your help.
Note to future visitors.
The original closure of their question was based on their original post where they were using mysql_fetch_array without the i, and changed it before it could be recorded in revisions.
Then completely changed their code https://stackoverflow.com/revisions/34335181/3 after I posted my answer.
Original answer based on the above
So you changed mysql_fetch_array to mysqli_fetch_array after I closed the question about your mixing MySQL APIs.
It is unclear as to which MySQL API you're using to connect with. mysql_, mysqli_, or PDO (those different APIs do not intermix).
Can I mix MySQL APIs in PHP?
Plus, you're not checking for errors.
Also, no idea what variable you are using to connect with.
http://php.net/manual/en/function.mysqli-connect.php
What's going on here is that you're not connecting to your query and I do not know what variable you are using.
So, base yourself on the following and change the variable to the one you're using in your connection file:
$result = mysqli_query($connection, "SELECT ...
mysqli_query() requires a connection:
http://php.net/manual/en/mysqli.query.php
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,
as well as or die(mysqli_error($connection)) to mysqli_query().
Your HTML form is also unknown, and if it is using a POST method and if the input does have the name attribute for it.
I.e.:
<form method="post" action="your_handler.php">
<input type="text" name="id">
</form>
Forms default to a GET if a POST method isn't specifically set. Therefore, that would trigger/cause an undefined index notice.
Sidenote: Make sure there are no whitespaces in your input/query. Use trim() and var_dump() as an additional tool.
Plus, if you're looking for an exact match, don't use LIKE, but a WHERE iddistrito = '$pesq'");
Read up on LIKE: http://dev.mysql.com/doc/refman/5.7/en/pattern-matching.html
There are wildcards you can use, if pattern matching is required.
Your present code is open to SQL injection. Use mysqli_* with prepared statements, or PDO with prepared statements.

Can't Get Simple SQL Insert to Work

<?php include_once("database.php");
?>
<?php include_once("header.php");
?>
<?php
if ($_POST['submit'] )
{
$food_name = $_POST['food_name'];
$food_calories = $_POST['food_calories'];
echo $food_name . $food_calories;
if (!empty($food_name) && !empty($food_calories) )
{
$query = 'INSERT INTO foods VALUES(0, $food_name, $food_calories)';
mysqli_query($con, $query) or die(mysqli_error($con));
echo 'added';
} else {echo'fail';}
} else {echo'fa2oo';}
?>
<h1> Please Fill out Form Below to Enter a New Food </h1>
<form action="addfood.php" method="post">
<p>Name:</p>
<input type="text" name="food_name"/>
<p>Calories:</p>
<input type="text" name="food_calories"/> </br>
<input type="submit" value="submit" />
</form>
<?php include_once("footer.php")?>
Really don't understand why this simple insert is not working. The form is self-referencing. The form does not echo anything and simply resets when i hit the submit button. database connects with no errors.
Since you're inserting strings, you need to enclose them by single quotes ('):
$query = "INSERT INTO foods VALUES(0, '$food_name', $food_calories)";
Note, however, that building an SQL statement by using string manipulation will leave your code vulnerable to SQL inject attacks. You'd probably be better off using a prepared statement.
You have a few errors in your code:
1. Missing name attribute
You are missing the name attribute for your submit button. So add it like this:
<input type="submit" name="submit" value="submit" />
//^^^^^^^^^^^^^
2. Wong variables in empty()
You have to check if the $_POST variables are empty! Otherwise you would try to assign an undefined variable to another variable. So change your second if statement to this:
if (!empty($_POST['food_name']) && !empty($_POST['food_calories']) )
//^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^
And also put the assignments inside the second if statement.
$food_name = $_POST['food_name'];
$food_calories = $_POST['food_calories'];
3. Wrong quotes + missing quotes
You have to use double quotes that your variable in the query gets parsed as variables. Also you have to put single quotes around them since they are strings, so change your query to this:
$query = "INSERT INTO foods VALUES(0, '$food_name', '$food_calories')";
//^ ^ ^ ^ ^
Side notes:
Add error reporting at the top of your file(s) to get useful error messages:
<?php
ini_set("display_errors", 1);
error_reporting(E_ALL);
?>
You may also want to change to mysqli with prepared statements since they are, much safer.
Here's the safe way of doing this using mysqli. Prepared statements will make sure you don't have (as high of) a risk of SQL injection
editing to include the connection:
$conn = new mysqli($host, $username, $password, $dbname);
If you want to see errors, you need to tell php to give the the errors. this should suffice:
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
This part is how to do the query.
Note the bind_param part; this is where you identify how your variables are going to into the database, and what datatype they need, so you don't need to remember which items to put in quotes in the actual query.
$query = $conn->prepare("INSERT INTO foods VALUES(0, ?, ?)");
$query->bind_param("si",$food_name, $food_calories);
$query->execute();
$query->close();
As mentioned before, $food_name is a string, so you specify it as such with the s in the bind_param and assuming that calories are an integer, they go in as i.
Another nice feature of using this approach is you no-longer need to worry about escaping variables; items in inputs go in exactly as they are entered
If you want more information in detail there's always this reliable source:
http://php.net/manual/en/mysqli.quickstart.prepared-statements.php
If you find this a bit too much, here's a great site to learn step by step how to use prepared statements from scratch (it also includes PDO but you may find it easier to use the mysqli at first and it still pretty good). http://www.w3schools.com/php/php_mysql_prepared_statements.asp
Have fun!
There are a few things wrong here.
Firstly, anything inside this conditional statement will not happen because of your submit button not bearing the "submit" name attribute.
if ($_POST['submit'] ){...}
However, it's best using an isset() for this.
if (isset($_POST['submit'] )) {...}
Modify your submit to read as:
<input type="submit" name="submit" value="submit" />
^^^^^^^^^^^^^
Then, we're dealing with strings, so wrap the variables in your values with quotes.
Wrap your query in double quotes and the values in single quotes:
$query = "INSERT INTO foods VALUES (0, '$food_name', '$food_calories')";
Sidenote #1: If you experience difficulties, use the actual column names in which they are to go inside of.
I.e.: INSERT INTO table (col1, col2, col3) VALUES ('$val1', '$val2', '$val3')
Sidenote #2: Make sure that 0 for your column is indeed an int, however I don't know why you're using that.
If that column is an auto_increment, then replace the 0 with '' or NULL, should your schema accept it.
Now, should there be any character that MySQL may complain about, being quotes, etc., then you will need to escape/sanitize your data.
Say someone entered Tim's donuts in an input:
MySQL would translate that in your values as 'Tim's donuts', in turn throwing a syntax error.
Using mysqli_real_escape_string() for instance, would escape the apostrophe and render it as 'Tim\'s donuts' being a valid statement since it has been escaped.
Better yet, using prepared statements, as outlined below.
In its present state, your present code is open to SQL injection. Use prepared statements, or PDO with prepared statements, they're much safer.
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: Error reporting should only be done in staging, and never production.
Footnotes:
Given that we don't know which MySQL API you are connecting with, please note that different APIs do not intermix with each other.
For example:
You can't connect using PDO and querying with mysqli_
You can't connect using mysql_ and querying with mysqli_
etc. etc.
You must be consistent from A to Z, meaning from connection to querying.
Consult Choosing an API on PHP.net
https://php.net/mysqlinfo.api.choosing
Final closing note(s):
As stated by Rizier123, you are best using:
if (
!empty($_POST['food_name'])
&&
!empty($_POST['food_calories'])
)
It is a better solution.
Your issue (at least one of them) might be the SQL statement itself. Depending on the columns that you have in this foods table, you'll be required to specify the columns that you're inserting into. Try this:
INSERT INTO foods (col1, col2, col3) VALUES (val1, val2, val3)
Also, if val1 is supposed to be the ID column, you can't specify a value for that if it's auto-incrementing... the db will take care of that for you.

Cannot print data from MySQL Query with PHP

I am writing a PHP script that is supposed to interact with a MySQL database. On my local testing server, the code echos out what it is supposed to just fine, but in the live environment, I get an error saying Fatal error: Call to a member function fetch_array() on a non-object in [file path removed for security] on line 42. Here is my code from around line 42.
$query = "SELECT " . $data . " FROM mySchemaTable WHERE incrementId = " . $something;
$result = mysqli_query($conn,$query);
$row = $result->fetch_array(MYSQL_BOTH); // This line is 42.
echo $row['0'];
break;
I noticed a few problems with your code:
Firstly, you're mixing OOP and Procedural programming with MySQLi commands. Although PHP allows this, you'll want to make that uniform throughout. If you're using $conn = mysqli_connect(parameters here); you'll want to focus on procedural (change $result->fetch_array(MYSQLI_BOTH) to mysqli_fetch_array($conn, MYSQLI_BOTH); for instance). (I would assume you're doing this, so do this ^ change)
Else, if it's $conn = new mysqli(parameters); then you'll want to make it OOP based; instead of mysqli_query($sql); you'd use $conn->query($sql);, assuming $sql contains the query you want to run.
Secondly, echo $row['0']; should be echo $row[0]; unless the row you're returning is actually named 0, in which case disregard this.
Thirdly, and as a side note, it's a bad idea to directly insert variables into SQL queries, especially if they're user generated. You should look into sanitizing input or prepared statements to protect against SQL injection attacks.
Sanitizing Input Reference: What's the best method for sanitizing user input with PHP?
Prepared Statements: http://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php
The problem was solved without my intervention. It turns out that my code was fine as it was, but something was wrong with my host's MySQL. It's fixed now, and everything is working again.

PHP Retrieve Database Value

So i have this so far..
if(isset($_POST['Decrypt']))
{
$dbinary = strtoupper($_POST['user2']);
$sqlvalue = "SELECT `value` FROM `license` WHERE `binary` = '$dbinary'";
$dvalue = mysql_query($sqlvalue) or die(mysql_error());
}
I have a field where the user enters a binary code which was encrypted. (The encrypt part works). This is supposed to retrieve the value from the database. When ever i do it, instead of the value showing up, it says "Resource id #11".
There's nothing wrong with your quoting. In fact, everything looks right so far.
The thing is, right now $dvalue is just a resource to the SQL database. You have to fetch the contents with one more line:
$dvalue = mysql_fetch_array($dvalue);
In the future, you might want to start using PDO or MySQLi instead of the mysql functions, because those are deprecated as of 5.5.0. The advantage of PDO and MySQLi is that they offer security from SQL Injection, which is when users run their own SQL code by inputting something like x'; DROP TABLE members; --.
Don't use the mysql_ functions anymore. They are deprecated. Use PDO or MySQLi instead.
That being said, you are only running the query, and not retrieving any results. You will have to call a function like mysqli_fetch_array to get data from the resource ID that mysqli_query will return.
My advice is to go back to the tutorials and documentation and try again with one of these other extensions. Good luck.
Read this page: W3 Schools page on MySQL select useage. Basically $dvalue is a result set id and you'll need to actually fetch the array out of the database in another step. Also, mysql_* functions are deprecated. Lookup and use the mysqli_* functions instead.
while($row = mysqli_fetch_array($dvalue))
{
echo $row['value'];
echo "<br>";
}

Should I use mysqli_real_escape string() or mysql_real_escape_string() for form data? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
mysql_escape_string VS mysql_real_escape_string
I need to get company_name (given by user through a form) entered into my mysql database.
When I use
$company = mysqli_real_escape_string($_POST['company_name'])
I get an error
Warning: mysqli_real_escape_string() expects exactly 2 parameters, 1 given in /opt/lampp/htdocs/Abacus-Version-2/admin/Company/insert_company.php on line 58
But everything seems to fine while using
$company = mysql_real_escape_string($_POST['company_name'])
What can I do in such cases?
The one to use depends on whether you are using the MySQLi extension or the MySQL extension
// procedural mysqli
$db = new mysqli;
$sql = sprintf("INSERT INTO table (id,name,email,comment) VALUES (NULL,'%s','%s','%s')",
mysqli_real_escape_string($db,$name),
mysqli_real_escape_string($db,$email),
mysqli_real_escape_string($db,$comment) );
// mysql
$conn = mysql_connect();
$sql = sprintf("INSERT INTO table (id,name,email,comment) VALUES (NULL,'%s','%s','%s')",
mysql_real_escape_string($name,$conn),
mysql_real_escape_string($email,$conn),
mysql_real_escape_string($comment,$conn) );
mysql_real_escape_string() is designed to make data safe for insertion into the database without errors. (IE such as escaping slashes so that it doesn't break your code).
You should use mysql_ or mysqli_ functions to match your connection string. "mysqli" is the object oriented implementation of the mysql set of functions, so the functions are called in the object oriented style. "mysql" is procedural. I'd suggest changing over to "mysqli" because I believe there has been talk of depreciating the "mysql" functions in future versions.
If you connection string is:
mysql_connect()
then use:
mysql_real_escape_string($_POST[''])
If it is:
$mysqli = new mysqli();
then use:
$mysqli->real_escape_string($_POST[''])
Definitely NO
Both functions has nothing to do with form data.
They have to be used to format string literals inserted into SQL query only.
This function belongs to the SQL query, not to whatever form. And even to very limited part of the query - a string literal.
So, every time you're going to insert into query a string literal (frankly, a portion of data enclosed in quotes), this function ought to be used unconditionally.
For the any other case it shouldn't be used at all.
As for the error you're getting - it's pretty self-explanatory: this function expects 2 parameters, not one. Just pass proper parameters as stated in the manual page for this function, and you'll be okay
It should be this if you use Procedural style:
$city = mysqli_real_escape_string($link, $city);
where link is the connection
or this when you use Object oriented style:
$city = $mysqli->real_escape_string($city);
Check out the php manual:
http://php.net/manual/en/mysqli.real-escape-string.php
Since all the MySQL extension is being deprecated, you'd best use the MySQLi methods instead, it's more future proof.
Both variants are fine* (Please look at my Update).
When you are using a mysql_connect then you should stick to mysql_real_escape_string() and also pass the connection handle.
When you are using a mysqli_connect then you should stick to mysqli_real_escape_string().
UPDATE
As pointed out by Jeffrey in the comments, using mysql_ functions is NOT fine. I agree to that. I was just pointing out, that you need to use the function that is used by the MySQL-extension you are using.
It came to me, that it was not the question, which MySQL-extension to use, but which function for escaping data.
If you ask me:
Use mysqli or PDO, because mysql is not recommendable and deprecated.
Pass the Connection Handle to the escape-function or better
use prepared Statements (PDO-Style)

Categories