I think this should work but it is not...
Basically i am trying to check mysql db to see if there is a record that meets the 2 variables..if no do one thing if yes do another thing. the result is always no at this point.
$result = mysql_query("SELECT 'lastname' FROM 'Cust_Releases' WHERE 'lastname' = '$usercheck' AND 'TripID'= '$RLtripid'");
echo $result;
if(mysql_num_rows($result) == 0) {
echo"no";// row not found, do stuff...
}
else {
echo"yes"; // do other stuff...
}
First of all, stop using mysql_* functions because this extension is deprecated as of PHP 5.5.0.
Second always use the (`) symbol around database names, table names and column names.
You have a reserved word used RELEASE.
$sql = "SELECT `lastname` FROM `Releases` WHERE `lastname` = '$usercheck' AND `TripID` = '$RLtripid'";
Reserved words you find here
$result = mysql_query("SELECT lastname FROM `Releases` WHERE lastname = '$usercheck' AND TripID= '$RLtripid' LIMIT 1");
if (!$result) {
die('Invalid query: ' . mysql_error());
}
echo $result;
if(mysql_num_rows($result) == 0) {
echo"no";// row not found, do stuff...
}
else {
echo"yes"; // do other stuff...
}
Escaping 'Releases', as Bondye suggested
Adding 'LIMIT 1' to your query to allow the possibility of an early-out when there is more than one matching record. You don't appear to need the total count. May not make any difference if unique constraints exist which guarantee that only one row can be returned
mysql_query is deprecated. In real code you should be using PDO and prepared statements / bind variables!
debugging is a very important thing in programming. first do make sure that the varibales $usercheck, and $RLtripid contain values.
-----------------------
$sql = "SELECT `lastname` FROM `Cust_Releases` WHERE `lastname` = '$usercheck' AND `TripID`= '$RLtripid'";
echo $sql;
$result = mysql_query($sql);
....-------------------
Try this code. It will help you
$result = mysql_query("SELECT COUNT( * ) from Cust_Releases lastname = '$usercheck' AND TripID= '$RLtripid'");
if($result == 0) {
echo"no";// row not found, do stuff...
}
else {
echo"yes"; // do other stuff...
}
Related
From the following Queries, Which one is the most optimal and fastest to use?
[COUNT(id)]
$SQL = "SELECT name, COUNT(id) as Count FROM names WHERE name = :name";
$row = $stmt->fetch();
if ($data['count'] > 0) {
while ($row) {
$name = $row['name'];
}
} else {
return;
}
OR [rowCount()]
$SQL = "SELECT name FROM names WHERE name = :name";
if ($stmt->rowCount() > 0) {
while ($row = $stmt->fetch()) {
$name = $row['name'];
}
} else {
return;
}
OR [EXISTS]
$SQLEX = "SELECT EXISTS (SELECT name FROM names WHERE name = :name LIMIT 1)";
if ($stmt->fetchColumn == 1) {
$SQL = "SELECT name FROM names WHERE name = :name";
while (row = $stmt->fetch()){
$name = $row['name'];
}
} else {
return;
}
OR [RAW]
$SQL = "SELECT name FROM names WHERE name = :name";
$row = $stmt->fetch();
if ($row) {
while($row) {
$name = $row['name'];
}
} else {
return;
}
Also i wanted to know, Why does using $stmt->fetch() with $stmt->rowCount() allows me to fetch data, But using it with $stmt->fetchColumn doesn't?
First, if you have an index on names(name), then all should be quite comparable in speed.
Second, it is always worth trying such performance tests on your own system.
Third, if names are declared as unique (or primary key) in the names table, then all should be quite fast.
In general, though, the fastest way to determine if a row is available is:
SELECT EXISTS (SELECT name FROM names WHERE name = :name)
The LIMIT 1 in the subquery is unnecessary -- EXISTS stops at the first row (whether the database uses an index or a table scan).
In general, the first method using an aggregation is the worst solution. Without an index, it is going to result in a full table scan that reads the entire table. The second might or might not read the entire table, depending on whether the database starts returning matching rows as they are available. It also has the downside of returning more data.
Ok, it seems this question needs more than one answer...
f you need to check the existence only,
if there is an unique index for the field, all methods are equal, but some of them just make no sense.
if there is no unique index, then go for EXISTS
If you need to fetch the actual data and see if there was anything returned, then just select your data and fetch it:
if only one column from a single row is expected, then use fetchColumn()
if only one row is expected, then use fetch()
if multiple rows are expected, then use fetchAll()
and then use the resulting value to see whether your query returned any data.
So if you finally made your mind as to what you're asking about, here is the most optimal code for you:
$SQL = "SELECT name FROM names WHERE name = :name";
$data = $stmt->fetchAll(PDO::FETCH_COLUMN);
if (!$data) {
return;
}
foreach ($data as $name) ...
And there is nothing wrong with fetchColumn() other than your idea to use it.
Something is wrong with my php,
I'm doing an account validation where if the data exist it will display "There is data" and else "No data"...
When I enter the first 'row' reference_id and submit, it shows "There is data" which is correct but when I entered the second to the last 'row' reference_id it shows "No data" even though it exist in my Database!
Database:
reference_id (varchar 250)
status (varchar250)
PHP
if (isset($_POST['submit_valid'])) {
if (!empty($_POST['reference_id']))
{
$query = mysqli_query($con, "SELECT * FROM client_record");
$result = mysqli_fetch_array($query);
if ($result['reference_id'] == $_POST['reference_id'])
{
echo"<script type='text/javascript'> alert('There is data'); window.location.href='next_page.php'; </script>";
}
if ($result['reference_id'] !== $_POST['reference_id']) {
echo"<script type='text/javascript'> alert('No data.'); window.location.href='this_page.php'; </script>";
}
}
}
I am not sure if it's the mysqli_fetch_array fault or the if-else condition is wrong?
if you guys know the problem please help me?
Your query execution currently only looks at the first row. A fetch needs to be looped to iterate over all rows. e.g.
$query = mysqli_query($con, "SELECT * FROM client_record");
$result = mysqli_fetch_array($query);
should be
$query = mysqli_query($con, "SELECT * FROM client_record");
while($result = mysqli_fetch_array($query)) {
but this is inefficient. When looking for a specific record use a where clause. Parameterized queries also will prevent SQL injections, and quoting issues. The i in the bind_param is for an integer, if your id is a string use s.
$prepared = mysqli_prepare($con, "SELECT * FROM client_record where reference_id = ?");
mysqli_stmt_bind_param($prepared, 'i', $_POST['reference_id']);
mysqli_stmt_execute($prepared);
mysqli_stmt_store_result($prepared);
while (mysqli_stmt_fetch($prepared)) {
$query = mysqli_query($con, "SELECT * FROM client_record");
$result = mysqli_fetch_array($query);
This will give you the first row from the table.
Add a WHERE reference_id = :refid clause?!
Then bind the refid parameter, so as to avoid SQL injection.
Lapiz, the problem is actually with the comparison operator:
($result['reference_id'] == $_POST['reference_id'])
This will check the first reference_id from the returned set in array.
The best way to tackle this would be to use if (in_array(5, $result)) where 5 is the needle and $result is the array haystack.
Because all you are doing is to check if the reference exists in the returned data set .
This is also good design practices, to collect results and avoid multiple reference queries each time, hit the database once and query the result set.
If its a multidemnsional array loop through the set:
foreach($result as $resultItem)
{
if(in_array("reference_id", $resultItem, true))
{
echo "There is Data";
}
}
Good Luck .
I allow userst to create SQL queries (SELECT, UPDATE, INSERT) by posting a form.
The code:
$sql = $_POST["sql_query"]
mysqli_query($link, $sql);
And I want to make a mysqli_num_rows if the $sql uses SELECT.
How to chek if the $sql contains an SELECT?
$sql = '';
$rows = 0;
$result = mysqli_query($link, $sql);
if(strtoupper(substr($sql,0,6)) == 'SELECT')
$rows = mysqli_num_rows($result);
SELECT will always be the first word in the SQL, so just compare the first six characters. Be sure to ignore case (I'm doing this by capitalising the letters) or you may miss some queries, but this should work as a quick and easy solution.
$sql = $_POST["sql_query"];
if (strpos(strtolower($sql),'insert') !== false)
{
mysql_query($sql,$con);
}
else if (strpos(strtolower($sql),'select') !== false)
{
$row= mysql_num_rows(mysql_query($sql,$con));
}
[EDIT I dont know mysqli so i may not know the actual syntaxes. So i am giving w.r.t mysql]
Hope you can adjust it according to your convenience. Its the logic u need.
if(strstr($sql,'SELECT') || strstr($sql,'select')) {
//your code here
$query = mysqli_query($link, $sql);
$count = mysqli_num_rows($query);
echo $count;
}
I have this query I can run against my db and it works fine. However when I try it in the PHP version I get 0 results. I'm missing something fundamental, I just can't tell what it is.
Query
SELECT *
FROM table_admin_20
WHERE column1 = '0607'
PHP
$store_info_query = "SELECT * FROM '".$table_name."' WHERE 'column1' = '".$store_number."'";
if ($query_run = mysql_query($store_info_query)) {
if (mysql_num_rows($query_run) == NULL) {
$response["success"] = 0;
echo json_encode($response);
echo 'nope';
} else {
while ($row = mysql_fetch_assoc($query_run)) {
$store_info = $row['column1'];
echo '1111111';
echo $store_info;
}
}
} else {
echo 'fail';
}
I know I have 0 protection against SQL injection, I'm merely trying to pull data, this is in no way live yet. Anyways, I get the 'fail' response each time. Thanks for any help.
Don't add security as an afterthought, just switch to PDO or mysqli and use prepared statements so that you don't have to worry about the values any more. In case of table- or column names, you would need to use white-lists though.
The cause of your problem is that you are quoting your table- and field names. If you need to escape them, use backticks:
$store_info_query = "SELECT * FROM `".$table_name."` WHERE `column1` = '".$store_number."'";
You've to replace ' with ` for the table and column names. ' is just for values. Try this:
$store_info_query = "SELECT * FROM `".$table_name."` WHERE `column1` = '".$store_number."'";
Please avoid using * and rethink your security-strategies. As already mentioned, take a look at PDO: http://php.net/manual/en/book.pdo.php
You are putting wrong quotes around table name and column name. Try this
$store_info_query = "SELECT * FROM `".$table_name."` WHERE `column1` = '".$store_number."'";
this is my table
Field Type Null Key Default Extra
id_key int(11) NO PRI NULL auto_increment
tbl_users_username varchar(255) YES UNI NULL
tbl_users_password varchar(32) YES NULL
tbl_users_identifier varchar(32) YES NULL
tbl_users_token varchar(32) YES NULL
tbl_users_access_type int(1) YES NULL
tbl_users_timeout int(10) YES NULL
this is my code
$query = "SELECT * FROM tbl_users where tbl_users_username = '$_POST[email_address]'" ;
$result = mysql_query($query);
if($result)
{
echo "TRUE";
}
else
{
echo "FALSE";
}
There are no problems connecting to the database. The problem arises when I run the query. No matter if the email is in the table or not it returns a $result. What am I missing here? It is supposed to echo true if email address exists in table, false if it is not in table.
The result will be returned nevertheless(if you made a valid query) use mysql_num_rows to check if the mail exists instead.
Actually use PDO if you can
I suggest that you print out your query to ascertain that it is 100% the query you expect it to be.
In addition to that, You are checking:
$result = mysql_query($query);
if($result)
This checks if a resource was returned from your query. It your query is valid then as per the documentation, you should always have a resource.
Suggested code:
$result = mysql_query($query);
if($result)
{
$num = mysql_num_rows($result);
if ($num > 0)
{
//do logic processing here...
echo "TRUE";
}
}
else
{
die('Invalid query: ' . mysql_error());
}
Code Explanation:
Fetch the resource from the query
If valid resource was returned, continue and check the number of records that were fetched
from this query.
If the resource was not returned, the else part echo out a failure message.
I would strongly suggest that you look into using PDO library.
Briefly the Advantages of PDO:
Allows you to use prepared statement with ease (prepared statement are great for security!!!)
PDO can connect to various different Databases including MySQL, but others as well.
Its quite easy to use in my opinion and it quite easy to pick for new comers etc.
Stack overflow usage tips:
Always use the search in the top right hand corner. Numerous people have come across problems that may could help you.
Always have a look at the How to Ask Question FAQ
Feedback & always ask further questions if required!
$_POST[email_address] should use single or double quotes i guess:
$_POST["email_address"] or $_POST['email_address']
$query = "SELECT * FROM tbl_users where tbl_users_username = '" . $_POST['email_address'] . "'" ;
However, as #FabioCosta says, you have to fetch the result or count the number of returned rows to achieve what you are aiming at:
$query = "SELECT 1 FROM tbl_users where tbl_users_username = '" . $_POST['email_address'] . "'";
$result = mysql_query($query);
if(mysql_num_rows($result) === 1) {
echo "TRUE";
} else {
echo "FALSE";
}
If you use PHP's mysql_num_rows function, you should be able to return the number of rows, and your logic will work. So, try the following:
$num = mysql_num_rows($result);
if ($num > 0) {
echo "TRUE";
}else{
echo "FALSE";
}
$query = "SELECT *
FROM tbl_users
WHERE tbl_users_username = '" . mysql_real_escape_string($_POST['email_address']) . "'";
$result = mysql_query($query) or die(mysql_error());
if($result)
{
echo "TRUE";
}
else
{
echo "FALSE";
}
This should fix any problems you're running into, or at least give you a handy error message to work off of.
The following query will select the tbl_users_username value based on the value in the posted email_address' value. So, use this query:
$query =
"SELECT * FROM tbl_users where tbl_users_username = '".$_POST['email_address']."';";