Problems with LIKE query on PHP files - php

I am working on an Android app that connects to an sql database through php files. Currently I am having problems with the like function on one of my queues.
Here is the code of the file where the problem is:
$con = mysqli_connect($host,$uname,$pwd,$db) or die("connection failed");
$like = $_REQUEST['like'];
$sql_q = mysqli_query($con,"SELECT `ID`, `Value`, `Value_Complete` FROM `products` WHERE `ID` LIKE '$like'");
if($sql_q)
{
while($result = mysqli_fetch_assoc($sql_q))
{
$output[] = $result;
}
if($output)
{
print(json_encode($output));
}
}
else
{
echo 'Invalid query: ' . mysqli_error() . "\n";
}
mysqli_close($con);
?>
This code works with this query - SELECT ID, Value, Value_Complete FROM products WHERE ID LIKE '11/02/__/00/%' - and returns:
[{"ID":"11\/02\/00\/00\/00\/0\/0\/0","Value":"Tradicionais","Value_Complete":""},
{"ID":"11\/02\/01\/00\/00\/0\/0\/0","Value":"Caipis","Value_Complete":""},
{"ID":"11\/02\/02\/00\/00\/1\/0\/0","Value":"Daiquiri","Value_Complete":""},
{"ID":"11\/02\/03\/00\/00\/1\/0\/0","Value":"Gin Tonico","Value_Complete":""},
{"ID":"11\/02\/04\/00\/00\/1\/0\/0","Value":"Long Island Ice Tea","Value_Complete":""},
{"ID":"11\/02\/05\/00\/00\/1\/0\/0","Value":"Manhattan","Value_Complete":""},
{"ID":"11\/02\/06\/00\/00\/1\/0\/0","Value":"Margarita","Value_Complete":""},
{"ID":"11\/02\/07\/00\/00\/1\/0\/0","Value":"Martini Seco","Value_Complete":""},
{"ID":"11\/02\/08\/00\/00\/1\/0\/0","Value":"Black Russian","Value_Complete":""},
{"ID":"11\/02\/09\/00\/00\/1\/0\/0","Value":"White Russian","Value_Complete":""},
{"ID":"11\/02\/10\/00\/00\/1\/0\/0","Value":"Sex on the Beach","Value_Complete":""},
{"ID":"11\/02\/11\/00\/00\/1\/0\/0","Value":"Sidecar","Value_Complete":""},
{"ID":"11\/02\/12\/00\/00\/1\/0\/0","Value":"Sakerinha","Value_Complete":""},
{"ID":"11\/02\/13\/00\/00\/1\/0\/0","Value":"Tequila Sunrise","Value_Complete":""},
{"ID":"11\/02\/14\/00\/00\/0\/0\/0","Value":"Vodka","Value_Complete":""}]
The same query returns this in phpMyAdmin:
However, the same code does not work with the query - SELECT ID, Value, Value_Complete FROM products WHERE ID LIKE '$like'. It returns an empty result set but in phpMyAdmin returns:
I just can't figure out the issue here... Even this - SELECT ID, Value, Value_Complete FROM products WHERE ID LIKE '%'- returns nothing, when it should return everything.
Could you help me? Thanks.

try to change your query:
$con = mysqli_connect($host,$uname,$pwd,$db) or die("connection failed");
$like = $_REQUEST['like'];
$sql_q = mysqli_query($con,"SELECT `ID`, `Value`, `Value_Complete` FROM `products` WHERE `ID` LIKE '%".$like."%'");
if($sql_q)
{
while($result = mysqli_fetch_assoc($sql_q))
{
$output[] = $result;
}
if($output)
{
print(json_encode($output));
}
}
else
{
echo 'Invalid query: ' . mysqli_error() . "\n";
}
mysqli_close($con);
?>

Basically like in something work as equal to (=) but it give you the flexibility to use wild card. % wild card use to define in sql query that there is something but not matter.
If you are not use % with your query it means you are searching same string that is stored in $like variable.
In phpmyadmin you don't need to use %. Because phpmyadmin is designed to the make the use of database easy. So when you select like in search option it automatically add % before applying query on database.
Due to this reason you see these difference.

Add % to the variable
"SELECT `ID`, `Value`, `Value_Complete` FROM `products` WHERE `ID` LIKE '$like%'"

Please try this this complete solution according to your requirements
SELECT tablename FROM id WHERE FIND_IN_SET('/',$column name);
It uses the find_in_Set mysql function which takes 2 parameters, one is the separator and the other is the column name.

Related

query works in sql, not in php

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."'";

How to check if a row exists in MySQL using PHP

I am trying to read in an XML file and compare it to fields in an existing database.
If the ID in the database doesn't exist in the XML file, then the whole row corresponding to the Id is no longer valid and will be deleted.
To do this I read in each line of the XML from start to finish in a while statement.
As step one I am trying to do a simple compare, and echo if it finds an Id in the database that doesn't exist in the XML.
I know there are some Ids in the database that don't exist in the XML, but the following code is not displaying them.
I've got three questions, firstly how would I display the Id that is pulled from the database, and secondly why isn't this code finding any ids that are not in the XML?
The final question is am I going about this completely the wrong way and is there a better way to do it!
$sql_result = mysql_query("SELECT id FROM `list` WHERE id = $id") or die(mysql_error());
if($sql_result)
{
// echo $id . " Id exists " . $sql_result["id"] . "\n";
}
else
{
echo "Id no longer exists" . $id . "\n";
}
Your code isn't finding what you expect because even though the id may not be found, $sql_result still holds a TRUE value because the query was successful. Instead, check if myqsl_num_rows() > 0
if($mysql_num_rows($sql_result) > 0)
{
// echo $id . " Id exists "\n";
//Now, to print the id, you need to fetch it from `$sql_result`,
//which is just a resource at this point:
$row = mysql_fetch_assoc($sql_result);
echo $row['id'];
}
This is the proper way to check:
$sql_result = mysql_query("SELECT `id` FROM `list` WHERE `id` = ".intval($id,10)." LIMIT 0,1");
if(is_resource($sql_result) && mysql_num_rows($sql_result) > 0 ){
$sql_result = mysql_fetch_assoc($sql_result);
echo $id . " Id exists " . $sql_result["id"] . "\n";
}
else{
echo "Id no longer exists" . $id . "\n";
}
You should check the number of rows returned using mysql_num_rows(). Otherwise, you are simply checking to see if the query executed without any error.
if($sql_result)
to
if(mysql_num_rows($sql_result))
You can use NOT IN() on your select with the IDs that exist on you XML like:
SELECT id FROM `list` WHERE id NOT IN($your_id_list)
With this you'll have a list of IDs that are not in the list.
Your IDs must be separated with a comma like:
SELECT id FROM `list` WHERE id NOT IN(123,654,987,45)
Question 1: how would I display the Id that is pulled from the database?
$sql_result = mysql_query("SELECT `id` FROM `list` WHERE `id` = $id") or die(mysql_error());
$sql_row = mysql_fetch_assoc($sql_result);
if(!empty($sql_row['id'])) {
echo "Id exists - " . $sql_row['id'] . "\n";
} else {
echo "Id no longer exists - " . $sql_row['id'] . "\n";
}
Question 2: why isn't this code finding any ids that are not in the XML?
I think in your code the if() condition will always return true irrespective if the Id exists in the database or not. And secondly as you might have guessed from my code above, you are missing to fetch the data from the SQL resultset
Question 3: am I going about this completely the wrong way and is there a better way to do it?
You are doing it the right way by browsing through the XML and checking each entry in the database for existence. A better way might be to first retrieve all IDs from the XML and then use them in the single SQL query:
SELECT `id` FROM `list` WHERE `id` NOT IN ($list);
Please note that this query might run slow if there are a very large number of IDs in the XML file, say a few hundreds.
mysql_num_rows()
Or
SELECT COUNT(*) [...]

Check whether data is at table

I asked something about in_array() and I already got that working. But now I have a different problem:
I have a table that says which services are assigned to hosts: services_hosts(service_id, host_id).
How can I see if the service that is selected is already assigned to that host, also selected? Basically, I want to see if the specific line (service_id, host_id) already exists in that table.
EDIT:
The problem is that I want to compare in a separate file that has functions that connect to DB:
function addServiceToHost($service_name, $host_id)
{
$query = "INSERT INTO monitoring_hosts_services (service_id, host_id) values ((SELECT service_id FROM monitoring_services WHERE name = '".$service_name."'), '".$host_id."')";
$result = #pg_exec($this->conn, $query);
if ($row = pg_fetch_row($result))
{
"blabla error msg"
exit;
}
return $this->parseResultObj($result);
}
I might not unserstand your question correctly but would this do the trick:
SELECT * FROM ServerHostsTable WHERE service_id = '5' AND host_id = '8'
$query = ("SELECT * FROM ServerHostsTable WHERE service_id = '5' AND host_id = '8'")
if(mysql_num_rows($query)>0)
{
//the item is in the db
}
else
{
//not in the db
}
hope this helps
your question is not very clear, but from what I understand you want to test if a specific row is inserted into a database table. you could do this like this:
$result=mysql_query("SELECT service_id FROM services_hosts WHERE service_id=$theserviceid AND host=$thehostid");
if($row=mysql_fetch_row($result){
echo "already in the db";
} else {
echo "not in the db!";
}
I would run this query.
$sql = "SELECT COUNT(*) AS ret\n";
$sql.= "FROM services_hosts\n";
$sql.= "WHERE service_id = $service_id\n";
$sql.= "AND host_id = $host_id";
The result should be one row with one field (named ret):
0 - the service is not present on the host
1 - service is present on the host
enything else - there is a problem with table in database

Get next auto increment

I know this isn't so complicated but I can't remember how to do.
I just need to know the next auto increment.
$result = mysql_query("
SHOW TABLE STATUS LIKE Media
");
$data = mysql_fetch_assoc($result);
$next_increment = $data['Auto_increment'];
...but i won't work for me, what am I doing wrong?
$result = mysql_query("
SHOW TABLE STATUS LIKE 'Media'
");
$data = mysql_fetch_assoc($result);
$next_increment = $data['Auto_increment'];
The name of the table needed to be wrapped with single quotes like this: 'table_name'
So it works just fine now.
:)
The query should look like this:
SHOW TABLE STATUS WHERE `Name` = 'Media';
Another way, but slow, is:
SELECT AUTO_INCREMENT FROM information_schema.`TABLES` T where TABLE_SCHEMA = 'myScheme' and TABLE_NAME = 'Media';
The information_schema is mostly usefull for getting data from many schemes.
You can also use this function
function getNextValue(){
$query = "SHOW TABLE STATUS LIKE 'vendors'";
dbconnect();
$results=mysql_query($query);
if(mysql_errno() != 0) {
$result['count'] = -1;
$result['error'] = "Error: ".mysql_error();
} else {
$result['count'] = mysql_num_rows($results);
for($counter=0;$counter<$result['count'];$counter++) {
$result[$counter] = mysql_fetch_assoc($results);
}
}
return $result[0]['Auto_increment'];
mysql_close();
}
SELECT AUTO_INCREMENT
FROM information_schema.TABLES
WHERE TABLE_SCHEMA = "database_name"
AND TABLE_NAME = "table_name";
if you need to know the next auto_increment, then it's 99% likely you're doing it wrong. instead of the getting the next auto_increment, you should just do the insert you're about to do, then use SELECT LAST_INSERT_ID() to get the auto_increment value from that insert.
if you try to guess the next auto_increment value and you have multiple users doing it at the same time, you'll frequently get the wrong value.

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