postgresql help with php loop - php

I keep getting an "Notice: Undefined index: did" error with this query, and I'm not understanding why... I'm much more used to mysql, so, maybe the syntax is wrong?
This is the php query code:
function get_demos() {
global $session;
$demo = array();
$result = pg_query("SELECT DISTINCT(did,vid,iid,value) FROM dv");
if(pg_num_rows($result) > 0) {
while($r = pg_fetch_array($result)) {
switch($r['did']) {
case 1:
$demo['a'][$r['vid']] = $r['value'];
break;
case 2:
$demo['b'][$r['vid']] = $r['value'];
break;
case 3:
$demo['c'][$r['vid']] = $r['value'];
break;
}
}
} else {
$session->session_setMessage(2);
}
return $demo;
}
When I run that query at the pg prompt, I get results:
"(1,1,1,"A")"
"(1,2,2,"B")"
"(1,3,3,"C")"
"(1,4,4,"D")"
"(1,5,5,"E")"
"(1,6,6,"F")"
"(1,7,7,"G")"
"(1,8,8,"H")"
"(1,9,9,"I")"
"(1,10,A,"J")"
"(1,11,B,"K")"
"(1,12,C,"L")"
"(1,13,D,"M")"
"(2,14,1,"A")"
"(2,15,2,"B")"
"(2,16,0,"C")"
"(3,17,1,"A")"
"(3,18,2,"B")"
"(3,19,3,"C")"
"(3,20,4,"D")"
"(3,21,5,"E")"
"(3,22,6,"F")"
"(3,23,7,"G")"

You must use pg_fetch_assoc() function if you want to get associative array in $r.

Related

PHP Fatal Error Cannot Use String Offset As Array

I keep getting a fatal error when a script is ran on my php server,
This web app was built ten years ago and I am currently clearing errors so we can start updating it. Current version PHP 5.2.17
Fatal error: Cannot use string offset as an array in /home/user/public_html/admin/script.php on line 1418
This is the line the error is on,
$name = $d["#"]["_Name"];
This is the full function,
if (isset($b["_BORROWER"]["EMPLOYER"])) {
if (!isset($b["_BORROWER"]["EMPLOYER"][0])) {
$temp = $b["_BORROWER"]["EMPLOYER"];
unset($b["_BORROWER"]["EMPLOYER"]);
$b["_BORROWER"]["EMPLOYER"][0] = $temp;
}
foreach($b["_BORROWER"]["EMPLOYER"] as $c => $d) {
$pid = '0';
// Finish up.
$item["type"] = "Personal";
$name = $d["#"]["_Name"];
//check for files in other bureaus
$query = doquery("SELECT name,id FROM <<myitems>> WHERE cid='".$client["id"]."' AND type='Personal'");
$results = dorow($query);
if($results){
if(isset($results['name'])){
$temp = $results;
unset($results);
$results[0] = array($temp);
}
foreach($results as $c){
if(isset($c['name'])){
if($address == decrypt_string($c['name'])) {
$pid = $c['id'];
break;
};
}
}
}
Does anyone understand what is triggering this error and how to fix it?
You can use isset() to check the array value exists or not like,
$name = isset($d["#"]["_Name"]) ? $d["#"]["_Name"] : "";

class definative commands out of sync solution

After about a week search I seem to find no conclusive / efficient / upto date / standard way of doing this.
The obvious solution is to run a query get the result into a variable and clear down ready for the next query - for efficiency NOT closing the connection.
This is being done in a wrapper class which has select / update / insert which in turn call a query or queries (for mysqli multi_query() ) so ideally it would be good to clear any result prior to next within query / queries to ensure it runs with no concern of what has gone before.
This does not seem possible as some solutions need a result set.
Currently the select / update / insert call:
private function queryclearup($dataresource) {
//clear up if required
switch ($this->dbtype) {
case "mysqli":
#mysqli_next_result($this->connection);
#mysqli_free_result($dataresource); //clear result to avoid out of sync issues
break;
}
}
after dealing with the result set - for example converting to a data array in the case of select, or just logging an error in the case of update / insert.
Still this problem persists with some (update), but not others (select / insert).
public function select($query, $args = array()) {
$this->loghelper->write("SQL Select\n" . $query);
$args = _PHP::array_defaults($args, array(
"pk" => null
));
$data_table = array();
$errors = null;
$query = utf8_decode($query);
switch ($this->dbtype) {
case "mysqli":
$dbdata = $this->query($query);
$data_table = $this->resourceToDataTable($dbdata, $args);
break;
}
return $data_table;
}
Then
private function resourceToDataTable($dataresource, $args = array()) {
$data_table = array();
if (gettype($dataresource) == "resource" || gettype($dataresource) == "object") {
do {
switch ($this->dbtype) {
case "mysqli":
$row = $dataresource->fetch_assoc();
break;
}
if ($row) {
array_push($data_table, $row);
}
} while ($row);
if (!empty($args["pk"])) {
$pktable = array();
foreach ($data_table as $d) {
if (!array_key_exists($args["pk"], $pktable)) {
$pktable[$d[$args["pk"]]] = $d;
}
}
$data_table = $pktable;
}
}
$this->queryclearup($dataresource);
return $data_table;
}
This appears to be whats required
private function queryclearup($dataresource) {
//clear up if required
switch ($this->db["contype"]) {
case "mysqli":
while ($dump = #mysqli_next_result($this->connection)) {
$donothing = 1;
}
#mysqli_free_result($dataresource); //clear result to avoid out of sync issues
break;
}
}

Query not assigned into the variable / Not going into the condition

I was doing this code for my project and it seems that I can't get the values of the query into $currentRow. All that saved into the variable $currentrow is 22 which is the number rows in the database. I want to have access to all the query results. Please help. Here's the code.
public function getBSIConfig(){
$conn = oci_connect("472proj","system","//localhost/XE");
$sql = oci_parse($conn,"SELECT conf_id, conf_key, conf_value FROM bsi_configure");
oci_execute($sql);
echo "0";
while($currentRow = oci_fetch_all($sql,$res)){
echo "1.5";
echo $currentRow;
if($currentRow["conf_key"]){
echo "1";
if($currentRow["conf_value"]){
$this->config[trim($currentRow["conf_key"])] = trim($currentRow["conf_value"]);
echo "2";
}else{
$this->config[trim($currentRow["conf_key"])] = false;
echo "3";
}
}
}
}
And the output is only:
0
1.5
22
The results from this function are stored in the 2nd argument, rather than returned directly. See if this works for you:
$results = array();
$numResults = oci_fetch_all($sql, $results);
foreach ($results as $result) {
if ($result["conf_key"]) {
// etc ...
}
}
Read this http://php.net/manual/en/function.oci-fetch-all.php , you might get an idea what's wrong.

mysqli_num_rows from class function error

This is the first time I learn class in PHP, I tried to make a simple search in database.
here is some script from my class:
class DB {
...
function list_query($query) {
$ns = array();
$q = mysqli_query($this->con_(), $query);
while($n = mysqli_fetch_assoc($q)) {
$ns[] = $n;
}
return $ns;
}
...
function num_query($q) {
$num = mysqli_num_rows($q);
return $num;
}
...
}
search script :
$key = "foo";
$qsearch = $db->list_query("SELECT * FROM posts WHERE content LIKE '%".$db->escape_query($key)."%'");
$num = $db->num_query($qsearch);
if ($num == 0) {
echo "<h2>not found</h2>";
} else {
echo "<h2>result for : ".$key."</h2>";
foreach($qsearch as $val) {
echo "<h4>".$val['title']."</h2>";
echo strip_tags($val['content']);
}
}
but there is an error with the num_query() function.
with warning :
Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, array given in class/db.php on line 30.
I have checked it with manual mysqli_query() then use the num_query() function, it's work well.
sorry for my english
Your list_query() returns array. And your num_query expects mysqli_result as a parameter.
So, when you write $qsearch = $db->list_query(), you're getting an array; and then you pass that array to num_query.
Perhaps, your num_query should be like:
function num_query($result) {
return count($result);
}

php - return variable from function

I am trying to return a variable from a function. I have the function below, which inserts a postid to the database. I need the postid's value returned to another page.
forum.php - Where the function is.
function newTopic(){
// Get the POST data
global $ir;
$postid = mysql_insert_id();
mysql_query("UPDATE forum_topics SET post_id='$postid' WHERE topic_id='$topicid'");
// No error found and the update was succesful - Return success!
return 100;
return $postid;
}
newtopic.php - Where I need the $postid variable.
if($_POST)
{
$newTopic = $forum->newTopic();
/*
* Return codes:
* 100: Success
*/
switch($newTopic)
{
//If no error = success.
case 100:
$success = 'You have successfully created the topic.';
$issuccess = 1;
$stop = true;
break;
}
$checkerror = $error;
$checksuccess = $success;
}
if($checksuccess){
$contents.="
".alert("success","$success")."";
refresh("3","/forum/t$id-$postid");
}
As you can see, I am trying to use $postid variable from the function newTopic(). Although, the $postid variable is empty.
How can I get the value from the function newTopic.php located in forum.php, to newtopic.php?
When you have used
return 100;
your code will never see
return $postid;
You can use this code to return
return array("code"=>"100","postid"=>$postid);
Now in new_topic.php use the code as shown
if($_POST)
{
$newTopic = $forum->newTopic();
/*
* Return codes:
* 100: Success
*/
switch($newTopic['code'])
{
//If no error = success.
case 100:
$success = 'You have successfully created the topic.';
$issuccess = 1;
$stop = true;
break;
}
$checkerror = $error;
$checksuccess = $success;
}
if($checksuccess){
$contents.="
".alert("success","$success")."";
refresh("3","/forum/t$id-$newTopic['postid']");
}
Your code looks that is returning value 100 before returning $postid variable.
That's wrong.Your code will exit the function at first return.
comment the line "//return 100;"
OR return an array. You cannot return two values like u do.
Instead of doing
return 100;
return $postid;
Do
//return 100;
return array("successs"=>100,"id"=>$postid);
Then use your $newTopic variable as folows:
In switch:
switch($newTopic['success'])
Use the postId anywhere else
$newTopic['id']
try with reference like in the below code
function newTopic(&$postid){
// Get the POST data
global $ir;
$postid = mysql_insert_id();
mysql_query("UPDATE forum_topics SET post_id='$postid' WHERE topic_id='$topicid'");
// No error found and the update was succesful - Return success!
return 100;
}
....... //some codes
$postid = null;
newTopic($postid);
$my_postId = $postid; //Now you have your post ID
OR in you exists code like
if($_POST)
{
$last_postid = null;
$newTopic = $forum->newTopic($last_postid );
/*
* Return codes:
* 100: Success
*/
switch($newTopic)
{
//If no error = success.
case 100:
$success = 'You have successfully created the topic.';
$issuccess = 1;
$stop = true;
$postid = $last_postid;
break;
}
$checkerror = $error;
$checksuccess = $success;
}
if($checksuccess){
$contents.="
".alert("success","$success")."";
refresh("3","/forum/t$id-$postid");
}
EDIT: Call-time pass-by-reference fixed.
If you want to return two values you can not just write two returns.
There are several options to return more values. One is using an array:
return array(100, $postId);
and
list($status, $postId) = $forum->newTopic();
You can also use an associatve array as s.d suggested.
However, as your one variable only contains the status you can also use exceptions in the case the operation fails.

Categories