I stuck on something stupid..
I have the table that has only one column.
I want to check if there is some value, which I get from the url (method $_GET)
mysql_connect("localhost", "user", "pass") or die(mysql_error());
mysql_select_db("db") or die(mysql_error());
$row=htmlspecialchars($_GET['row']);
$query = #mysql_query ("SELECT * FROM table WHERE row=$row");
if ($result = #mysql_fetch_array($query)) {
echo "There is that row";
}
else {
echo "There is not that row";
}
Can you tell me what's wrong?
The correct way would be to check if the resultset contains any rows. You can do this with mysql_num_rows():
if (mysql_num_rows($query)>0) {
echo "There is that row";
}
else {
echo "There is not that row";
}
Also if your $row is a string, you should enclose it in single quotes.
Note:
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
Obligatory "you should be using PDO" comment.
You don't say what sort of field it is, maybe it is a text field so it needs to be in quotes.
$query = #mysql_query ("SELECT * FROM table WHERE row='" . $row . "');
Also if you remove the # you might get to see some sort of error
$query = mysql_query ("SELECT * FROM table WHERE row='" . $row . "') or die(mysql_error());
You seem to mix row and column. When querying SQL database you usually specify clumnName="value" after WHERE statement. You have valid syntax for a table with one column named "row".
There might be a problem in your query as you do not escape your arguments, so it will fail it $row actually has any quotes in it. This would be avoided with use of PDO instead of mysql_ functions which are no longer maintained. Query your table like this instead:
$query = #mysql_query("SELECT * FROM gvar WHERE gvarebi='{addslashes($row)}'");
To actually check if there are any results, it is better to use mysql_num_rows as it will return number of rows for specified query. So update your code with this:
if (mysql_num_rows($query) > 0) {
echo "row exists";
} else {
echo "row does not exists";
}
Related
I think the error is with SQL query or just the numrows funtion?
A few more things might be wrong because i've made alot of changes and am totally confused now.
Can anybody tell what is wrong with mysqli_num_rows in this code please?
Thanks in advance.
<?php
$i=0;
$key=$_GET['abc'];
$ex=explode(" ", $key);
$query="SELECT * FROM search";
/*foreach ($ex as $val)
{
$i++;
if($i == 1)
$query .="keywords like '%$val%' ";
else
$query .="or keywords like '%$val%' ";
}*/
$con=mysqli_connect("localhost","xxxxxxx","xxxxxxx","search");
if (!$con)
die("Connection failed: " . mysqli_connect_error());
else
echo "Connected successfully";
mysqli_select_db($con,"search");
$queryy=mysqli_real_query($con,$query);
$nr =#mysqli_query($con, $queryy);
$row=mysqli_num_rows($nr);
if($row>0)
{
while($r=mysqli_fetch_assoc($queryy))
{
$id=$r['id'];
$title=$r['title'];
$description=$r['description'];
$keywords=$r['keywords'];
$link=$r['link'];
echo "<h2> <a href='$link'>$title</a></h2> $description <br /><br />";
}
}
else
echo "no results found for \"<b>$key</b>\" ";
?>
$queryy=mysqli_real_query($con,$query);
$nr =#mysqli_query($con, $queryy);
$row=mysqli_num_rows($nr);
mysqli_real_query() takes a query string and returns a boolean to indicate whether or not it was successful. The result can then be accessed through mysqli_store_result() or mysqli_use_result().
mysqli_query() takes a query string and either returns a mysqli_result object (in this case as it is a SELECT query) or a boolean to indicate success or failure. The result object can then be passed to other functions.
In your code, you pass the boolean indicator from the first function in place of a query string to the second function. This will obviously fail, and you shouldn't try to execute two queries anyway. You should simply remove the first one.
You should also remove the # error suppression and do proper error checking instead. For example:
$result = mysqli_query ($con, $query);
if ($result)
{
$rows = mysqli_num_rows ($result);
if ($rows > 0)
{
while ($r = mysqli_fetch_assoc ($result))
{
// Do stuff
}
}
else
{
echo "no results...";
}
}
else
{
// Query failed.
}
You will notice that I have given the variables more meaningful names. Note also that the mysqli_fetch_assoc() function takes a result parameter, not a query string.
Note also that for anything more complicated than a simple SELECT * query, you should probably be using prepared statements instead.
You should also escape your HTML output using htmlspecialchars() to avoid XSS attacks and generally embarrassing output failures. E.g.:
$link_h = htmlspecialchars ($link);
$title_h = htmlspecialchars ($title);
echo "<h2> <a href='$link_h'>$title_h</a></h2>...";
And so on.
EDIT
Why is only the first row being echoed and not all rows that meet the WHERE condition?
$sql="SELECT from_name, to_name FROM private_messages WHERE from_id='$var' OR to_id='$var'" ;
$sql2 = mysql_query($sql);
$row = mysql_fetch_array($sql2);
echo $row['from_name'];
echo $row['to_name'];
Use a "while fetch" loop.
Here's an example of the pattern, using the mysqli interface.
(NOTE: The PHP mysql interface is deprecated. New development should use PDO or mysqli.)
if ($sth = mysqli_query($con, $sql) {
//echo "#debug: query returned a result set";
while ($row = mysqli_fetch_assoc($sth)) {
//echo "#debug: fetched next row";
echo $row['from_name'];
}
//echo "#debug: exited while loop, last row already fetched";
} else {
//echo "#debug: query execution returned FALSE, handle error";
}
This is the same as the pattern used with the deprecated mysql interface. (Is there some reason you are using that interface? N.B. Do not mix mysqli_ and mysql_ functions.
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'";
I have code
$email = "jb#tlb.com";
$row = mysql_query("SELECT EXISTS(SELECT email FROM accounts WHERE email='".$email."');");
echo $row[0];
However, nothing is echoed.
This is strange because something is being returned because, later in the code I have a function that is CALLED:
if ( $row[0] == 0 ) { echo "Email address is available<br>";};
However: this is strange because when i put the SAME CODE into mySQL database command prompt:
It clearly returns 1 or TRUE.
The mysql_query is returning 0 when the same exact command in mysql command prompt returns 1. Further: I am unable to echo the result for debugging purposes.
EDIT: Please not, the regular mySQL command is returning this and ONLY this:
EDIT: Here is there entire database:
MySQL query gives you a ressource. After that you have to fetch the data with mysql_fetch_assoc or mysql_fetch_row or something else for example. But its better to use prepared statements with mysqli or PDO to get more security.
$email = "jb#tlb.com";
$res = mysql_query("SELECT EXISTS(SELECT email FROM accounts WHERE email='".myql_real_escape_string($email)."')");
$row = mysql_fetch_assoc($res);
echo $row['email'];
Answer to your question:
$email = "jb#tlb.com";
$res = mysql_query("SELECT email FROM accounts WHERE email='".mysql_real_escape_string($email)."')");
$numRows = mysql_num_rows($res);
if($rowRows > 0) {
echo "Record Available";
}
You need to actually retrieve the result set from the query. mysql_query() just returns a resource handle for a successful select. You then need to fetch the results using mysql_fetch_* class of functions. Alternatively, you can use mysql_num_rows() to determine the number of rows returned in the result set.
In this case it is really senseless to wrap your actual query into a subquery. Just run your select and determine the number of rows:
$email = "jb#tlb.com";
$result = mysql_query("SELECT email FROM accounts WHERE email='".$email . "'");
if($result) {
$row_count = mysql_num_rows($result);
echo $row_count;
}
Also, you should not be writing new code using mysql_* functions, as these are deprecated. I would suggest mysqli or PDO extensions instead.
You need to do something like
while ($r = mysql_fetch_assoc($row))
{
echo $r[0];
}
after that code.
Let me know.
I have a script which works without errors, but can't delete chosen value from mysql.
It looks like: What problem could be?
include('opendb.php');
$a = $_GET['new_pav'];
$select = mysql_query("SELECT * from naujiena WHERE new_pav = '$a'");
while($row = mysql_fetch_row($select)){
$result = mysql_query("DELETE FROM `naujiena` WHERE new_pav='".mysql_real_escape_string($a)."' ");
}
Firstly, read this (and below):
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
The red warning box is telling you to stop using mysql_* in anything new.
As for your query, DELETE FROM x WHERE y=z is a valid query, so the error could be from your use of quotes (if new_pav is an int, then this could explain it); strings are quoted in MySQL.
Also, do not interpolate/concat strings in an SQL query, or you risk SQL Injection. Look up pdo, and start using classes for something that involves a state (the db connection), rather than a variable and countless functions. (I originally used mysqli here):
try {
$db = new PDO("mysql:dbname=$dbname;host=$dbhost", $dbuser, $dbpass);
$query = $db->prepare("SELECT COUNT(*) FROM naujiena WHERE new_pav = :pav");
if (!$query->bindParam(":pav", $_POST["new_pav"])) {
die("Input incorrect; couldn't bind");
}
$query->execute();
$rows = $query->fetchColumn(0); // fetch a single column. count(*) here.
if ($rows !== 0) { // It has a result~
$query = $db->prepare("DELETE FROM naujiena WHERE new_pav = :pav");
$query->execute(array(":pav" => $_POST["new_pav"]));
}
$db = null; // explicitly close connection
} catch (PDOException $e) { // catch any exception PDO throws at you.
// note that you should catch where appropriate.
die("Connection Failed: " . $e->getMessage());
}
Note that with SQL Injection, I could type ' OR 1=1 -- and delete your whole table.
As you can see, this is far from a one/two-liner, but you must never trust anything added to SQL that you didn't hardcode in yourself, period.
Apart from using mysql_ libraries your code:
$select = mysql_query("SELECT * from naujiena WHERE new_pav = '$a'");
while($row = mysql_fetch_row($select)){
$result = mysql_query("DELETE FROM `naujiena` WHERE new_pav='".mysql_real_escape_string($a)."' ");
}
In the SELECT you are not escaping the value of $a but in the delete you are escaping it.
Anyway if you are just doing a delete you do not need the SELECT or while loop. So you could use the following code:
$result = mysql_query("DELETE FROM `naujiena` WHERE new_pav='".mysql_real_escape_string($a)."' ");