SQLite Full-Text Search with PDO - php

I created the sqlite-FTS4 table with multiple columns such as:
CREATE VIRTUAL TABLE [selection_fts] USING fts4 (tender_id, tender_orderName_clean, tender_fm, branch, lot_name_clean);
and I try to execute code like
$q = $db->query("SELECT * FROM selection_fts WHERE selection_fts MATCH (\"(tender_orderName_clean:двер* OR lot_name_clean:двер*) AND tender_fm:Министерство Иностранных Дел AND branch:на строительство\") limit 0,250");
$rows = $q->fetchAll(PDO::FETCH_ASSOC);
var_dump($rows);
die();
The code above returns 0 rows, but in my SQlite manager I see some results.
Do you please explain my mistake?

Although this is an old question, I just ran into the same issue and found out that (atleast in my case) the exact MATCH to the database entry didn't return any results. When I took irrelevant parts out of the MATCH string, I got results back.
Might be a bug in the SQLite driver, maybe...

Related

Trying to delete all rows in database that do not match array

I am trying to figure out how to delete all ids in the database that do not exist in an array. I have been trying to use NOT IN in my query but I am not sure why it wont work when running it in a script the same way it works when I manually enter it into mysql. Here is an example.
mysqli_query($con, "DELETE FROM table WHERE id NOT IN ($array)");
$array is a list of ids from a json api. I use CURL to fetch the ids and I am trying to delete all ids in the database that do not match the ids in $array.
First I use another simple CURL script to scrape the apis and insert the ids found into the database and what I am trying to do here is basically make a link/data checker.
If the ids in the database are not found in the array when rechecking them then I want them deleted.
I thought that the query above would work perfect but for some reason it doesn't. When the query is ran from a script the mysql log shows the queries being ran as this.
Example:
DELETE FROM table WHERE id NOT IN ('166')
or this when I am testing multiple values.
DELETE FROM table WHERE id NOT IN ('166', '253', '3324')
And what happens is it deletes every row in the table every time. I don't really understand because if I copy/paste the same query from the log and run it manually myself it works perfect.
I have been trying various ways of capturing the array data such as array_column, array_map, array_search and various functions I have found but the end result is always the same.
For right now, just for testing I am using these 2 bits of code for testing 2 different apis which gives me the same sql query log output as above. The functions used are just a couple random ones that I found.
//$result is the result from CURL using json_decode
function implode_r($g, $p) {
return is_array($p) ?
implode($g, array_map(__FUNCTION__, array_fill(0, count($p), $g), $p)) :
$p;
}
foreach ($result['data'] as $info){
$ids = implode_r(',', $info['id']);
mysqli_query($con, "DELETE FROM table WHERE id NOT IN ($ids)");
}
And
$arrayLength = count($result);
for($i = 0; $i < $arrayLength; $i++) {
mysqli_query($con, "DELETE FROM table WHERE id NOT IN ('".$result[$i]['id']."')");
}
If anyone knows what is going on i'd appretiate the help or any suggestions on how to achieve the same result. I am using php 7 and mysql 5.7 with innodb tables if that helps.
It probably doesn't work because your IN value is something like this
IN('1,2,3,4');
When what you want is this
IN('1','2','3','4')
OR
IN( 1,2,3,4)
To get this with implode include the quotes like this
$in = "'".implode("','", $array)."'";
NOTE whenever directly inputting variables into SQL there is security Implications to consider such as SQLInjection. if the ID's are from a canned source you're probably ok, but I like to sanitize them anyway.
You can't mix array and string.
This works:
mysqli_query($con, "DELETE FROM table WHERE id NOT IN (".implode(',', $ids).")");

mysql query on WordNet database was working fine and just stop working

this query is provided by wordnet itself, and is used for retrieving word information, such as definition, examples etc from a view named dict. it was working fine for a month but now it just stopped working.
beside, this query works fine in phpMyadmin!
if ($stmt = $link->prepare("SELECT lemma,pos,sensenum,synsetid,definition ,sampleset FROM dict WHERE lemma = ? ORDER BY pos,sensenum"))
{
$stmt->bind_param("s",$Vocab);
$stmt->execute();
$stmt->bind_result($Lemma, $Pos, $Sensenum, $synsetid, $Def1, $Def2);
while($stmt->fetch())
{
$output[]=array("Pos"=>$Pos,"Sensenum"=>$Sensenum,"Def1"=>$Def1,"Def2"=>$Def2, "pDef"=>'');
}
echo "##*##";
print json_encode($output);
$stmt->close();
}
Check return values at every method/function call and print mysqli_connect_errno(), mysqli_connect_error() and mysqli_stmt_errno($stmt) at relevant places to check for the errors.
The database name may have changed in configuration. The user/password may have changed (if you think they are correct, then run a dummy query like select now() as c1 and see if that works.
If the dummy query works, run your original query, but by removing where clause, and by limiting rows with limit 10 clause.
And, if you figured it out, add that information here for future readers.

Not getting all rows from a query with odbc_exec in php

I'm trying to display how many id's does my procedure finds, but the variable $processz only got the first row of the sql result. It should display that there are 17 rows or id's, and only got 1. Why does it happends?
$conexion = con_abrir();
$sqlquery = "OEE.dbo.VerPlanillas_fechas '$Linea_ID','$fecha1','$fecha2'";
$processz = odbc_exec($conexion,$sqlquery);
con_cerrar($conexion);
$res = count($processz);
echo $res;
count ($processz) tells you how many results you have - one.
If you want to know how many rows are in the result, you need to call odbc_num_rows ($processz);
Look into using PDO rather than odbc specific functions.

Query different MySQL tables from PHP

been googling for hours and I'm quite new to this.
I have two identical tables in one MySQL database:
One named "users" and one named "keys".
They are identical for testing purposes.
When I query "users" I get a response, when I query "keys" I get nothing.
Querying users I get the expected response:
<?php
require('../db/connect.php');
$query = mysql_query("
SELECT name
FROM users
WHERE can_share = '".$_POST['URLkey']."'
");
echo mysql_result($query, 0);
?>
Querying keys I get nothing:
<?php
require('../db/connect.php');
$query = mysql_query("
SELECT name
FROM keys
WHERE can_share = '".$_POST['URLkey']."'
");
echo mysql_result($query, 0);
?>
I guess there must be some basic understanding of databases that has slipped by me, but still, after hours of searching I can't figure it out. Maybe I'm becoming retarded.
I think that might be due to table name being 'keys'.
Have a look here:
http://dev.mysql.com/doc/refman/5.5/en/reserved-words.html
You have to understand while designing your tables and naming the attributes that some words are reserved by MySQL itself.
So, if you name your table 'WHERE' you will have troubles in usual query. Why?
'SELECT * FROM WHERE'
Such a query obviously doesn't work, as it will ask you to provide table name.
Now, when you change format situation also changes:
'SELECT * FROM `WHERE`'
As you can see I added some backwards commas. In MySQL they are used to denote names of tables or fields. If you use them - the server processes and reads your query correctly.
So, that's why your edited query worked fine in the end.
Thanks to enabeling debugging, I got this message:
mysql_result() expects parameter 1 to be resource, boolean given in
...
And figured out that I had to query "keys" like this:
<?php
require('../db/connect.php');
$query = mysql_query("
SELECT `name`
FROM `keys`
WHERE `can_share` = '".$_POST['URLkey']."'
");
echo mysql_result($query, 0);
?>
Now it works, but I still don't understand why only one of the tables needed that formatting. And I have learned that I should rewrite the whole thing to not be vulnerable to SQL injection attacks. ...
EDIT: It seems like the words "key" and "keys" and some more are reserved by MySQL, so to use them, they have to be formatted like that.

Microsoft´s sqlsrv driver for PHP not returning any result when querying "SELECT SCOPE_IDENTITY() AS id"

this query works fine using the php_mssql driver:
INSERT INTO Table(columnName) VALUES ('text');
SELECT SCOPE_IDENTITY() AS id;
Table does have an id column, which is an identity.
I would execute that query, and get the last id in the table.
The same code doesn´t work if the query is executed using Microsoft´s php_sqlsrv driver.
I don´t get any error when executing the query (sqlsrv_query function) , but i get the following error when calling sqlsrv_fetch_array:
"The active result for the query contains no fields"
I´ve googled a lot, and didn´t find no answer, it was a big surprise for me that no one faced this problem before, it seems like nobody is using this driver, even though is the "official" one since PHP 5.3 release...
Thanks.
In the initial CTP the field indices started at 1. Later they were changed to start at 0.
Try something like this:
// connection to the dbserver
$result = sqlsrv_query("INSERT INTO Table(columnName) VALUES ('text'); SELECT SCOPE_IDENTITY() AS ID");
echo "The last insert_id is".lastId($result);
function lastId($queryID) {
sqlsrv_next_result($queryID);
sqlsrv_fetch($queryID);
return sqlsrv_get_field($queryID, 0);
}

Categories