MYSQL/Laravel LIKE behaving unexpectedly - php

I have a bunch of mathematical tasks which I want to filter through a textbox.
For example:
4*1 should return 4*1, 4*10, 4*11, ...
4*11 should return 4*11
To do that I wrote this piece of code:
$operator = DB::connection()->getPdo()->quote("{$operator}");
$operand2 = DB::connection()->getPdo()->quote("{$operand2}%");
DB::table('tasks')
->select(DB::raw('*'))
->whereRaw("operand1 = {$operand1} AND operator = {$operator} AND CAST(operand2 AS CHAR(50)) LIKE {$operand2}")
->get();
The results of this are pretty unexpected und unpredictable.
When I type 4*5 I get 4*{any operand}
When I type 4*12 I get 4*1, 4*10, 4*11, 4*12
UPDATE/SOLUTION
It turned out that it didn't have anything to with MySQL or Laravel. It was an error in JS. I used the keypress event instead of keyup. This way always the last typed digit was lost.

Related

Find the smallest number in php / SQL

I have a code that looks for the smallest number in the average column. When in mysql, I put the column in "double", it works. But for some reasons and particular actions, my column must be in "text". I need a php / SQL code to show the smallest number.otherwise my code tells me that 13.06 is smaller than 8.56.here is my code:
$sql1 = "SELECT MIN(moyenne)as moyenneP FROM rangec where classe = '".$_SESSION['classroom']."' AND position = '".$_SESSION['anscol']."'
AND ecoles= '".$_SESSION['ecoles']."' AND trimestre= '".$_SESSION['trimestre']."'";
foreach ($bdd->query($sql1) as $classement)
{
$moyenneP =$classement['moyenneP'];
$moyenneP=''.round($moyenneP, 2).'';
}
I believe I have been explicit! Thank you in advance for your assistance.

PHP SQLite - prepared statement misbehaves?

I have the following SQLite table
CREATE TABLE keywords
(
id INTEGER PRIMARY KEY,
lang INTEGER NOT NULL,
kwd TEXT NOT NULL,
count INTEGER NOT NULL DEFAULT 0,
locs TEXT NOT NULL DEFAULT '{}'
);
CREATE UNIQUE INDEX kwd ON keywords(lang,kwd);
Working in PHP I typically need to insert keywords in this table, or update the row count if the keyword already exists. Take an example
$langs = array(0,1,2,3,4,5);
$kwds = array('noel,canard,foie gras','','','','','');
I now these data run through the following code
$len = count($langs);
$klen = count($kwds);
$klen = ($klen < $len)?$klen:$len;
$sqlite = new SQLite3('/path/to/keywords.sqlite');
$iStmt = $sqlite->prepare("INSERT OR IGNORE INTO keywords (lang,kwd)
VALUES(:lang,:kwd)");
$sStmt = $sqlite->prepare("SELECT rowid FROM keywords WHERE lang = :lang
AND kwd = :kwd");
if (!$iStmt || !$sStmt) return;
for($i=0;$i < $klen;$i++)
{
$keywords = $kwds[$i];
if (0 === strlen($keywords)) continue;
$lang = intval($langs[$i]);
$keywords = explode(',',$keywords);
for($j=0;$j < count($keywords);$j++)
{
$keyword = $keywords[$j];
if (0 === strlen($keyword)) continue;
$iStmt->bindValue(':kwd',$keyword,SQLITE3_TEXT);
$iStmt->bindValue(':lang',$lang,SQLITE3_INTEGER);
$sStmt->bindValue(':lang',$lang,SQLITE3_INTEGER);
$sStmt->bindValue(':kwd',$keyword,SQLITE3_TEXT);
trigger_error($keyword);
$iStmt->execute();
$sqlite->exec("UPDATE keywords SET count = count + 1 WHERE lang =
'{$lang}' AND kwd = '{$keyword}';");
$rslt = $sStmt->execute();
trigger_error($sqlite->lastErrorMsg());
trigger_error(json_encode($rslt->fetchArray()));
}
}
which generates the following trigger_error output
Keyword: noel
Last error: not an error
SELECT Result: {"0":1,"id":1}
Keyword: canard
Last Error: not an error
SELECT Reult:false
Keyword:foiegras
Last Error: not an error
SELECT Result: false
From the SQLite command line I see that the three row entries are present and correct in the table with the id/rowid columns set to 1, 2 and 3 respectively. lastErrorMsg does not report an error and yet two of the three $rslt->fetchArray() statements are returning false as opposed to an array with rowid/id attributes. So what am I doing wrong here?
I investigated this a bit more and found the underlying case. In my original code the result from the first SQLite3::execute - $iStmt-execute() - was not being assigned to anything. I did not see any particular reason for fetching and interpreting that result. When I changed that line of code to read $rslt = $iStmt->execute() I got the expected result - the rowid/id of the three rows that get inserted was correctly reported.
It is as though internally the PHP SQLite3 extension buffers the result from SQLiteStatement::execute function calls. When I was skipping the assignment my next effort at running such a statement, $sStmt->execute() was in effect fetching the previous result. This is my interpretation without knowing the inner workings of the PHP SQLite3 extension. Perhaps someone who understands the extension better would like to comment.
Add $rslt = NONE; right after trigger_error(json_encode($rslt->fetchArray())); and the correct results appear.
FetchArray can only be called once and somehow php is not detecting that the variable has changed. I also played with changing bindValue to bindParam and moving that before the loop but that is unrelated to the main issue.
It is my opinion that my solution should not work unless there is a bug in php. I am too new at the language to feel confident in that opinion and would like help verifying it. Okay, not a bug, but a violation of the least surprise principle. The object still exists in memory so without finalizing it or resetting the variable, fetch array isn't triggering.

SOAP API / SQL Error "ORA 00904 invalid Identifier"

I have the following problem:
I need to get a few columns of a oracle db table to display information on a .php page. To do this, I'm using a SOAP-API, which works flawlessly with any other table, only not with this one.
This is the Code I am using for all of these Queries:
$setSearchObjectsIn = new SearchObjectsInType();
$setSearchObjectsIn->sessionId = (String) $sessionId;
$setSearchObjectsIn->table = (String) 'STFCFG_DD_VALUE';
$setSearchObjectsIn->caseSensitive = (String) 'false';
$setSearchObjectsIn->limitedResult = (String) 'false';
$setSearchObjectsIn->restrictions[0]['attributeName']= (String) 'STFCFG_DD_VALUE.DDID';
$setSearchObjectsIn->restrictions[0]['restriction']['operator'] = (String) '=';
$setSearchObjectsIn->restrictions[0]['restriction']['value'] = (String) $ddid;
$setSearchObjectsIn->resultColumns[0] = (String) 'STFCFG_DD_VALUE.DD_VALUE';
$setSearchObjectsIn->resultColumns[1] = (String) 'STFCFG_DD_VALUE.CATALOG_NAME';
$setSearchObjectsIn->resultColumns[2] = (String) 'STFCFG_DD_VALUE.MSG_ID';
$client = new SoapClient((String) $instance.'/axis/services/GenericApiWS?wsdl');
$result = $client->searchObjects($setSearchObjectsIn);
And this is the Error I get with this special table:
ORA-00904: "MAN_ID": ungültiger Bezeichner
I have also tried starting this query with SoapUI, which results in the exactly same thing.
The fact, that I have nothing like "MAN_ID" in my code has me wondering, as the error looks like I would query a column named like that, which I obviously don't do. (There is also no column "MAN_ID" in the requested table, so I have no idea where this comes from)
I hope you can help me
I'd try looking for MAN_ID in the SOAP server code - the error may be what the server returns and it may be looking for that column implicitly. The error message is definitely produced by Oracle, so search the way your query gets there and if possible, see what query gets executed.

Pass By Reference to COM Object in PHP

So I'm hoping someone can help and I'm sure this is probably something simple I'm missing. I'm using PHP to access a .net API for a third party software.
Based on the very minimalist documentation on the API I have a working vbsript that connects to the object, performs a login and then does a query which results in the output of the query being dumped to a message box.
Here's the vbscript sample:
'Test device status
Set xxx = CreateObject("The.API.Object.Goes.Here")
'Login
Result = Xxx.LoginToHost("xxx.xxx.xxx.xxx","8989","Administrator","")
if (Result = true) then
MsgBox("OK")
else
MsgBox("Error - " & Xxx.LastError)
WScript.Quit
end if
'Get Status
Result = Xxx.GetDeviceStatus("", out)
if (Result = true) then
MsgBox(out)
else
MsgBox("Error - " & Xxx.LastError)
end if
'Logout
Result = Xxx.Logout()
if (Result = true) then
MsgBox("Logout OK")
else
MsgBox("Error - " & Xxx.LastError)
end if
The Xxx.GetDeviceStatus has two perimeters, the first being a device target or if left blank returns all devices, the second is the string variable to dump the result in.
When the script executes, the second message box contains a list of all devices as I would expect.
In PHP I have:
$obj = new DOTNET("XxxScripting, Version=1.0.XXXX.XXXXXX, Culture=neutral, PublicKeyToken=XXXXXXXXXXXXXXXX","Here.Goes.The.Api");
$obj->LoginToHost('xxx.xxx.xxx.xxx','8989','Administrator','');
$result = $obj->GetDeviceStatus('','out');
echo $result."<br />";
echoing result gives 1 because the value of result is a boolean value and GetDeviceStatus is successful. What I can't figure out is how to get the value of 'out' which is the actual query result.
Any help would be greatly appreciated.
The second parameter of GetDeviceStatus() method call according to the VBScript should pass a variable that will be populated with the output.
However in the PHP example you are just passing the string 'out' which isn't equivalent to what is being done in the VBScript.
Instead try passing a PHP variable to the method and then echoing that variable to screen, like this;
$result = $obj->GetDeviceStatus('', $out);
if ($result)
echo $out."<br />";
After a bit of digging it appears according to the PHP Reference that you need to pass By Reference variables to COM using the VARIANT data type.
Quote from ferozzahid [at] usa [dot] com on PHP - COM Functions
"To pass a parameter by reference to a COM function, you need to pass VARIANT to it. Common data types like integers and strings will not work for it."
With this in mind maybe this will work;
$out = new VARIANT;
$result = $obj->GetDeviceStatus('', $out);
if ($result)
echo $out."<br />";

How do I validate a PHP integer within a variable?

I have integrated Yelp reviews into my directory site with each venue that has a Yelp ID returning the number of reviews and overall score.
Following a successful MySQL query for all venue details, I output the results of the database formatted for the user. The Yelp element is:
while ($searchresults = mysql_fetch_array($sql_result)) {
if ($yelpID = $searchresults['yelpID']) {
require('yelp.php');
if ( $numreviews > 0 ) {
$yelp = '<img src="'.$ratingimg.'" border="0" /> Read '.$numreviews.' reviews on <img src="graphics/yelp_logo_50x25.png" border="0" /><br />';
} else {
$yelp = '';
}
} //END if ($yelpID = $searchresults['yelpID']) {
} //END while ($searchresults = mysql_fetch_array($sql_result)) {
The yelp.php file returns:
$yrating = $result->rating;
$numreviews = $result->review_count;
$ratingimg = $result->rating_img_url;
$url = $result->url;
If a venue has a Yelp ID and one or more reviews then the output displays correctly, but if the venue has no Yelp ID or zero reviews then it displays the Yelp review number of the previous venue.
I've checked the $numreviews variable type and it's an integer.
So far I've tried multiple variations of the "if ( $numreviews > 0 )" statement such as testing it against >=1, !$numreviews etc., also converting the integer to a string and comparing it against other strings.
There are no errors and printing all of the variables returned gives the correct number of reviews for each property with venues having no ID or no reviews returning nothing (as opposed to zero). I've also compared it directly against $result->review_count with the same problem.
Is there a better way to make the comparison or better format of variable to work with to get the correct result?
EDIT:
The statement if ($yelpID = $searchresults['yelpID']) { is not operating as it should. It is identical to other statements in the file, validating row contents which work correctly for their given variable, e.g. $fbID = $searchresults['fbID'] etc.
When I changed require('yelp.php'); to require_once('yelp.php'); all of the venue outputs changed to showing only the first iterated result. Looking through the venues outputted, the error occurs on the first venue after a successful result which makes me think there is a pervasive piece of code in the yelp.php file, causing if ($yelpID = $searchresults['yelpID']) { to be ignored until a positive result is found (a yelpID in the db), i.e. each venue is correctly displayed with a yelp number of reviews until a blank venue is encountered. The preceding venues' number of reviews is then displayed and this continues for each blank venue until a venue is found with a yelpID when it shows the correct number again. The error reoccurs on the next venue output with no yelpID and so on.
Sample erroneous output: (line 1 is var_dump)
string(23) "bayview-hotel-bushmills"
Bayview Hotel
Read 3 reviews on yelp
Benedicts
Read 3 reviews on yelp (note no var_dump output, this link contains the url for the Bayview Hotel entry above)
string(31) "bushmills-inn-hotel-bushmills-2"
Bushmills Inn Hotel
Read 7 reviews on yelp
I suspect this would be a new question rather than clutter/confuse this one further?
END OF EDIT
Note: I'm aware of the need to upgrade to mysqli but I have thousands of lines of legacy code to update. For now I'm working on functionality before reviewing the code for best practice.
Since the yelp.php is sort of a blackbox; the best explanation for this behavior would be that it only set's those variables if it finds a match. Updating your code to this should fix that:
unset($yrating, $numreviews, $ratingimg, $url);
require('yelp.php');
I also noticed this peculiar if-statement, do you realize that's an assignment or is this a copy/paste error? If you want to test (that's what if is for)
if ($yelpID == $searchresults['yelpID']) {

Categories