So I have my code
function GetApi($connection,$UserId){
global $Apicall;
$Apicall = array();
$Apiidquery = mysqli_query($connection, "SELECT ID FROM ` Characterapi` WHERE UserId = '$UserId'");
while($results = mysqli_fetch_assoc($Apiidquery)){
$Apicall[] = $results['ID'];
}
}
The output of this function if I call
$Apicall[0] = 3
$Apicall[1] = 11
and this is the information I want. But now I want to use a function like
function Keyquery($Apicall,$connection ){
global $keyidcall, $keyid ,$Vcode;
$Keyidquery = array();
$Keyidquery = mysqli_query($connection, "SELECT keyid, Vcode FROM `Characterapi` WHERE ID = '$Apicall'");
$results = mysqli_fetch_object($Keyidquery);
$keyid = $results->keyid;
$Vcode = $results->Vcode;
}
This code does run if i set $Apicall ="3"; The issue im having is that I want the first function to get All the IDs associated with $userId in my data base then for each Id run the second function to to get the two specific pieces of information from that query.
In response to the comment below, this is the solution which I would use. However you should be wary of using this method as it does not parameterize the values, and as such not sanitized.
<?php
function Keyquery($Apicall,$connection ){
global $keyidcall, $keyid ,$Vcode;
$string = "ID IN('";
$string.= implode("','", $Apicall);
$string.="')";
$Keyidquery = mysqli_query($connection, "SELECT keyid, Vcode FROM `Characterapi` WHERE ".$string.";");
$results = mysqli_fetch_object($Keyidquery);
$keyid = $results->keyid;
$Vcode = $results->Vcode;
}
?>
Related
I'm trying to combine multiple queries into one result set that I can json_encode. I'm trying to get the user's article and article topic in the first query and the amount of likes in the second query. I'm using AJAX to retrieve the data from the database. My AJAX code looks like this, which doesn't seem to be having any problems:
$.ajax({
url: 'includes/articles/getArticlePreview.php',
type: 'POST',
data: {articleId: articleId, idUsers: idUsers},
dataType: 'json',
success: function(data) {
data.forEach(function(item) {
console.log(item.voteCount);
console.log(item.article);
console.log(item.topic);
});
}
});
and on the back end, I did two separate queries and tried to combine them into one JSON object. My first query is like this:
include '../dbh.inc.php';
$idUsers = mysqli_real_escape_string($conn, $_POST['idUsers']);
$articleId = mysqli_real_escape_string($conn, $_POST['articleId']);
$q = "SELECT COUNT(*) FROM articlevotes WHERE articlevotes.article_id = '$articleId'";
$r = mysqli_query($conn, $q);
while ($row = mysqli_fetch_array($r)) {
$voteCount = $row['COUNT(*)'];
$data['voteCount'] = $voteCount;
}
This returns the vote count just fine. Then, I add my second query:
$query = "SELECT articles.article, articles.topic FROM articles WHERE articles.article_id = '$articleId' AND articles.idUsers = '$idUsers'";
$result = mysqli_query($conn, $query);
while ($row = mysqli_fetch_array($result)) {
$article = $row['article'];
$topic = $row['topic'];
$data['article'] = $article;
$data['topic'] = $topic;
}
This works fine on its own, as well (when I delete the first query and only encode this one). But when I try to put them all in a $results[] = $data; array and echo json_encode($results);, I'm only getting the "voteCount" in the JSON object and when I go to the network and click on the file that contains the queries, I get the error messages:
Notice: Undefined index: idUsers in C:\xamp\htdocs\Real Website\includes\articles\getArticlePreview.php on line 5
Notice: Undefined index: articleId in C:\xamp\htdocs\Real Website\includes\articles\getArticlePreview.php on line 6
[{"voteCount":"0"}]
Here's the whole query put together:
<?php
include '../dbh.inc.php';
$idUsers = mysqli_real_escape_string($conn, $_POST['idUsers']);
$articleId = mysqli_real_escape_string($conn, $_POST['articleId']);
$q = "SELECT COUNT(*) FROM articlevotes WHERE articlevotes.article_id = '$articleId'";
$r = mysqli_query($conn, $q);
while ($row = mysqli_fetch_array($r)) {
$voteCount = $row['COUNT(*)'];
$data['voteCount'] = $voteCount;
}
$query = "SELECT articles.article, articles.topic FROM articles WHERE articles.article_id = '$articleId' AND articles.idUsers = '$idUsers'";
$result = mysqli_query($conn, $query);
while ($row = mysqli_fetch_array($result)) {
$article = $row['article'];
$topic = $row['topic'];
$data['article'] = $article;
$data['topic'] = $topic;
}
$results[] = $data;
echo json_encode($results);
I believe I've combined queries like this before, so I'm not sure what I'm doing wrong here. Additionally, is there a better alternative to this than doing two separate queries? Something to combine them in one query? Thanks.
I have this php script that gives me a json response.
<?php
include("init.php");
$string="";
$newString="";
$get_posts = "select * from books_table";
$run_posts = mysqli_query($con,$get_posts);
$posts_array = array();
while ($posts_row = mysqli_fetch_array($run_posts)){
$row_array['title'] = $posts_row['title'];
$row_array['author'] = $posts_row['author'];
$row_array['bookUrl'] = $posts_row['bookUrl'];
$row_array['imageUrl'] = $posts_row['imageUrl'];
$row_array['displayDate'] = $posts_row['displayDate'];
$row_array['numberOfPages'] = $posts_row['numberOfPages'];
array_push($posts_array,$row_array);
}
$string = json_encode($posts_array,JSON_UNESCAPED_UNICODE);
echo $string;?>
And the json I get
[{"title":"Clean Code","author":"Robert Martin","bookUrl":"http:\/\/amzn.to\/1DJybxH","imageUrl":"http:\/\/adavis.github.io\/adept-android\/images\/clean_code.jpg\"","displayDate":"August 11, 2008","numberOfPages":"464"},{"title":"Effective Java","author":"Joshua Bloch","bookUrl":"http:\/\/amzn.to\/1Ku8Xel","imageUrl":"http:\/\/adavis.github.io\/adept-android\/images\/effective_java.jpg","displayDate":"May 28, 2008","numberOfPages":"346"},{"title":"Working Effectively with Legacy Code","author":"Michael Feathers","bookUrl":"http:\/\/amzn.to\/1Jqe1PA","imageUrl":"http:\/\/adavis.github.io\/adept-android\/images\/legacy_code.jpg","displayDate":"October 2, 2004","numberOfPages":"456"},{"title":"Refactoring: Improving the Design of Existing Code","author":"Martin Fowler","bookUrl":"http:\/\/amzn.to\/1Lx4cjR","imageUrl":"http:\/\/adavis.github.io\/adept-android\/images\/refactoring.jpg","displayDate":"July 8, 1999","numberOfPages":"464"}]
I want to perform a query that will return the object whose title contains the word clean.
So I am using this url
[http://www.theo-android.co.uk/books/sample_data.php/q=clean][1]
Hoewever,I get the same json response as before. The object or objects are not filtered out. Why is this happening?
Thanks,
Theo.
If I understand correctly, you want sample_data.php to be able to return filtered data?
first of all, you'll need to update sample_data.php to handle the q param (I would use it as GET since it's simpler: http://www.theo-android.co.uk/books/sample_data.php?q=clean
<?php
include("init.php");
$string="";
$newString="";
$query = mysqli_real_escape_string($con,$_GET['q']); // get and escape the q param
$get_posts = "select * from books_table";
if($query != '') $get_posts .= " WHERE title LIKE '%{$query}%'"; // if $query is not empty string - query using a wild card
$run_posts = mysqli_query($con,$get_posts);
$posts_array = array();
while ($posts_row = mysqli_fetch_array($run_posts)){
$row_array['title'] = $posts_row['title'];
$row_array['author'] = $posts_row['author'];
$row_array['bookUrl'] = $posts_row['bookUrl'];
$row_array['imageUrl'] = $posts_row['imageUrl'];
$row_array['displayDate'] = $posts_row['displayDate'];
$row_array['numberOfPages'] = $posts_row['numberOfPages'];
array_push($posts_array,$row_array);
}
$string = json_encode($posts_array,JSON_UNESCAPED_UNICODE);
echo $string;?>
this way $posts_row will only have the relevant books
--ADDITION----
show book json by id
http://www.theo-android.co.uk/books/sample_data.php?id=1
<?php
include("init.php");
$string="";
$newString="";
$query = mysqli_real_escape_string($con,$_GET['q']); // get and escape the q param
$id = (int)$_GET['id']; // get and cast to int the id var from GET
$where_cond = array();
$get_posts = "select * from books_table";
if($query != '') $where_cond[] = " title LIKE '%{$query}%'"; // if $query is not empty string - query using a wild card
if($id > 0) $where_cond[] = " id = {$id}"; // if $id is a number
if(!empty($where_cond)) $get_posts .= " WHERE " . implode(" AND ",$where_cond);
$run_posts = mysqli_query($con,$get_posts);
$posts_array = array();
while ($posts_row = mysqli_fetch_array($run_posts)){
$row_array['title'] = $posts_row['title'];
$row_array['author'] = $posts_row['author'];
$row_array['bookUrl'] = $posts_row['bookUrl'];
$row_array['imageUrl'] = $posts_row['imageUrl'];
$row_array['displayDate'] = $posts_row['displayDate'];
$row_array['numberOfPages'] = $posts_row['numberOfPages'];
array_push($posts_array,$row_array);
}
$string = json_encode($posts_array,JSON_UNESCAPED_UNICODE);
echo $string;?>
because you want it to work for both id and q (and just one of them) I'm inserting each condition to an array and then implode it with AND separator
it's untested.
I have created the following function to fetch data from my database, but its capabilities are limited. Currently it can fetch one value at a time, which is fine for fetching the value of one column of one row, but as I progress with my work, I now want to be able to fetch multiple values in one call.
The Function:
function retrieve($value, $identifier = null) {
// Check if identifier is given
$identifier = (is_null($identifier)) ? "`ID` = '{$_SESSION["ID"]}'" : $identifier;
// Connect to the database
$connection = connect("limited");
// Pass query, get result and fetch value out of it
$query = "SELECT * FROM `users` WHERE $identifier";
$result = mysqli_query($connection, $query);
if (mysqli_num_rows($result) > 0) {
$data = mysqli_fetch_assoc($result);
return $data[$value];
}
mysqli_close($connection);
}
How I currently use it to fetch multiple values:
// Define variables
$x1 = retrieve("x1");
$x2 = retrieve("x2");
$x3 = retrieve("x3");
$x4 = retrieve("x4");
$x5 = retrieve("x5");
$x6 = retrieve("x6");
$x7 = retrieve("x7");
$x7 = retrieve("x8");
I have read other questions here on Stack Overflow, but none of them solves my problem as I use an optional parameter, which makes my life hard. For example, I thought of implementing the splat operator to allow unlimited parameters, but as I use the optional parameter $identifier, I can't make it into something like:
function retrieve($identifier = null, ...$value) {}
because it will use the first parameter as the identifier when I omit it.
I'm sure that regarding performance it would be better if I could fetch all the necessary values in one call of the function retrieve() instead of using it as shown above and that's why I would like to know:
How can I edit this function in order to fetch more values at once?
Calling it like so:
$x = retrieve($y);
$x1 = $y["x1"];
$x2 = $y["x2"];
...
EDIT:
Thanks to Manish Jesani for his help! I used his answer and modified to do exactly what I want. For anyone that may be interested in the future, here's the code:
function retrieve($value, $identifier = null) {
// Check if identifier is given
$values = array();
$identifier = (is_null($identifier)) ? "`ID` = '1'" : $identifier;
// Connect to the database
$connection = connect("limited");
// Pass query, get result and fetch value out of it
$query = "SELECT * FROM `users` WHERE $identifier";
$result = mysqli_query($connection, $query);
if (mysqli_num_rows($result) > 0) {
$data = mysqli_fetch_assoc($result);
if (is_array($value)) {
foreach($value as $_value) {
$values[$_value] = $data[$_value];
}
return $values;
}
else {
return $data[$value];
}
}
mysqli_close($connection);
}
You can call the function with as many parameters you want. Τo do this you have to use func_num_args() to get all of them, as shown below:
function retrieve() {
$args = func_num_args();
$query = "SELECT '".implode("','", func_get_args())."' FROM `users` WHERE $identifier";
$result = mysqli_query($connection, $query);
if (mysqli_num_rows($result) > 0) {
$data = mysqli_fetch_assoc($result);
return $data;
}
mysqli_close($connection);
}
You can call this function like this: $params = retrieve('x1','x2','x3').
Alternatively, you can retrieve them as variables list($x1, $x2, $x3) = retrieve('x1','x2','x3').
Please try this:
function retrieve($value, $identifier = null) {
// Check if identifier is given
$return = array();
$identifier = (is_null($identifier)) ? "`ID` = '{$_SESSION["ID"]}'" : $identifier;
// Connect to the database
$connection = connect("limited");
// Pass query, get result and fetch value out of it
$query = "SELECT * FROM `users` WHERE $identifier";
$result = mysqli_query($connection, $query);
if (mysqli_num_rows($result) > 0) {
$data = mysqli_fetch_assoc($result);
if(is_array($value))
{
foreach($value as $_value)
{
$return[$_value] = $data[$_value];
}
}
else
{
$return[$value] = $data[$value];
}
return $return;
}
mysqli_close($connection);
}
$x = retrieve(array("x1","x2","x3","x4","x5","x6"));
This is my question below when use codeigniter:
1: query id from DB
2: loop to call my function
public function create_all_static_page(){
$sql = "select id from information where is_static = 0";
$arr = $this->db->query($sql)->result_array();
foreach($arr as $r){
$this->create_static_temp_page($r['id']);
echo $r['id'];
}
}
private function create_static_temp_page($id){
//...another code
$html = $this->load->view('push_db_template_page', $data,true);
$html = addslashes($html);
$info['id'] = $id;
$info['static_content'] = $html;
if($this->db->replace('static_page',$info)){
$sql = "update information set is_static = 1 where id = {$id}";
$this->db->query($sql);
}
}
I have found,it loops just once. That is to say, if I output $r['id'] after $this->create_static_temp_page(); just outputs the first id and the foreach loop has been stopped, but I never use 'return' or 'exit' in my code.
Is there anything wrong with $this->load->view()?
The first question is how to run a function using the URL, I have the following function:
function do_curl($start_index,$stop_index){
// Do query here to get all pages with ids between start index and stop index
$query = "SELECT * FROM xxx WHERE xxx >= $start_index and xxx <= $stop_index";
Now when I'm trying to do curl.php?start_index=0&stop_index=2 this is not working but when i delete the function and WHERE idnum = 1 it is working.
Now the second question is how 'compile' all the fields from the rows to arrays? I have the current code:
$query = "SELECT * FROM fanpages";
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($result))
{
$fanpages_query = '\'http://graph.facebook.com/'.$row['page_id'].'\', ';
echo $fanpages_query;
}
$fanpages = array($fanpages_query);
$fanpages_count = count($fanpages);
echo $fanpages_count;
echo $fanpages_query; returning
'http://graph.facebook.com/AAAAAA', 'http://graph.facebook.com/BBBBBBB', 'http://graph.facebook.com/CCCCCCCC',
(I don't have an idea how to do it in a different way, also when im doing it in such a way i can't delete the final comma which will return PHP-error.)
echo $fanpages_count; returns 1 and like you can see i have 3 there.
Thanks in advance guys!
Do a function call to do the query
function do_curl($start_index, $stop_index){
...
}
$fanpages = do_curl($_GET['start_index'], $_GET['stop_index']);
For your second question, you can use arrays and the implode function to insert commas:
while ($row = mysql_fetch_array($result))
{
$fanpages_query[] = 'http://graph.facebook.com/'.$row['page_id'];
}
return $fanpages_query;
Then use implode to print them out:
echo implode(',', $fanpages);
The whole code:
function do_curl($start_index = 0, $stop_index = null) {
$queryIfThereIsNoStartIndex = '';
$queryIFThereIsNoStopIndex = '';
$queryIfBothStartAndStopIndexAreMissing = '';
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($result))
{
$fanpages_query[] = 'http://graph.facebook.com/'.$row['page_id'];
}
return $fanpages_query;
}
$fanpages = do_curl($_GET['start_index'], $_GET['stop_index']);
$fanpages_count = count($fanpages);
echo implode(',', $fanpages);
And you should totally use mysql_escape_string for escaping the values you add to the query.