Is there a way to combine SQL with FQL.
I am talking about something like FQL multiqueries.
This is my sample code.
//Here I take data from a SQL database
$result_user_pages = mysql_query("SELECT Page_ID FROM user_fanpage WHERE User_ID='$uid'");
while($row = mysql_fetch_array($result_user_pages))
{
$user_page_ID[$m] = $row['Page_ID'] ;
$m++;
}
//Here I pass '$user_page_ID' array into a for loop and call facebook api
for ($i=0; $i
$query1 = "SELECT post_id FROM stream WHERE source_id='$user_page_ID[$i]'";
$query2 = "SELECT fromid,text from comment WHERE post_id IN (SELECT post_id FROM #query1)";
$queries = '{
"query1": "' . $query1 . '",
"query2": "' . $query2 . '"
}';
$attachment = array("method"=>"fql.multiquery","queries"=>$queries,'access_token'=>$access_token);
$ret_code = $facebook->api($attachment);
}
If '$user_page_ID' has 10 elements, api is called 10 times.Therefore sometime it gives me a connection time out error message.If there is a away to combine sql query with fql(like fql multiqueries), I can avoid this error message.
Can any one tell me whether there is a way to do this or any other solution...??
You cannot do that with the restrictions that are in place
Related
I need to change this query to use a prepared statement. Is it possible?
The query:
$sql = "SELECT id, title, content, priority, date, delivery FROM tasks " . $op . " " . $title . " " . $content . " " . $priority . " " . $date . " " . $delivery . " ORDER BY " . $orderField . " " . $order . " " . $pagination . "";
Before the query, there's code to check the POST variables and change the content of variables in the query.
//For $op makes an INNER JOIN with or without IN clause depending on the content of a $_POST variable
$op = "INNER JOIN ... WHERE opID IN ('"$.opID."')";
//Or
$op = "INNER JOIN ... ";
//For $title (depends of $op):
$title = "WHERE title LIKE'%".$_POST["title"]."%'";
//Or
$title = "AND title LIKE'%".$_POST["title"]."%'";
//For $content:
$content = "AND content LIKE '%".$_POST["content"]."%'";
//For $priority just a switch:
$priority = "AND priority = DEPENDING_CASE";
//For $date and $delivery another switch
$d = date("Y-m-d", strtotime($_POST["date"]));
$date = "AND date >= '$d' 00:00:00 AND date <= '$d' 23:59:59";
//Or $date = "AND date >= '$d' 00:00:00";
//Or $date = "AND date <= '$d' 23:59:59";
//For $orderField
$orderField = $_POST["column"];
//For $order
$order= $_POST["order"];
//For $pagination
$pagination = "LIMIT ".$offset.",". $recordsPerPage;
How I could do this query using prepared statement?
The query could be more static but this means to make different prepared statements and execute it depending of $_POST checks.
It depends on many variables because this query show results in a table that contains search fields and column to order.
A full example of query would be like this (depending of $_POST checks):
SELECT id, title, content, priority, date, delivery FROM tasks INNER JOIN op ON task.op = op.opId WHERE op IN (4851,8965,78562) AND title LIKE '%PHT%' AND content LIKE '%%' AND priority = '2' ORDER BY date DESC LIMIT 0, 10
An excellent question. And thank you for moving to prepared statements. It seems that after all those years of struggle, the idea finally is starting to take over.
Disclaimer: there will be links to my own site because I am helping people with PHP for 20+ years and got an obsession with writing articles about most common issues.
Yes, it's perfectly possible. Check out my article, How to create a search filter for mysqli for the fully functional example.
For the WHERE part, all you need is to create two separate arrays - one containing query conditions with placeholders and one containing actual values for these placeholders, i.e:
WHERE clause
$conditions = [];
$parameters = [];
if (!empty($_POST["content"])) {
$conditions[] = 'content LIKE ?';
$parameters[] = '%'.$_POST['content ']."%";
}
and so on, for all search conditions.
Then you could implode all the conditions using AND string as a glue, and get a first-class WHERE clause:
if ($conditions)
{
$where .= " WHERE ".implode(" AND ", $conditions);
}
The routine is the same for all search conditions, but it will be a bit different for the IN() clause.
IN() clause
is a bit different as you will need more placeholders and more values to be added:
if (!empty($_POST["opID"])) {
$in = str_repeat('?,', count($array) - 1) . '?';
$conditions[] = "opID IN ($in)";
$parameters = array_merge($parameters, $_POST["opID"]);
}
this code will add as many ? placeholders to the IN() clause as many elements in the $_POST["opID"] and will add all those values to the $parameters array. The explanation can be found in the adjacent article in the same section on my site.
After you are done with WHERE clause, you can move to the rest of your query
ORDER BY clause
You cannot parameterize the order by clause, because field names and SQL keywords cannot be represented by a placeholder. And to tackle with this problem I beg you to use a whitelisting function I wrote for this exact purpose. With it you can make your ORDER BY clause 100% safe but perfectly flexible. All you need is to predefine an array with field names allowed in the order by clause:
$sortColumns = ["title","content","priority"]; // add your own
and then get safe values using this handy function:
$orderField = white_list($_POST["column"], $sortColumns, "Invalid column name");
$order = white_list($_POST["order"], ["ASC","DESC"], "Invalid ORDER BY direction");
this is a smart function, that covers three different scenarios
in case no values were provided (i.e. $_POST["column"] is empty) the first value from the white list will be used, so it serves as a default value
in case a correct value provided, it will be used in the query
in case an incorrect value is provided, then an error will be thrown.
LIMIT clause
LIMIT values are perfectly parameterized so you can just add them to the $parameters array:
$limit = "LIMIT ?, ?";
$parameters[] = $offset;
$parameters[] = $recordsPerPage;
The final assembly
In the end, your query will be something like this
$sql = "SELECT id, title, content, priority, date, delivery
FROM tasks INNER JOIN ... $where ORDER BY `$orderField` $order $limit";
And it can be executed using the following code
$stmt = $mysqli->prepare($sql);
$stmt->bind_param(str_repeat("s", count($parameters)), ...$parameters);
$stmt->execute();
$data = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
where $data is a conventional array contains all the rows returned by the query.
what i need to fetch data from stored procedures
syntax in sql developer
select abc_web_demo.wwv_json_data.dashboards('abc','7','tt',1211) from dual
returns json string
{"data":[{"logs":7,"to_abc":88,"to_cl":12,"to_me":0}]}
code
$tns = "
(DESCRIPTION =
(ADDRESS_LIST =
(ADDRESS = (PROTOCOL = TCP)(HOST =ABC)(PORT = 1521))
)
(CONNECT_DATA = (SID = AAA))
)
";
try {
$conn = new PDO("oci:dbname=".$tns, '**', '**');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo 'Connected to database';
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
$sql = "CALL abc_web_demo.wwv_json_data.dashboards('ABC','79','Y',121221) ";
$stmt = $conn->prepare($sql);
$te=$stmt->execute();
//$stmt = $connection->query("SELECT #NEW_ID");
//$id = $stmt->fetchColumn();
print_r($te);
Problem
i have google & found i need to pass in string in query
like $stmt = $connection->query("SELECT #NEW_ID");
here in my my case i need to pass 4 parameters in procedure.
i new in stored procedures i need help how to pass 4 arguments in procedure .
how to access json response using fetch statement.
i need json repsonse from fetch data.
any help much appreciated
Solution i tried
$output = $conn->query("select 'abc', '7' ")->fetch(PDO::FETCH_ASSOC);
var_dump($output);
Error
SQLSTATE[HY000]: General error: 923 OCIStmtExecute: ORA-00923: FROM keyword not found where expected
when i tried test query it works
$stmt = $conn->prepare("select * from customers");
$st=$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
print_r($result);
Write your query as follows. The FROM clause is mandatory in Oracle dialect of SQL.
select 'abc', '7' from dual
this my model code:
function get_ads($page=0, $type, $limit=1, $order=' order by rand()') {
if ($page === 0) {
$page = $this->get_adpage();
$qry = "select * from tbl_ads ";
$qry .= " where status=1 and pages like '%".$page. "%'";
$qry .= " and type = ".intval($type);
$qry .= $order;
$qry .= intval($limit) > 1 ? " limit 0,".$limit : " limit 0,1";
$results = $this->db->query($qry)->result(); return $results;}
}
}
Query like this
SELECT * FROM tbl_ads WHERE STATUS=1 AND pages LIKE '%1%' AND TYPE = 1 ORDER BY RAND() LIMIT 0,1`
Controller code is
function get_ads(){
$this->main_model->get_ads(14,2,1);
}
Its working fine local when uploading to server showing fatal error some times but some times its working fine.
Thanks for your help
Here the solution
$this->db->query($qry)->result() in this instead of result() result_array() for multiple rows or row_array() for single row of result did the trick
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Why do I get “Resource id #4” when I apply print_r() to an array in PHP?
How do i “echo” a “Resource id #6” from a MySql response in PHP?
why do i get "Resource id #6" as result in $result? want 1 or 0 :P
$sql = "SELECT * FROM members WHERE rchat=1 LIMIT 1";
$result = mysql_query($sql);
if (!$result) {
unlink($fn);
//$fn = $_SESSION['sess_user'].'.txt';
$fn = 'hittaingen.txt';
mysql_query("UPDATE members SET rchat=1 room='" . $_SESSION['sess_user'] . "' WHERE user='" . $_SESSION['sess_user'] . "'");
}
else {
//$fn = $result['room'].'.txt';
$fn = 'hitta.txt';
mysql_query("UPDATE members SET rchat=2 room='" . $result['room'] . "' WHERE user='" . $_SESSION['sess_user'] . "'");
}
mysql_query() returns just a reference of the result object and not the result itself. So in order to get you 0 or 1, you got to parse the result first using, e.g., mysql_fetch_array()
$row = mysql_fetch_array( $result );
Besides, you should definitely look into PDO and mysqli, as the the mysql_X() functions are marked as deprecated and generally not considered safe against SQL injections!
I'm trying to a single value in my DB...When I run it through the console, it works correctly (as I'm replacing the variables with numbers and text).. However, My query is not returning a value for book ID when I insert the PHP variable for it.. It's because the book_id is unpopulated...
$query = "UPDATE books "
. "SET readstatus='".$readstatus."' "
. "WHERE book_id=".$book_id;
echo $query
The echoed query states:
UPDATE books SET readstatus='half' WHERE book_id=0
The book ID is stored in the URI as bookstatusupdate.php?book_id=
Just cannot figure this one out!
It would help to know the error. Firstly, echo out the query:
$query = "UPDATE books "
. "SET readstatus='".$readstatus."' "
. "WHERE book_id=".$book_id;
echo $query;
I would guess that $book_id is unpopulated, so the query fails. What you should really be doing to make it secure is casting integers with (int) and wrapping strings in mysqli_real_escape_string().
$query = "UPDATE books "
."SET readstatus='". mysqli_real_escape_string( $readstatus )."' "
."WHERE book_id=". (int) $book_id;
If you're trying to get data from the URL, do it like so:
$book_id = (int) $_GET['book_id'];
$query = "UPDATE books "
."SET readstatus='". mysqli_real_escape_string( $readstatus )."' "
."WHERE book_id=". (int) $book_id;
echo $query;