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.
Related
<?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.
So, I'm working with PHP and prepared statements sent to a MySQL database. I've ran into a problem that I can't quite debug. Here is my code:
// Check if the input username is in the database
$stmtQuery = "SELECT * FROM updatedplayers WHERE Player=?;";
$preparedStmt = $dbc->prepare($stmtQuery);
$preparedStmt->bind_param("s", $setUsername);
$preparedStmt->execute();
$preparedStmt->bind_result($resultUUID, $resultUsername);
$preparedStmt->fetch();
// If it's not, kill the page.
if ($resultUUID == null) {
incorrect();
}
$stmtQuery = "SELECT Password, Salt FROM logins WHERE UUID=?;";
echo 'flag1 ';
$preparedStmt = $dbc->prepare($stmtQuery);
echo 'flag2 ';
$preparedStmt->bind_param("s", $resultUUID);
echo 'flag3 ';
The fist prepared statement works fine, it's at the line $preparedStmt->bind_param("s", $resultUUID);. There are also a couple other prepared statements before these, so I know I'm doing this correctly, but I'm not too sure about the last statement.
The code just seems to stop running after echo 'flag2 ';, which I put there to find the specific line. I don't get any error messages, it just doesn't print out flag3.
I've tried replacing $resultUUID with a static string, yet I get the same outcome. Also, I know my SQL statement is correctly formatted, I've tested within the console manually.
That's pretty much it, I'd love to hear some criticism, as I am new to PHP. Also, is there any way to get a better idea about the errors I get, instead of trying to pinpoint the error myself? Thanks!
So, adding ini_set('display_error', 1);, suggested by #user2182349, gave me a little more insight, I got "Fatal error: Call to a member function bind_param() on boolean".
After some research, I tried adding mysqli_report(MYSQLI_REPORT_ALL);, which ended up throwing "No index used in query/prepared statement".
I did some research on that to realize that it wasn't a problem, just MySQLI reporting unnecessary errors (which is what I asked it to do lol). In order to get a better, more insightful stack trace, I used mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);.
This threw "Commands out of sync; you can't run this command now". Again, more research taught me to use $preparedStmt->store_result();, in order to allow for another prepared statement to run.
Big thanks to all y'alls' help, hope this can help someone too.
You should be able to use a single select statement similar to this:
SELECT u.UUID, u.Username, l.Password, l.Salt
FROM updatedplayers AS u
JOIN logins AS l ON (u.UUID = l.UUID)
WHERE u.Player = ?
Check the case of the field names to be sure they match the database.
At the top of the file, add ini_set('display_errors',1);. If you have any PHP errors, they will be displayed. Also check the return values from the database calls and use the error display functions.
I think you need to close the prepared statement before you use the variable for another query:
$preparedStmt->close();
Or use another variable name like $preparedStmt2 for the second query.
I would suggest you should start using PDO... I have issues encountered with mysqli prepared statement years ago. Since then, PDO gives me no headaches when it comes to multiple queries at a time.
You should try PDO.. :-) it's more efficient.
http://php.net/manual/en/intro.pdo.php
http://php.net/manual/en/class.pdostatement.php
Or you can do the following "if you want alternative solution"..
//Close connection
$preparedStmt->close();
//AND OPEN YOUR CONNECTION AGAIN TO PREPARE NEW QUERIES..
$stmtQuery = "SELECT Password, Salt FROM logins WHERE UUID=?;";
echo 'flag1 ';
$preparedStmt = $dbc->prepare($stmtQuery);
echo 'flag2 ';
$preparedStmt->bind_param("s", $resultUUID);
echo 'flag3 ';
<?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.
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.
I'm using ajax to gather the ckeditor data to be submitted. The problem is only the content before the first apostrophe is being submitted to the database. What could I be doing wrong?
Edit:
$date = strtotime($formData['date']);
$article=mysql_real_escape_string($formData['article'],$DBconnect);
$DBconnect=mysql_connect($dbVals['host'],$dbVals['user'],$dbVals['pass']);
mysql_select_db($dbVals['db'], $DBconnect);
$SQLstring="INSERT INTO PressRelease (ip, tym, title, date, article) VALUES('${_SERVER['REMOTE_ADDR']}', ".time().",'${formData['title']}', '$date', '$article')";
I'm fairly new at this so if there is anything else you need to see in order to help let me know.
It sounds like you aren't escaping the text data before you insert it into the database. Use this function on the data before you pass it into your SQL query:
http://www.php.net/manual/en/function.mysql-real-escape-string.php
Edit: sorry, that's assuming you are using MySQL.
A different, more complicated, and arguably superior method to the one suggested by Mark, is using Parameterized Statements.
To borrow an example from Wikipedia:
<?php
$db = new mysqli("localhost", "user", "pass", "database");
$stmt = $db -> prepare("SELECT priv FROM testUsers WHERE username=? AND password=?");
$stmt -> bind_param("ss", $user, $pass);
$stmt -> execute();
?>
It leaves the escaping up to the MySQL driver, severely reducing the chance of SQL Injection and things like accidental double-escaping.
Note that this is not possible using the old MySQL functions. You need the Improved MySQLI functions/object, or something like PDO.
If I understand correctly the following is the case:
You've got a textarea that's "taken over" by CKeditor
You're reading the content of that textarea with Javascript
You're sending the gathered content to the server with AJAX
If you alert() the content that Javascript gets from the textarea, you can see whether step 2 succeeds. If not, please post your Javascript.
If step 2 is correct, then maybe there's a problem server side, dump your db query to look at that.
Update:
Make sure you when you're developing that you turn on all errors and notices. And if you're doing stuff which you can't "see" easily, like AJAX, make sure to keep an eye on your server's error log.
In your code example line 2 you use $DBconnect, and then in line 4 you define what that is. As you can see in the PHP.net entry for mysql_real_escape_string if the function cannot find a connection to the database the function generates an error and returns FALSE. The FALSE is put into your database and that's what goes into your database.
My advice to you is: try harder at debugging. Test all your assumptions, test the value of variables at every step, check if they have the value you expect them to have. Use var_dump(), print_r(), echo and die(). Or if you want something more advanced use a debugger (I don't).