Function to count MySQL rows using WHERE - php

am making function to count rows using "WHERE", but i get a mysql error
Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in C:\AppServ\www\test\test\index.php on line 9
Unknown column '1' in 'where clause'
here is my function
function CountRows($table, $field = NULL, $value = NULL){
mysql_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD);
mysql_select_db(DB_NAME);
if($field != NULL && $value != NULL){
return mysql_num_rows(mysql_query("SELECT * FROM `".$table."` WHERE `".$field."` = `".$value."`"))or die(mysql_error());
}else{
return mysql_num_rows(mysql_query("SELECT * FROM `".$table."`"));
}
}
i've created this function to simplify counting rows mysql rows for banned members, inactive members etc, since all will be using WHERE
all help will be appreciated, thanks in advance

You should not connect to database each time you need to do a query.. Just keep a persistent connection or ideally use PDO.
Value should be enclosed with simple single quotes. This is probably what is getting you an error, as anything enclosed in backticks kind of quotes is considered a database/table/field name.
Use COUNT(*), it does not fetch all the database rows.
If value is possibly supplied by user, make sure that it is safe by escaping it with mysql_real_escape_string if not using PDO.
Without using PDO code would be:
mysql_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD);
mysql_select_db(DB_NAME);
function CountRows($table, $field = NULL, $value = NULL){
if ($field != NULL && $value != NULL) {
$query = "SELECT COUNT(*)
FROM `".$table."`
WHERE `".$field."` = '". mysql_real_escape_string($value) . "'";
} else {
$query = "SELECT COUNT(*) FROM `".$table."`";
}
$count = mysql_fetch_array(mysql_query($query));
return $count[0];
}

Backticks (`) are for enclosing table and column names. Don't wrap $value in them, just use single-quotes (').
Also, there's no reason you need to pull the full data set from the DB and count the rows in it. Just query for the count:
if($field != NULL && $value != NULL){
$cnt = mysql_fetch_assoc(mysql_query("SELECT COUNT(*) as cnt FROM `".$table."` WHERE `".$field."` = '".$value."'"))or die(mysql_error());
}else{
$cnt = mysql_fetch_assoc(mysql_query("SELECT COUNT(*) as cnt FROM `".$table."`"));
}
return $cnt['cnt'];

Additionally:
Do not connect/select database in the function. This should be done one time at the beginning of every page, no more (unless multiple connections are desired).
Do not SELECT * just so you can calculate the number of rows. Use MySQL's COUNT() function instead.
$result = mysql_query("SELECT COUNT(0) AS numRows FROM aTable");
$numRows = mysql_result($result, 0, 'numRows');
Do NOT use your function with user input without taking appropriate actions to secure yourself against SQL injection.

Related

I want the highest and the lowest value of a table, why can't I save that value in PHP?

$category = htmlspecialchars($_GET['category']);
$sql = "(SELECT number
FROM german
WHERE german.category_german LIKE ".$category."
ORDER BY number DESC
LIMIT 1) as 'high',
(SELECT number
FROM german
WHERE german.category_german LIKE ".$category."
ORDER BY number ASC
LIMIT 1) as 'low'";
if ($result = $conn -> query($sql)) {
while ($row = $result -> fetch_row()) {
$high_value = $row[high];
$low_value = $row[low];
$r_n = rand($low_value,$high_value).PHP_EOL;
echo $r_n;
}
}
What am I missing? I want the highest and the lowest value of a table, why can't I save that value in PHP? I just can't access the values. And I tried out MIN and MAX as well, but they didn't function neither:
$category = htmlspecialchars($_GET['category']);
$sql = "SELECT MIN('number') AS 'low', MAX('number') AS 'high' FROM german WHERE german.category_german LIKE ".$category."";
if ($result = $conn -> query($sql)) {
while ($row = $result -> fetch_row()) {
$high_value = $row[high];
$low_value = $row[low];
$r_n = rand($low_value,$high_value).PHP_EOL;
echo $r_n;
}
}
As a result of $r_n I only get 0. The database shouldn't be the problem. Beforehand (where I only used the highest value) everything functioned:
$category = htmlspecialchars($_GET['category']);
$sql = "SELECT number FROM german WHERE german.category_german LIKE ".$category." ORDER BY number DESC LIMIT 1";
if ($result = $conn -> query($sql)) {
while ($row = $result -> fetch_row()) {
$r_n = $row[0];
$r_n = rand(1,$r_n).PHP_EOL;
echo $r_n;
}
}
You can't use multiple SELECT statements at top-level of a query. They would have to be subqueries:
SELECT (SELECT ...) AS high, (SELECT ...) AS low
Your second query would have worked, but you shouldn't have quotes around number. That makes it a literal string, not the column values. So MAX('number') should be MAX(number), MIN('number') should be MIN(number). See When to use single quotes, double quotes, and backticks in MySQL
And if category is a string, you need to put quotes around $category:
WHERE german.category_german LIKE '".$category."'"
But the better way to resolve that problem is to use a prepared statement with parameters, How can I prevent SQL injection in PHP? than substituting variables directly into the query. See

check if record exist in mysql db

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...
}

how can i check if a variable is saved or not in the db?

I have this code:
$local_id = $_GET['id'];
$sql = dbquery("SELECT * FROM `videos` WHERE `id` = ".$local_id." LIMIT 0, 1");
while($row = mysql_fetch_array($sql)){
$video_id = $row["youtube_id"];
// the rest
}
how can i check if $local_id does not exist in the db and display an error?
mysql_num_rows
if(mysql_num_rows($sql) == 0) {
//Show error
}
$sql = dbquery("select count(*) from videos where id = ".$local_id." LIMIT 0, 1");
$row = mysql_fetch_row($sql);
if($row[0] == 0)
echo 'error';
You can use the following query:
"SELECT COUNT(*) FROM `videos` WHERE `id` = ".mysql_real_escape_string($local_id)
This query will return one number: how many records have matched your query. If this is zero, you surely know that there are no records with this ID.
This is more optimal than other solutions posted in case you only want to check for the existence of the ID, and don't need the data (if you use SELECT * ..., all the data will be unnecessarily sent from MySQL to you). Otherwise mysql_num_rows() is the best choice, as #Ryan Doherty correctly posted.
Be sure to ALWAYS escape data that came from the outside (this time GET) before you put it into a query (mysql_real_escape_string() for MySQL).
If you fail to do so, you are a possible victim for SQL Injection.
You could have a $count variable and increment it in the while loop. After the loop, check the count, if it is 0, then echo an error message.

Simple way to read single record from MySQL

What's the best way with PHP to read a single record from a MySQL database? E.g.:
SELECT id FROM games
I was trying to find an answer in the old questions, but had no luck.
This post is marked obsolete because the content is out of date. It is not currently accepting new interactions.
$id = mysql_result(mysql_query("SELECT id FROM games LIMIT 1"),0);
$link = mysql_connect('localhost','root','yourPassword')
mysql_select_db('database_name', $link);
$sql = 'SELECT id FROM games LIMIT 1';
$result = mysql_query($sql, $link) or die(mysql_error());
$row = mysql_fetch_assoc($result);
print_r($row);
There were few things missing in ChrisAD answer. After connecting to mysql it's crucial to select database and also die() statement allows you to see errors if they occur.
Be carefull it works only if you have 1 record in the database, because otherwise you need to add WHERE id=xx or something similar to get only one row and not more. Also you can access your id like $row['id']
Using PDO you could do something like this:
$db = new PDO('mysql:host=hostname;dbname=dbname', 'username', 'password');
$stmt = $db->query('select id from games where ...');
$id = $stmt->fetchColumn(0);
if ($id !== false) {
echo $id;
}
You obviously should also check whether PDO::query() executes the query OK (either by checking the result or telling PDO to throw exceptions instead)
Assuming you are using an auto-incrementing primary key, which is the normal way to do things, then you can access the key value of the last row you put into the database with:
$userID = mysqli_insert_id($link);
otherwise, you'll have to know more specifics about the row you are trying to find, such as email address. Without knowing your table structure, we can't be more specific.
Either way, to limit your SELECT query, use a WHERE statement like this:
(Generic Example)
$getID = mysqli_fetch_assoc(mysqli_query($link, "SELECT userID FROM users WHERE something = 'unique'"));
$userID = $getID['userID'];
(Specific example)
Or a more specific example:
$getID = mysqli_fetch_assoc(mysqli_query($link, "SELECT userID FROM users WHERE userID = 1"));
$userID = $getID['userID'];
Warning! Your SQL isn't a good idea, because it will select all rows (no WHERE clause assumes "WHERE 1"!) and clog your application if you have a large number of rows. (What's the point of selecting 1,000 rows when 1 will do?) So instead, when selecting only one row, make sure you specify the LIMIT clause:
$sql = "SELECT id FROM games LIMIT 1"; // Select ONLY one, instead of all
$result = $db->query($sql);
$row = $result->fetch_assoc();
echo 'Game ID: '.$row['id'];
This difference requires MySQL to select only the first matching record, so ordering the table is important or you ought to use a WHERE clause. However, it's a whole lot less memory and time to find that one record, than to get every record and output row number one.
One more answer for object oriented style. Found this solution for me:
$id = $dbh->query("SELECT id FROM mytable WHERE mycolumn = 'foo'")->fetch_object()->id;
gives back just one id. Verify that your design ensures you got the right one.
First you connect to your database. Then you build the query string. Then you launch the query and store the result, and finally you fetch what rows you want from the result by using one of the fetch methods.
$link = mysql_connect('localhost','root','yourPassword')
mysql_select_db('database',$link);
$sql = 'SELECT id FROM games'
$result = mysql_query($sql,$link);
$singleRow = mysql_fetch_array($result)
echo $singleRow;
Edit: So sorry, forgot the database connection. Added it now
'Best way' aside some usual ways of retrieving a single record from the database with PHP go like that:
with mysqli
$sql = "SELECT id, name, producer FROM games WHERE user_id = 1";
$result = $db->query($sql);
$row = $result->fetch_row();
with Zend Framework
//Inside the table class
$select = $this->select()->where('user_id = ?', 1);
$row = $this->fetchRow($select);
The easiest way is to use mysql_result.
I copied some of the code below from other answers to save time.
$link = mysql_connect('localhost','root','yourPassword')
mysql_select_db('database',$link);
$sql = 'SELECT id FROM games'
$result = mysql_query($sql,$link);
$num_rows = mysql_num_rows($result);
// i is the row number and will be 0 through $num_rows-1
for ($i = 0; $i < $num_rows; $i++) {
$value = mysql_result($result, i, 'id');
echo 'Row ', i, ': ', $value, "\n";
}
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$db = new mysqli('localhost', 'tmp', 'tmp', 'your_db');
$db->set_charset('utf8mb4');
if($row = $db->query("SELECT id FROM games LIMIT 1")->fetch_row()) { //NULL or array
$id = $row[0];
}
I agree that mysql_result is the easy way to retrieve contents of one cell from a MySQL result set. Tiny code:
$r = mysql_query('SELECT id FROM table') or die(mysql_error());
if (mysql_num_rows($r) > 0) {
echo mysql_result($r); // will output first ID
echo mysql_result($r, 1); // will ouput second ID
}
Easy way to Fetch Single Record from MySQL Database by using PHP List
The SQL Query is SELECT user_name from user_table WHERE user_id = 6
The PHP Code for the above Query is
$sql_select = "";
$sql_select .= "SELECT ";
$sql_select .= " user_name ";
$sql_select .= "FROM user_table ";
$sql_select .= "WHERE user_id = 6" ;
$rs_id = mysql_query($sql_select, $link) or die(mysql_error());
list($userName) = mysql_fetch_row($rs_id);
Note: The List Concept should be applicable for Single Row Fetching not for Multiple Rows
Better if SQL will be optimized with addion of LIMIT 1 in the end:
$query = "select id from games LIMIT 1";
SO ANSWER IS (works on php 5.6.3):
If you want to get first item of first row(even if it is not ID column):
queryExec($query) -> fetch_array()[0];
If you want to get first row(single item from DB)
queryExec($query) -> fetch_assoc();
If you want to some exact column from first row
queryExec($query) -> fetch_assoc()['columnName'];
or need to fix query and use first written way :)

MySQL check if a table exists without throwing an exception

What is the best way to check if a table exists in MySQL (preferably via PDO in PHP) without throwing an exception. I do not feel like parsing the results of "SHOW TABLES LIKE" et cetera. There must be some sort of boolean query?
Querying the information_schema database using prepared statement looks like the most reliable and secure solution.
$sql = "SELECT 1 FROM information_schema.tables
WHERE table_schema = database() AND table_name = ?";
$stmt = $pdo->prepare($sql);
$stmt->execute([$tableName]);
$exists = (bool)$stmt->fetchColumn();
If you're using MySQL 5.0 and later, you could try:
SELECT COUNT(*)
FROM information_schema.tables
WHERE table_schema = '[database name]'
AND table_name = '[table name]';
Any results indicate the table exists.
From: http://www.electrictoolbox.com/check-if-mysql-table-exists/
Using mysqli I've created following function. Assuming you have an mysqli instance called $con.
function table_exist($con, $table){
$table = $con->real_escape_string($table);
$sql = "show tables like '".$table."'";
$res = $con->query($sql);
return ($res->num_rows > 0);
}
Hope it helps.
Warning: as sugested by #jcaron this function could be vulnerable to sqlinjection attacs, so make sure your $table var is clean or even better use parameterised queries.
This is posted simply if anyone comes looking for this question. Even though its been answered a bit. Some of the replies make it more complex than it needed to be.
For mysql* I used :
if (mysqli_num_rows(
mysqli_query(
$con,"SHOW TABLES LIKE '" . $table . "'")
) > 0
or die ("No table set")
){
In PDO I used:
if ($con->query(
"SHOW TABLES LIKE '" . $table . "'"
)->rowCount() > 0
or die("No table set")
){
With this I just push the else condition into or. And for my needs I only simply need die. Though you can set or to other things. Some might prefer the if/ else if/else. Which is then to remove or and then supply if/else if/else.
Here is the my solution that I prefer when using stored procedures. Custom mysql function for check the table exists in current database.
delimiter $$
CREATE FUNCTION TABLE_EXISTS(_table_name VARCHAR(45))
RETURNS BOOLEAN
DETERMINISTIC READS SQL DATA
BEGIN
DECLARE _exists TINYINT(1) DEFAULT 0;
SELECT COUNT(*) INTO _exists
FROM information_schema.tables
WHERE table_schema = DATABASE()
AND table_name = _table_name;
RETURN _exists;
END$$
SELECT TABLE_EXISTS('you_table_name') as _exists
As a "Show tables" might be slow on larger databases, I recommend using "DESCRIBE " and check if you get true/false as a result
$tableExists = mysqli_query("DESCRIBE `myTable`");
$q = "SHOW TABLES";
$res = mysql_query($q, $con);
if ($res)
while ( $row = mysql_fetch_array($res, MYSQL_ASSOC) )
{
foreach( $row as $key => $value )
{
if ( $value = BTABLE ) // BTABLE IS A DEFINED NAME OF TABLE
echo "exist";
else
echo "not exist";
}
}
Zend framework
public function verifyTablesExists($tablesName)
{
$db = $this->getDefaultAdapter();
$config_db = $db->getConfig();
$sql = "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = '{$config_db['dbname']}' AND table_name = '{$tablesName}'";
$result = $db->fetchRow($sql);
return $result;
}
If the reason for wanting to do this is is conditional table creation, then 'CREATE TABLE IF NOT EXISTS' seems ideal for the job. Until I discovered this, I used the 'DESCRIBE' method above. More info here: MySQL "CREATE TABLE IF NOT EXISTS" -> Error 1050
Why you make it so hard to understand?
function table_exist($table){
$pTableExist = mysql_query("show tables like '".$table."'");
if ($rTableExist = mysql_fetch_array($pTableExist)) {
return "Yes";
}else{
return "No";
}
}

Categories