I'm currently learning php and am testing around with sqli queries.
I want to have an input field where a number can be entered. This number is used in the sql-query. Unfortunately it doesn't work the way I want.
The text field is stored in index.php as this:
<form method="post" action="handler.php">
<input type="text" name="idEingabe">
<input type="submit" value="Abfrage für eingegebene ID starten">
</form>
In handler.php, I'm using
$stridEingabe = $_POST["idEingabe"];
And the query contains:
$query = 'SELECT name, beschreibung FROM uebersicht WHERE id = "$stridEingabe"';
$result = mysqli_query($con, $query);
if ($result = mysqli_query($con, $query)) {
/* Array ausgeben */
while ($row = mysqli_fetch_assoc($result)) {
printf ("<b>%s</b> <br>%s<br> <br>", $row["name"], $row["beschreibung"]);
}
/* free result set */
mysqli_free_result($result);
}
mysqli_close($con);
?>
Unfortunately I don't get any results when I enter the number into the text box and click the submit-button. But if I write the number in the query without using $stridEingabe, I'm getting the results.
Where is the mistake?
Thanks a lot
Seeing that an answer's been submitted before this, thought I'd put one in too and based on a comment I left under the question.
One of the problems here is, you're querying twice which is a major issue, resulting in a syntax error that MySQL is throwing in the background, but you're not listening for it. Plus, your quoting method which I've modified below, just in case it is a string; which we don't know at this time.
$query = 'SELECT name, beschreibung FROM uebersicht WHERE id = "$stridEingabe"';
$result = mysqli_query($con, $query);
^^^^^^^^^^^^
if ($result = mysqli_query($con, $query)) {
^^^^^^^^^^^^
/* Array ausgeben */
while ($row = mysqli_fetch_assoc($result)) {
printf ("<b>%s</b> <br>%s<br> <br>", $row["name"], $row["beschreibung"]);
}
what you want is to remove = mysqli_query($con, $query) and add error checking:
$query = "SELECT name, beschreibung FROM uebersicht WHERE id = '".$stridEingabe."'";
$result = mysqli_query($con, $query);
if ($result) {
/* Array ausgeben */
while ($row = mysqli_fetch_assoc($result)) {
printf ("<b>%s</b> <br>%s<br> <br>", $row["name"], $row["beschreibung"]);
}
} // brace for if ($result)
// else statement for if ($result)
else{
echo "There was an error: " .mysqli_error($con);
}
Or, better yet using mysqli_real_escape_string().
$stridEingabe = mysqli_real_escape_string($con,$_POST["idEingabe"]);
Although prepared statements are best.
Plus, in regards to SQL injection which is something you're open to, should be using mysqli with prepared statements, or PDO with prepared statements, they're much safer.
Footnotes:
Make sure you are indeed using mysqli_ to connect with and not another MySQL API such as mysql_ or PDO to connect with. Those different APIs do not intermix with each other.
I say this because, the connection method is unknown in your question.
Plus, if you're using your entire code inside the same file, then you should be using a conditional statement for your POST array, otherwise it will thrown a notice immediately on page load; assuming error reporting is enabled on your system.
The notice would be "Undefined index idEingabe..."
I.e.:
if(!empty($_POST['idEingabe'])){...}
Another thing; if your inputted value is an integer, you can use the following functions to make sure they are integers and not a string, if that is what the ultimate goal is:
http://php.net/manual/en/function.is-int.php - is_int()
http://php.net/manual/en/function.is-numeric.php - is_numeric()
and using a conditional statement in conjunction with those.
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.
Two things, first your quotes are wrong, and second, with your code you are vulnerable to sql code injection attacks, try this instead:
$stridEingabe = mysql_real_escape_string($_POST["idEingabe"]);
$query = "SELECT name, beschreibung FROM uebersicht WHERE id='$stridEingabe'";
The problem is that you are not concatenating the $string to the query
Use something like
$query = 'SELECT name, beschreibung FROM uebersicht WHERE id = ''.$stridEingabe.'';
Or use double quotes which is way more acceptable
$query = "SELECT name, beschreibung FROM uebersicht WHERE id = '$stridEingabe'";
And try to use only the $results declared in the if statement to avoid double queries.
You are using wrong quotes. try this:
$query = "SELECT name, beschreibung FROM uebersicht WHERE id = '$stridEingabe'";
Related
I'm having trouble updating a site. With security in mind, I am trying to rewrite the SQL statements using PDO prepared. It's my preferred choice generally.
The site I'm working on has this query, returning results via json to a search box. It works ...
$sql = "SELECT * FROM stock_c_ranges WHERE deleted = 'no' AND current_status = 'current'";
$result = mysqli_query($conn, $sql);
$results_list = array();
while($row = mysqli_fetch_array($result)){
$results_list[] = $row['manufacturer_name'].' ID:'.$row['id'];
}
echo json_encode($results_list);
I've re-written using prepared statements ...
$range = "SELECT * FROM stock_c_ranges WHERE deleted= :deleted AND current_status= :cstatus";
$deleted='no';
$c_status='current';
$result_lists=array();
$stmt=$pd_con->prepare($range);
$stmt->bindParam(':deleted',$deleted,PDO::PARAM_STR);
$stmt->bindParam(':cstatus',$c_status,PDO::PARAM_STR);
$stmt->execute;
while($row=$stmt->fetch(PDO::FETCH_ASSOC)){
$results_list[] = $row['manufacturer_name']. 'ID:'.$row['id'];
}
echo json_encode($results_list);
..... this doesn't
I've either made a glaring syntax error that I'm just blind to after looking at it for so long, or there is something about using PDO and JSON/AJAX that I'm not aware of stopping it functioning.
Apologies, writing it on here has highlighted the glaringly obvious ...
$stmt->execute;
Should have been ...
$stmt->execute();
I want to get some data from sql server using php but the sql doesn't seem reading the php variable
<?php
$q = $_POST["fl"];
echo $foo;
if ($_POST["fl"] == true);
{
$conn1=odbc_connect('SQLDB','','');
if (!$conn1)
{exit("Connection Failed: " . $conn1);}
$sql1= "SELECT * FROM dbo.Audit WHERE Details = '$q'";
$rs1=odbc_exec($conn1,$sql1);
if (!$rs1)
{exit("Error in SQL");}
while (odbc_fetch_row($rs1))
The best way to do that is:
$stmt = odbc_prepare($conn1, "SELECT * FROM dbo.Audit WHERE Details = ?");
$success = odbc_execute($stmt, array(PDO::quote($_POST["fl"])));
You're testing for the presence of your $q incorrectly. You should have something more like:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (isset($_POST['fl'])) {
$q = $_POST['fl'];
$sql = "SELECT ... WHERE Details = '$q'":
etc..
} else {
die("No fl value was passed");
}
}
Also note that I have not corrected your SQL injection vulnerability. Your code, even if it was working, is just begging to get your database trashed.
To avoid the apparent downvote party I'm not going to post any SQL, but yadda yadda SQL injection, yadda yadda input validation, etc.
Your problem is:
if ($_POST["fl"] == true); //<-- this semicolon, get rid of it
{
$conn1=odbc_connect('SQLDB','','');
Aside from that your code is syntactically fine, though you should be using if(isset($_POST['f1'])) in place of if ($_POST["fl"] == true).
You can use PDO object for making a select query to the database....
$q = $_POST['fl'];
$pdo=new PDO('mysql:host=localhost;dbname=databasename','username','password');
$query="select * from dbo.Audit WHERE Details = :q;";
$result=$pdo->prepare($query);
$result->bindValue(':q',$q);
$result->execute();
First things first, please sanitize the post before you put it inside an SQL query.
You have to use htmlentities or even better, PDO.
Second, you can try this if your current one doesn't work:
$sql1 = "SELECT * FROM dbo.Audit WHERE Details = '".$q."'";
I am trying to select a table within my database with a GET Method.
Now when I hardcode the value of the variable in there (the table name) it works as expected and it returns the values in an array.
But when I try to determine the table name through a variable, I get the following error:
Fatal error: Call to a member function fetch_array() on a non-object in
Now I have tried the var_dump($result); but that returns bool(false).
Now the variable does carry a value, because when I echo it back to the screen it gives the value I would expect.
So why does not return the value when making the query for my table search???
$result = $mysqli->query("SELECT * FROM PodcastSermons WHERE sermonSeries = ". $series); //This where a change needs to happen
var_dump($result);
$posts = array();
while($row = $result->fetch_array())
{
$ID=$row['ID'];
$sermonTitle=$row['sermonTitle'];
$sermonSpeaker=$row['sermonSpeaker'];
$sermonSeries=$row['sermonSeries'];
$sermonDate=$row['sermonDate'];
$linkToImage=$row['linkToImage'];
$linkToAudioFile=$row['linkToAudioFile'];
$posts []= array (
'ID'=> $ID,
'sermonTitle'=> $sermonTitle,
'sermonSpeaker'=> $sermonSpeaker,
'sermonSeries'=> $sermonSeries,
'sermonDate'=> $sermonDate,
'linkToImage'=> $linkToImage,
'linkToAudioFile'=> $linkToAudioFile
);
}
$response['posts'] = $posts;
var_dump($posts);
PS I have read about the depreciation in mysql style and that I know have to use mysqli writing. I am running PHP Version 5.2.6-1+lenny16
If the $series is a string you need to put quotes around the variable..
Try...
$result = $mysqli->query("SELECT * FROM PodcastSermons WHERE sermonSeries = '". $series ."'");
Hope it helps.
Now I have tried the var_dump($result); but that returns bool(false).
Because your query failed.
Try:
if( ! $result = $mysqli->query("SELECT * FROM PodcastSermons WHERE sermonSeries = ". $series); ) {
echo "An error has occurred: \n" . var_export($mysqli->error_list, TRUE);
} else {
//do stuff
}
The central question seems to me: Where does $series come from? Where does that variable ever get initialized?
If you're passing this in from the web form, two things: either use $_GET or $_POST (whatever action you use in your form). And then you have to sanitize what comes from there, in order to not be vulnerable to SQL injection attacks. Prepared statements are your friend in this case; they help harden your script against this kind of attacks.
try this
$result = $mysqli->query("SELECT * FROM PodcastSermons WHERE sermonSeries = '$series' ");
$result = $mysqli->query("SELECT * FROM PodcastSermons WHERE sermonSeries = ". $series); //This where a change needs to happen
You should be using Prepared Statements if the variable: $series is user defined.
$result->prepare("SELECT * FROM PodcastSermons WHERE `sermonSeries`=?");
$result->bind_param('s', $series);
$result->execute();
Also, Print_r($result); to check if your initial $result to see if it has been populated; Furthermore, in your SQL Query is sermonSeries properly matched to your SQL Table?
Update:
while($row = $result->fetch_array())
{
Try Modifying this to:
while($row = $result->fetch_array(MYSQLI_ASSOC))
{
http://uk1.php.net/manual/en/mysqli-result.fetch-array.php
your query simply fails. check var_dump($series); before executing.
i assume it might be a string and you just don't quote it?
just a tip: first build a string with your commandtext before
calling $mysqli->query. and use that string (like $mysqli->query($cmd);
dump that string :) might open your eyes ;)
that way you can extract it and execute it directly against the database (f.e. phpmyadmin).
I have a mySQL database from where I fetch some data via PHP.
This is what I've got:
if ($db_found) {
$URL_ID = $_GET["a"];
$SQL = "SELECT * FROM tb_employees WHERE URL_ID = $URL_ID";
$result = mysql_query($SQL);
while ($db_field = mysql_fetch_assoc($result)) {
$firstname = $db_field['firstname'];
$surname = $db_field['surname'];
$function = $db_field['function'];
$email = $db_field['email'];
$telnr = $db_field['telnr'];
}
mysql_close($db_handle);
}
else {
print "Database not found... please try again later.";
mysql_close($db_handle);
}
The URL_ID field in my mySQL database is, for this example, 001. When I go to www.mydomain.com/index.php?a=001 it fetches all the data, puts it into a variable, and I can echo the variables without any problem.
Now, I want to change the URL_ID, and I've changed it to "62ac1175" in the mySQL database. However, when I proceed to www.mydomain.com/index.php?a=62ac1175, I get this error message:
Warning: mysql_fetch_assoc() expects parameter 1 to be resource,
boolean given in
mydomain.com\db_connect.php on line 17
The field in mySQL has varchar(8) as type and utf8_general_ci as collation.
If I change the entry back to 001 and change my URL to ?a=001, it works fine again.
What's going wrong?
You are not doing any error checking in your query, so it's no wonder it breaks if the query fails. How to add proper error checking is outlined in the manual on mysql_query() or in this reference question.
Example:
$result = mysql_query($SQL);
if (!$result)
{ trigger_error("mySQL error: ".mysql_error());
die(); }
your query is breaking because you aren't wrapping the input in quotes. You can avoid* quotes only for integers (which 62ac1175 is not). Try
$SQL = "SELECT * FROM tb_employees WHERE URL_ID = '$URL_ID'";
Also, the code you show is vulnerable to SQL injection. Use the proper sanitation method of your library (like mysql_real_escape_string() for the classic mysql library that you are using), or switch to PDO and prepared statements.
In your code, this would look like so: Instead of
$URL_ID = $_GET["a"];
do
$URL_ID = mysql_real_escape_string($_GET["a"]);
* however, if you avoid quotes, mysql_real_escape_string() won't work and you need to check manually whether the parameter actually is an integer.
Hi i am too new too php and mysql and i want to count the member number due to the search made by user. However, mysql_num_rows doesnt work.
mysql_num_rows(mysql_query("SELECT * FROM members WHERE $title LIKE '%$_POST[search]%' LIMIT $start,$member_number"));
It says "mysql_num_rows(): supplied argument is not a valid MySQL result resource in ..."
NOTE: $title is a select menu which user choose where to search. LIMIT is, as you know :), number of member which is shown in a page.
And also $start= ($page-1)*$member_number; in order to set the first entry in that page. I think the problem is here but i cant solve it. :(
Your query probably has an error, in which case mysql_query will return false.
For this reason, you should not group commands like this. Do it like this:
$result = mysql_query("...");
if (!$result)
{ echo mysql_error(); die(); } // or some other error handling method
// like, a generic error message on a public site
$count = mysql_num_rows($result);
Also, you have a number of SQL injection vulnerabilities in your code. You need to sanitize the incoming $search variable:
$search = mysql_real_escape_string($_POST["search"]);
... mysql_query(".... WHERE $title LIKE '%$search%'");
if $start and $end come from outside, you also need to sanitize those before using them in your LIMIT clause. You can't use mysql_real_escape_string() here, because they are numeric values. Use intval() to make sure they contain only numbers.
Using a dynamic column name is also difficult from a sanitation point of view: You won't be able to apply mysql_real_escape_string() here, either. You should ideally compare against a list of allowed column names to prevent injection.
you have to use GET method in your form, not POST.
mysql_num_rows doesn't make sense here.
If you're using limit, you already know the number*.
If you want to know number, you shouldn't use limit nor request rows but select number itself.
// get your $title safe
$fields = array("name","lastname");
$key = array_search($_GET['title'],$fields));
$title = $fields[$key];
//escape your $search
$search = mysql_real_escape_string($_GET['search']);
$sql = "SELECT count(*) FROM members WHERE $title LIKE '%$search%'";
$res = mysql_query($query) or trigger_error(mysql_error()." in ".$sql);
$row = mysql_fetch_row($res);
$members_found = $row[0]
in case you need just 5 records to show on the page, no need for mysql_num_rows() again:
// Get LIMIT params
$member_number = 5;
$start = 0;
if (isset($_GET['page'])){
$start = abs($_GET['page']-1)*$member_number;
}
// get your $title safe
$fields = array("name","lastname");
$key = array_search($_GET['title'],$fields));
$title = $fields[$key];
//escape your $search
$search = mysql_real_escape_string($_GET['search']);
$sql = "SELECT count(*) FROM members
WHERE `$title` LIKE '%$search%'
LIMIT $start, $member_number";
$res = mysql_query($query) or trigger_error(mysql_error()." in ".$sql);
while($row = mysql_fetch_assoc($res){
$data[] = $row;
}
Now you have selected rows in $data for the further use.
This kind of error generally indicates there is an error in your SQL query -- so it has not been successful, and mysql_query() doesn't return a valid resource ; which, so, cannot be used as a parameter to mysql_num_rows().
You should echo your SQL query, in order to check if it's build OK.
And/or, if mysql_query() returns false, you could use mysql_error() to get the error message : it'll help you debug your query ;-)
Typically, your code would look a bit like this :
$query = "select ..."; // note : don't forget about escaping your data
$result = mysql_query($query);
if (!$result) {
trigger_error(mysql_error()." in ".$query);
} else {
// use the resultset
}