Alright, so i've got this code here (it's from a class)
function getResourceXML($id)
{
$xml = simplexml_load_file('resources.xml');
$array = array();
foreach($xml->catagory->resource as $children)
{
if(in_array($children['id'], $id))
{
array_push( $array, (string)$children['income'] );
}
print_r($array);
echo '<br />';
}
return $array;
}
function getResourceMultiplier()
{
$sql = "SELECT resourceArray FROM starinformation WHERE starOwner = :uid";
$que = $this->db->prepare($sql);
$que->bindParam('uid', $this->uid);
$resource = array();
try
{
$que->execute();
while($row = $que->fetch(PDO::FETCH_BOTH))
{
array_push($resource, $row[0]);
}
$resource = $this->getResourceXML($resource);
return $resource;
}
catch(PDOException $e) {}
}
I had to alter it after I realized my live server is php 4 instead of 5. It was working until i got ride of all the $array[] elements. now the array_push isn't inserting duplicate entries (at least I think that's what is going on)
Related
I can't understand and I seek for help=(
Here is my code:
$add_article = $this->M_articles->Add($_POST['title'], $_POST['content']);
echo "sd;flksdf;lksdfl;";
$add_article2 = true;
if ($add_article)
{
echo 'Article Added!';
header("Location:index.php");
die();
}
else
die('Error adding article');
this is function "Add" from M_Articles:
public function Add($title, $content)
{
/*
$title = trim($title);
$content = trim($content);
if ($title == '')
return false;
//запрос
$object = array();
$object['title'] = $title;
$object['content'] = $content;
$this->msql->Insert('articles', $object);
*/
return true;
}
The thing is...even if I comment everything from function "Add" and leave only "return true"... it wouldn't redirect me to index.php. Moreover, it doesn't even echo anything (even those "sd;fkfdsf.." string). The script just dies for some reason. I can't get where is the problem, can some1 explain to newbie what's the problem and how it should be fixed? If you need additional info, i'll provide it.
update: Maybe it's important...but if I delete those comment "/* */" things, it'd correctly add article to a DataBase. But then the script dies=/
update:
ok, now it says: "Notice: Undefined variable: result in Z:\home\myblog\www\c\M_MSQL.php on line 86"
here's my code for M_MSQL on line 86:
public function Insert($table, $object)
{
$columns = array();
$values = array();
foreach ($object as $key => $value)
{
$key = mysql_real_escape_string($key . '');
$columns[] = $key;
if ($value === null)
{
$values[] = "'$value'";
}
else
{
$value = mysql_real_escape_string($value . '');
$values[] = "'$value'";
}
}
$columns_s = implode(',', $columns);
$values_s = implode(',', $values);
$query = "INSERT INTO $table ($columns_s) VALUES ($values_s)";
$result = mysql_query($query);
if (!$result)
die(mysql_error());
return mysql_insert_id();
}
Reason is you are outputing things, so you have a notice : "Headers already sent".
If you remove the "echo" stuff, you'll be alright :
if ($add_article)
{
header('Location: /index.php?article_added=1');
}
I have been working on this problem for the last 2 days, searched over and over again .. nothing. Understanding that I am not an expert here - it's good! lol
I am trying to get the information found in the link below;
https://graph.facebook.com/570215713050551_4508656/comments/?fields=likes.fields(id,username,name,profile_type)
to then export into a csv.
Now I have current numerous other api tools, but this one has stumped me.
Basically, need to get the data foreach then run that again plus do the "next" paging etc.
Totally lost here.
My current code is here.
<?php
//Export and Download the Liker Data from each comment here ..
$id = $_GET['data'];
$commentor = $_GET['commentor'];
$toget = 'https://graph.facebook.com/'.$id.'/comments/?fields=likes.fields(id,username,name,profile_type)';
$data = #file_get_contents($toget);
$data = json_decode($data,true);
if($data['data'] == FALSE){
echo "gay!";
die;
}
$alldata = array();
function moredata($data){
global $alldata;
foreach ($data["data"] as $eachdata){
$onedata['id'] = $eachdata['id'];
foreach ($eachdata["likes"] as $ex){
$onedata['uid'] = $$ex['data'][0]['id'];
$onedata['name'] = $ex['data'][0]['name'];
$onedata['username'] = $ex['data'][0]['username'];
$onedata['profile_type'] = $ex['data'][0]['profile_type'];
//$onedata['link'] = $eachdata['link'];
}
$alldata[] = $onedata;
$onedata = array();
}
if (array_key_exists('next', $data['paging'])) {
$nextpagelink = $data['paging']['next'];
$nextdata = json_decode(file_get_contents($nextpagelink),true);
moredata($nextdata);
}
}
moredata($data);
... ETC ETC to get out the csv
Any help here would be amazing! Thanks guys.
It was little tricky but can be solved the issue with nested recursion.
I have tried your code and made few changes and it worked. Check the code below
$alldata = array();
$arrlikedata = array();
function moredata($data){
global $alldata;
global $arrlikedata;
foreach ($data["data"] as $eachdata)
{
$onedata['id'] = $eachdata['id'];
if(isset($eachdata["likes"])){
$onedata['likes'] = more_like_data($eachdata["likes"]);
}
else{
$onedata['likes'] = array();
}
$alldata[] = $onedata;
$arrlikedata = array();
}
if (array_key_exists('next', $data['paging'])) {
$nextpagelink = $data['paging']['next'];
$nextdata = json_decode(file_get_contents($nextpagelink),true);
moredata($nextdata);
}
}
function more_like_data($likedata)
{ global $alldata;
global $arrlikedata;
if(isset($likedata["data"])){
foreach ($likedata["data"] as $ex){
if(isset($ex)){
$onedata1['uid'] = $ex['id'];
$onedata1['name'] = $ex['name'];
$onedata1['username'] = (isset($ex['username']))?$ex['username']:'';
$onedata1['profile_type'] = $ex['profile_type'];
$arrlikedata[] = $onedata1;
$onedata1 = array();
}
}
}
if(isset($likedata['paging'])){
if (array_key_exists('next', $likedata['paging']))
{
$nextpagelink = $likedata['paging']['next'];
$nextlikedata = json_decode(file_get_contents($nextpagelink),true);
return more_like_data($nextlikedata);
}
else{
return $arrlikedata;
}
}
else{
return $arrlikedata;
}
}
moredata($data);
print "<pre>";
print_r($alldata);
print "</pre>";
Having some trouble with the following code. I've created a class to manage the DB connection, using what you see below as queryPreparedQuery and works fine when getting data for a single user, or any data that returns a single result using something like this...
include 'stuff/class_stuff.php';
function SweetStuff() {
$foo = new db_connection();
$foo->queryPreparedQuery("SELECT Bacon, Eggs, Coffee FROM Necessary_Items WHERE Available = ?",$bool);
$bar = $foo->Load();
$stuff = 'Brand of Pork is '.$bar['Bacon'].' combined with '.$bar['Eggs'].' eggs and '.$bar['Coffee'].' nectar for energy and heart failure.';
return $stuff;
}
echo SweetStuff();
Problem is, I want to build the functionality in here to allow for a MySQL query which returns multiple results. What am I missing? I know it's staring me right in the face...
class db_connection
{
private $conn;
private $stmt;
private $result;
#Build a mysql connection
public function __construct($host="HOST", $user="USER", $pass="PASS", $db="DB_NAME")
{
$this->conn = new mysqli($host, $user, $pass, $db);
if(mysqli_connect_errno())
{
echo("Database connect Error : "
. mysqli_connect_error());
}
}
#return the connected connection
public function getConnect()
{
return $this->conn;
}
#execute a prepared query without selecting
public function execPreparedQuery($query, $params_r)
{
$stmt = $this->conn->stmt_init();
if (!$stmt->prepare($query))
{
echo("Error in $statement when preparing: "
. mysqli_error($this->conn));
return 0;
}
$types = '';
$values = '';
$index = 0;
if(!is_array($params_r))
$params_r = array($params_r);
$bindParam = '$stmt->bind_param("';
foreach($params_r as $param)
{
if (is_numeric($param)) {
$types.="i";
}
elseif (is_float($param)) {
$types.="d";
}else{
$types.="s";
}
$values .= '$params_r[' . $index . '],';
$index++;
}
$values = rtrim($values, ',');
$bindParam .= $types . '", ' . $values . ');';
if (strlen($types) > 0)
{
//for debug
//if(strpos($query, "INSERT") > 0)
//var_dump($params_r);
eval($bindParam);
}
$stmt->execute();
return $stmt;
}
#execute a prepared query
public function queryPreparedQuery($query, $params_r)
{
$this->stmt = $this->execPreparedQuery($query, $params_r);
$this->stmt->store_result();
$meta = $this->stmt->result_metadata();
$bindResult = '$this->stmt->bind_result(';
while ($columnName = $meta->fetch_field()) {
$bindResult .= '$this->result["'.$columnName->name.'"],';
}
$bindResult = rtrim($bindResult, ',') . ');';
eval($bindResult);
}
#Load result
public function Load(&$result = null)
{
if (func_num_args() == 0)
{
$this->stmt->fetch();
return $this->result;
}
else
{
$res = $this->stmt->fetch();
$result = $this->result;
return $res;
}
}
#Load result
public function Execute(&$result = null)
{
if (func_num_args() == 0)
{
$this->stmt->fetch_array();
return $this->result;
}
else
{
$res = $this->stmt->fetch_array();
$result = $this->result;
return $res;
}
}
private function bindParameters(&$obj, &$bind_params_r)
{
call_user_func_array(array($obj, "bind_param"), $bind_params_r);
}
}
UPDATE
Got this to work with Patrick's help. Was able to find the following code with the help of this question, and with a few tweaks, it works beautifully. Added the following after the execute() statement in ExecPreparedQuery, returning an array at the very end instead of the single result:
# these lines of code below return multi-dimentional/ nested array, similar to mysqli::fetch_all()
$stmt->store_result();
$variables = array();
$data = array();
$meta = $stmt->result_metadata();
while($field = $meta->fetch_field())
$variables[] = &$data[$field->name]; // pass by reference
call_user_func_array(array($stmt, 'bind_result'), $variables);
$i=0;
while($stmt->fetch())
{
$array[$i] = array();
foreach($data as $k=>$v)
$array[$i][$k] = $v;
$i++;
}
# close statement
$stmt->close();
return $array;
As a result of the altered code, I changed the call to interpret multidimensional array data rather than a single result, of course. Thanks again!
In your Execute function you are calling $this->stmt>fetch_array().
That function only returns an array of a single row of the result set.
You probably want:
$this->stmt->fetch_all()
Update
To retrieve the entire result set from a prepared statement:
$this->stmt->store_result()
i want to fetch titles and title's tags.
public function titles()
{
$query=mysql_query("SELECT * FROM title");
while($row = mysql_fetch_object($query)){
$data->title[] = $row;
$data->tag[] = $this->tags($row->id);
}
return $data;
}
public function tags($title_id)
{
$query=mysql_query("SELECT * FROM tag WHERE title_id = '$title_id'");
while($row = mysql_fetch_object($query)){
$tag[] = $row;
}
return $tag;
}
I'm trying to print in this way
$data = titles();
foreach($data->title as $title)
{
echo $title->topic;
foreach($data->tag as $tag)
{
echo $tag->name;
}
}
but it doesnt work. How can I do?
thank you for help.
You should have something like this in your titles method
$data = new stdClass();
$data->title = array();
$data->tag = array();
You also need to add files like this
$data->title[$row->id][] = $row;
$data->tag[$row->id][] = $this->tags($row->id);
Then you can loop like this
foreach($data->title as $id => $title)
{
echo $title->topic;
foreach($data->tag[$id] as $tag)
{
echo $tag->name;
}
}
Also Enable error so that you can see PHP Errors .. at on top of your page
error_reporting(E_ALL);
ini_set("display_errors","On");
PHP DOC ON mysql_***
Use of this extension is discouraged. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include
What i think your code should look like
class Somthing {
private $db;
function __construct() {
$this->db = new mysqli("localhost", "user", "password", "db");
}
function titles() {
$data = new stdClass();
$data->title = array();
$data->tag = array();
$result = $this->db->query("SELECT * FROM title");
while ( $row = $result->fetch_object() ) {
$data->title[$row->id] = $row;
$data->tag[$row->id] = $this->tags($row->id);
}
return $data;
}
function tags($title_id) {
$tag = array();
$result = $this->db->query("SELECT * FROM tag WHERE title_id = '$title_id'");
while ( $row = $result->fetch_object() ) {
$tag[] = $row;
}
return $tag;
}
}
$somthing = new Somthing();
foreach ($somthing->titles() as $id => $title ) {
echo $title->topic;
foreach ( $data->tag[$id] as $tag ) {
echo $tag->name;
}
}
I'm using drupal's NAT module and need to get the nid from the term id.
Here's what I tried:
foreach ( (array)nat_get_nids($termid) as $natid ) {
$NatName = $natid->name;
}
print $natid;
This does not work.
Node auto term's get nid function is like this:
function nat_get_nids($tids, $get_nodes = FALSE) {
static $nid_cache = NULL;
static $node_cache = NULL;
$return = array();
// Keep processing to a minimum for empty tid arrays.
if (!empty($tids)) {
// Sort tid array to ensure that the cache_string never suffers from order
// issues.
sort($tids);
$cache_string = implode('+', $tids);
if ($get_nodes) {
if (isset($node_cache[$cache_string])) {
return $node_cache[$cache_string];
}
elseif (isset($nid_cache[$cache_string])) {
// If the nid cache stores the same string, node_load() each nid and
// return them.
$return = array();
foreach (array_keys($nid_cache[$cache_string]) as $nid) {
$return[$nid] = node_load($nid);
}
$node_cache[$cache_string] = $return;
return $return;
}
}
else {
if (isset($nid_cache[$cache_string])) {
return $nid_cache[$cache_string];
}
elseif (isset($node_cache[$cache_string])) {
// If the node cache stores the same string, retrieve only the nids and
// return them.
foreach ($node_cache[$cache_string] as $nid => $node) {
$return[$nid] = $node->name;
}
// Cache extracted results.
$nid_cache[$cache_string] = $return;
return $return;
}
}
// Results have not been cached.
$tids = implode(', ', $tids);
$result = db_query("SELECT n.nid, t.name FROM {nat} n INNER JOIN {term_data} t USING (tid) WHERE n.tid IN (". db_placeholders($tids) .")", $tids);
while ($node = db_fetch_object($result)) {
if ($get_nodes) {
$return[$node->nid] = node_load($node->nid);
}
else {
$return[$node->nid] = $node->name;
}
}
if ($get_nodes) {
$node_cache[$cache_string] = $return;
}
else {
$nid_cache[$cache_string] = $return;
}
}
return $return;
}
Thanks in advance!
Edit: Try based on the first answer:
foreach (nat_get_nids($termid) as $nid => $node_name) {
}
print $node_name;
It looks like nat_get_nids is returning an associative array, so your for loop should look like
foreach (nat_get_nids($termid) as $nid => $node_name) {
...
}
$nids = nat_get_nids(array($termid));