Writing the following mySQL request in Doctrine - php

Let me preface by saying I know nothing about doctrine, but at my new position we use it all over the place (not sure why...). Either way, here's the php and mySQL statement I'm trying to turn into a Doctrine statement:
$find_vac = mysql_query("SELECT Vacancies FROM States WHERE Abbreviation = '".$state."'");
I think the part that's tripping me up is where the Abbreviation is a variable. Any help would be greatly appreciated!!!
UPDATE:
$res = Doctrine_Query::create()
->select('Vacancies')
->from('States')
->where('Abbreviation = ?', $state)
->execute();
$vacancies = $res[0]->getVacancies();
The above returns an error.
echo $res['Vacancies']."<br />";
This returns the number 4 no matter which state is selected (and even then all states range from 0-3 for the number of vacancies).

Something like this should do it. The variables can be inserted into the query in the same way as prepared statements.
$res = Doctrine_Query::create()
->select('Vacancies')
->from('States')
->where('Abbreviation = ?', $state)
->execute();
EDIT: This will give you an array of States in array form that match the search criteria. If you just want to get the value of the first one's vacancies, you can get it like this:
$vacancies = $res[0]['Vacancies'];
Or course, you'll also want to check that $res[0] exists and is itself an array in case a bogus or nonexistent $state is used.

Related

Creating an associative array to query one SQL in PHP to get several results

I am new to PHP and would appreciate any assistance in creating an associative array to query a table using SQL.
I want to use one select statement to get multiple results depending on the 'WHERE' key.
$a = $DB->getOne("SELECT DEF_VAL FROM JDEFAULTS WHERE DEF_KEY = :0", array('ip'));
$stmt1 = $DB->getOne("SELECT DEF_VAL FROM JDEFAULTS WHERE DEF_KEY = :0", array('ftpUserid'));
$c = $DB->getOne("SELECT DEF_VAL FROM JDEFAULTS WHERE DEF_KEY = :0", array('ftpPasswd'));
These codes return different values (as expected). I want to merge all of these into one line of SQL and get the values in a list depending on the DEF_KEY value.
how to create associative array from sql table
I have tried following the solutions from this but haven't been able to execute the code.
#Hashibul Hussain i havent understand your questions completly, but as far as i understood you want one query with three conditions. you can try this. this may work.
$stmt1 = $DB->getOne("SELECT DEF_VAL FROM JDEFAULTS WHERE DEF_KEY = :0 or WHERE DEF_KEY = :0 or WHERE DEF_KEY = :0", array('ip'), array('ftpUserid'), array('ftpPasswd'));
please elabrate your question further so that i can come up with better solution.

PHP, MySQL - Return which value was used when input is an array?

I'm running a PDO query, something like:
$inputArr = array(val1, val2, val3, ...);
$qMarks = str_repeat('?,', count($inputArr) - 1) . '?';
$stmt = $db->prepare("SELECT id, name, type, level
FROM table
WHERE name IN ($qMarks)");
$stmt->execute($inputArr);
... parse the rows that have been returned
And this works exactly as expected, no hang-ups or anything.
My problem is that I need to know which value from $inputArr was used to get each row returned.
I've tried
WHERE name IN ($qMarks) AS inputVal
and
WHERE name IN ($qMarks AS inputVal)
but those crash the query.
How can I determine which input array value was used to return each row in the output?
EDIT 1
Yes, I understand that the input search value would be name, for this particular case, but the query above is only for demonstration purposes of how I am putting the search values into the query.
The actual is much more complex, and returns any name value with is close (but not always identical).
The AS keyword is not going to work as you expect it. It's mainly used for aliasing subqueries. You can't (to my knowledge) use it in a WHERE clause.
The scenario you've outlined should have the 'name' in $row['name']. If it was a different variable that you wanted to see, you'd simply add it in your SELECT clause.
Great question, and simple answer:
The WHERE name IN $qMarks)"); part of your code is only obtaining the values in your database that are matching your array, so what you can do is see which values of name are present in the row you fetched. For example:
$rows_fetched = $stmt->fetchAll(PDO::FETCHASSOC);
$inputArray = array();
foreach($rows_fetched as $value)
{
$inputArray[] = $value['name'];
}
print_r($inputArray);//printing the results
Now you have the array $inputArray with all the values used to return each row in the output. Let me know if that worked for you!

SQL query result to string

I'm using SQL in Yii framework.
I need to show the person's latest active week (it's number and date).So I wrote following code:
public function latestWeek()
{
$datalogin=//the login is working fine
$sql ="SELECT w.number,MAX(w.start_date)
FROM tbl_person_week t, tbl_week w
WHERE t.person_id=$this->id AND t.week_id=w.id";
$query = mysqli_query($datalogin, $sql);
return $query;
}
Now , I checked this query on the server and it works fine (almost) but first thing: I need to convert it into string , because yii's CgridView can't read it , and I couldn't find a working solution for this.
Second: on the server , it gave me the max date indeed , but not it's correct number , but the first number available. How can I fix this as well?
Queries like that should never be used in objective framework. If yu want to execute your own query, you should do it this way:
$sql = "your sql code";
$array = Yii::app()->db->createCommand($sql)->queryAll();
As result you will get multidimensional array with selected columns and rows
If you want to use it in grid view, you should do it this way:
$count = Yii::app()->db->createCommand($sql)->queryScalar();
$dataProvider = new CSqlDataProvider($sql, array('totalItemCount'=>$count));
$this->widget('zii.widgets.grid.CGridView', array(
'id'=>'grid-id',
'dataProvider'=> $dataProvider,
));
You can also use connection other than Yii::app()->db. Check CDbConnection class in docs.
edit: if you wanna use queries like mysql_fetch_assoc, check out also queryRow() method instead of queryAll()
Use Mysql_fetch _array
public function latestWeek()
{
$datalogin=//the login is working fine
$sql ="SELECT w.number,MAX(w.start_date)
FROM tbl_person_week t, tbl_week w
WHERE t.person_id=$this->id AND t.week_id=w.id";
$query = mysqli_query($datalogin, $sql);
while($row = mysqli_fetch_array($query)){
echo $row;
}
}
Assuming from your qu. that you want the week number and start date as one string, you have to concatenate the two columns in the sql.
You also need to specify that the week number is from the row with the maximum start date, which isn't as simple as you might first think.
I don't like injecting the person_id straight into SQL, it isn't awful in this case but is a bad habit to get into security-wise. There are binding methods available in the framework and I agree with Arek, that you should lean on the yii framework as much as possible.
To get the scalar string value, if you are insisting on using your own SQL.. I suggest the following:
$sql='
SELECT CONCAT('Week ',tw.number,' starting ',tw.start_date)
FROM tbl_week tw
JOIN (
SELECT MAX(twi.start_date) max_start_date
FROM tbl_week twi
JOIN tbl_person_week tpwi
ON tpwi.week_id = twi.id
AND tpwi.person_id = :person_id
) i
ON tw.start_date = i.max_start_date;
';
$command=Yii::app()->db->createCommand($sql);
$command->bindParam(":person_id", $this->id);
return $command->queryScalar();

Proper Query in RETS

I need a little assistance regarding to RETS. I have not worked in it before. I am stuck at a point.
Here is the code
$rets_modtimestamp_field = "LastTr_260";
$previous_start_time = "2013-01-01T00:00:00";
$listing_status = "Status_383";
$listing_price = "ListPr_276";
The original query that I got was
$query = "({$rets_modtimestamp_field}={$previous_start_time}+)";
I had to update the query to add listing status and listing price. I searched around over the internet and updated the query to this.
$query = "(ListPrice=ListPr_276),(ModificationTimestamp=LastTr_260),(ListingStatus=Status_383),(".$previous_start_time."+)";
This is where the query is being used..
$search = $rets->SearchQuery("Property", $class, $query, array('Limit' => 1000));
Any ideas why the query is returning no results? I feel there is something in reference to start time...I have no idea about it...
Any help would be highly appreciated.
Thanks and Cheers
Ahmad
The last condition in your query is missing the name in the name=value pair. So your query would translate to:
$query = "(ListPrice=ListPr_276),(ModificationTimestamp=LastTr_260),(ListingStatus=Status_383),(2013-01-01T00:00:00+)";
With the name-value pair:
$query = "(ListPrice=ListPr_276),(ModificationTimestamp=LastTr_260),(ListingStatus=Status_383),({$rets_modtimestamp_field}={$previous_start_time}+)";
These look like the type of RETS field names that come from Interealty - one of the major RETS vendors. There are five variations of RETS field names - the "SystemName", "StandardName", "LongName", "ShortName", and "DBName." You appear to be querying on the DBName, which usually is not queryable. Try the SystemName, which should always be queryable. Interealty uses numeric SystemNames, so your list price field, ListPr_176, would very likely have the SystemName "176". The part of the query for the price would then look more like "(176=0+)". The entire query code should probably look more like this:
$rets_modtimestamp_field = "260";
$previous_start_time = "2013-01-01T00:00:00";
$listing_status = "383";
$listing_price = "276";
$query = "(".$listing_price."=0+),(".$listing_status."=|A),(".$rets_modtimestamp_field."=".$previous_start_time."+)";
(I added a presumed lookup value for Listing Status of active)

SQL full text search with PHP and PDO

I'm trying to write a simple, full text search with PHP and PDO. I'm not quite sure what the best method is to search a DB via SQL and PDO. I found this this script, but it's old MySQL extension. I wrote this function witch should count the search matches, but the SQL is not working. The incoming search string look like this: 23+more+people
function checkSearchResult ($searchterm) {
//globals
global $lang; global $dbh_pdo; global $db_prefix;
$searchterm = trim($searchterm);
$searchterm = explode('+', $searchterm);
foreach ($searchterm as $value) {
$sql = "SELECT COUNT(*), MATCH (article_title_".$lang.", article_text_".$lang.") AGINST (':queryString') AS score FROM ".$db_prefix."_base WHERE MATCH (article_title_".$lang.", article_text_".$lang.") AGAINST ('+:queryString')";
$sth = $dbh_pdo->prepare($sql);
$sql_data = array('queryString' => $value);
$sth->execute($sql_data);
echo $sth->queryString;
$row = $sth->fetchColumn();
if ($row < 1) {
$sql = "SELECT * FROM article_title_".$lang." LIKE :queryString OR aricle_text_".$lang." LIKE :queryString";
$sth = $dbh_pdo->prepare($sql);
$sql_data = array('queryString' => $value);
$sth->execute($sql_data);
$row = $sth->fetchColumn();
}
}
//$row stays empty - no idea what is wrong
if ($row > 1) {
return true;
}
else {
return false;
}
}
When you prepare the $sql_data array, you need to prefix the parameter name with a colon:
array('queryString' => $value);
should be:
array(':queryString' => $value);
In your first SELECT, you have AGINST instead of AGAINST.
Your second SELECT appears to be missing a table name after FROM, and a WHERE clause. The LIKE parameters are also not correctly formatted. It should be something like:
sql = "SELECT * FROM ".$db_prefix."_base WHERE article_title_".$lang." LIKE '%:queryString%' OR aricle_text_".$lang." LIKE '%:queryString%'";
Update 1 >>
For both SELECT statements, you need unique identifiers for each parameter, and the LIKE wildcards should be placed in the value, not the statement. So your second statement should look like this:
sql = "SELECT * FROM ".$db_prefix."_base WHERE article_title_".$lang." LIKE :queryString OR aricle_text_".$lang." LIKE :queryString2";
Note queryString1 and queryString2, without quotes or % wildcards. You then need to update your array too:
$sql_data = array(':queryString1' => "%$value%", ':queryString2' => "%$value%");
See the Parameters section of PDOStatement->execute for details on using multiple parameters with the same value. Because of this, I tend to use question marks as placeholders, instead of named parameters. I find it simpler and neater, but it's a matter of choice. For example:
sql = "SELECT * FROM ".$db_prefix."_base WHERE article_title_".$lang." LIKE ? OR aricle_text_".$lang." LIKE ?";
$sql_data = array("%$value%", "%$value%");
<< End of Update 1
I'm not sure what the second SELECT is for, as I would have thought that if the first SELECT didn't find the query value, the second wouldn't find it either. But I've not done much with MySQL full text searches, so I might be missing something.
Anyway, you really need to check the SQL, and any errors, carefully. You can get error information by printing the results of PDOStatement->errorCode:
$sth->execute($sql_data);
$arr = $sth->errorInfo();
print_r($arr);
Update 2 >>
Another point worth mentioning: make sure that when you interpolate variables into your SQL statement, that you only use trusted data. That is, don't allow user supplied data to be used for table or column names. It's great that you are using prepared statements, but these only protect parameters, not SQL keywords, table names and column names. So:
"SELECT * FROM ".$db_prefix."_base"
...is using a variable as part of the table name. Make very sure that this variable contains trusted data. If it comes from user input, check it against a whitelist first.
<< End of Update 1
You should read the MySQL Full-Text Search Functions, and the String Comparison Functions. You need to learn how to construct basic SQL statements, or else writing even a simple search engine will prove extremely difficult.
There are plenty of PDO examples on the PHP site too. You could start with the documentation for PDOStatement->execute, which contains some examples of how to use the function.
If you have access to the MySQL CLI, or even PHPMyAdmin, you can try out your SQL without all the PHP confusing things. If you are going to be doing any database development work as part of your PHP application, you will find being able to test SQL independently of PHP a great help.

Categories