Create one instance of an array whilst in a foreach loop - php

I have myself in a unique situation here and I am not sure if this is the correct way to go about it; I am open to suggestions.
I have a function in which it grabs all of the table names in a database and stores them into an array. Next newly parsed items ($id) are passed against this table name array and any matches are unset from this array. This leaves me with the leftovers which are items that have been discontinued.
Code below:
function itemDiscontinued($dbh, $id, $detail) {
try {
$tableList = array();
$result = $dbh->query("SHOW TABLES");
while ($row = $result->fetch()) {
$tableList[] = $row[0];
}
$key = array_search($id, $tableList);
unset($tableList[$key]);
print_r($tableList);
}
catch (PDOException $e) {
echo $e->getMessage();
}
}
The problem is that the array $tablelist keeps recreating itself due to the function being in a foreach loop (Parsing process). I only require one instance of it to work with once it is created. I apologise before hand if the problem is a bit hard to understand.

Yea, it's really hard to understand. Maybe you'll try this:
function itemDiscontinued($dbh, $id, $detail) {
static $tables = array();
if (!$tables) {
$tables = getTableList($dbh);
}
$key = array_search($id, $tables);
unset($tables[$key]);
print_r($tables);
}
function getTableList($dbh) {
try {
$tableList = array();
$result = $dbh->query("SHOW TABLES");
while ($row = $result->fetch()) {
$tableList[] = $row[0];
}
return $tableList;
} catch (PDOException $e) {
echo $e->getMessage();
}
}

how about an array_push with an extra parameter
function itemDiscontinued($dbh, $id, $detail, $outputArray) {
try {
$result = $dbh->query("SHOW TABLES");
while ($row = $result->fetch()) {
array_push($outputArray, $row[0]);
}
$key = array_search($id, $outputArray);
unset($outputArray[$key]);
return $outputArray; // use this for subsequent run on the foreach statment
}
catch (PDOException $e) {
echo $e->getMessage();
}
}

Related

PHP, not display all inside my array, but only first resulting

$projects = array('1' => $link1, '2' => $link2);
function server_status($projects) {
foreach ($projects as $server) {
$api_status = ping_api($server);
if ($api_status == 1) {
$json = json_decode(file_get_contents($server), true);
foreach ($json as $obj) {
if ($obj['online'] < 1) {
// OFFLINE
return -1;
}
else {
// ONLINE
return $obj['online'];
}
}
} else {
// MAINTENANCE
return 0;
}
}
}
function cache_status($data) {
echo $data;
$servername = "localhost";
$username = "root";
$password = "";
try {
$conn = new PDO("mysql:host=$servername;dbname=test", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
foreach ($data as $status) {
// server id + status
$sql = "UPDATE projects SET status=:status WHERE id=:server_id";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':status', $status, PDO::PARAM_INT);
$stmt->bindParam(':server_id', 1, PDO::PARAM_INT);
$stmt->execute();
}
}
$problem = array(server_status($projects));
print_r($problem);
My problem is, when I print_r the variable $problem it should return two results in array, since there are two results but it only returning the first result from array as an .. example: Array ( [0] => 260 )
IF anyone is kind enough to look at my code and tell me what I am doing wrong, I would be very greatful
You are using return statement inside your loop that is why it breaks your loop on first iteration and returns what ever you have mentioned to the original call of function. To resolve this issue you need to collect the response from each iteration in array and in the end of function return your response for each iteration something like
function server_status($projects) {
$response= array();
$status = 0; // default status
foreach ($projects as $server) {
$api_status = ping_api($server);
if ($api_status == 1) {
$json = json_decode(file_get_contents($server), true);
foreach ($json as $obj) {
if ($obj['online'] < 1) {
// OFFLINE
$status= -1;
}
else {
// ONLINE
$status = $obj['online'];
}
}
}
$response[] = array('server'=>$server,'status'=>$status);
}
return $response;
}

Issue Undefined variable after storing mysql query into a php variable

I have an issue on my php script. I am trying to store mysql query into a php variable and then I convert the result to string. It seems doing the job in the loop but at the end of my script, I have an error:
Internal Error -
Notice:Undefined variable: result
I want to pass the whole content of the variable $data.
Do you know what i am doing wrong?
Here my php script:
<?php
if (isset($_GET['data']) && $_GET['data']) {
$SelectDataFromRunTable="Select Reference, Variant, HGVSVar FROM run29012016";
$QueryResult=mysqli_query($conn,$SelectDataFromRunTable);
while($data = mysqli_fetch_array($QueryResult,MYSQLI_BOTH)){
print_r($data);
$data=implode(" ",$data);
}//end of while
$NameChecker='astringtest';
$options = array('features' => SOAP_SINGLE_ELEMENT_ARRAYS);
$client = new SoapClient($URL, $options);
try {
$result = $client->submitBatchJob(array('data'=>$data, 'process'=>$NameChecker))
->submitBatchJobResult;
} catch (Exception $e) {
echo $e->getMessage();
}
print_r($result);
mysqli_close($conn);
}
?>
while($data = mysqli_fetch_array($QueryResult,MYSQLI_BOTH)){
$data = implode(" ",$data);
}
This can not work, as you overriding $data with every loop:
while($data = mysqli_fetch_array(...)) will evaluate as many times you have rows in your dataset, till the end. The last assignmet is $data = null (e.g. when you reached the end of you result set) and you are going out of the while-loop.
What you can do is, store you data into another variable, like
$soap_data = "";
while($data = mysqli_fetch_array($QueryResult,MYSQLI_BOTH)){
$soap_data .= " " . implode(" ",$data);
}
//...
$result = $client->submitBatchJob(array('data'=>$soap_data, 'process'=>$NameChecker))
->submitBatchJobResult;
Also, what devpro said, it is always better to include a default for variables.
You need to define $result in default at top level like:
<?php
if (isset($_GET['data']) && $_GET['data'])
{
$result = array(); // ADD THIS
$SelectDataFromRunTable="Select Reference, Variant, HGVSVar FROM run29012016";
$QueryResult=mysqli_query($conn,$SelectDataFromRunTable);
while($data = mysqli_fetch_array($QueryResult,MYSQLI_BOTH))
{
print_r($data);
$data=implode(" ",$data);
}//end of while
$NameChecker='astringtest';
$options = array('features' => SOAP_SINGLE_ELEMENT_ARRAYS);
$client = new SoapClient($URL, $options);
try
{
$result = $client->submitBatchJob(array('data'=>$data, 'process'=>$NameChecker))
->submitBatchJobResult;
}
catch (Exception $e)
{
echo $e->getMessage();
}
print_r($result);
mysqli_close($conn);
}
?>
What i have changed?
I am adding $result = array(); in default.
You are trying to access $result outside where this var was defined.
try this:
try {
$result = $client->submitBatchJob(array('data'=>$data, 'process'=>$NameChecker))
->submitBatchJobResult;
print_r($result);
} catch (Exception $e) {
echo $e->getMessage();
}

php pdo oop fetch data not working

Class PHP
<?php
class product extends db {
function viewCat(){
$dbcon = new db();
$connn = $dbcon->dbcon();
try {
$stmt = $connn->prepare("SELECT * FROM `cat`");
$resultcat = $stmt->execute();
return $resultcat;
} catch (PDOException $e) {
echo 'Error: ' . $e->getMessage();
}
}
}
?>
the view
<?php
$menu = new product();
$resultmenux = $menu->viewCat();
foreach ($resultcatx as $row) {
print_r($row);
}
?>
the error i get is
Warning: Invalid argument supplied for foreach()
in your class file it should be, as I commented you are not fetching the data
$stmt = $connn->prepare("SELECT * FROM `cat`");
$stmt->execute();
$resultcat = $stml->fetchAll(PDO::FETCH_ASSOC); // this line was missing
return $resultcat;
and in view file as answered by shankhan
$resultmenux = $menu->viewCat();
foreach ($resultmenux as $row) {
print_r($row);
}
It should be like this:
$resultmenux = $menu->viewCat();
foreach ($resultmenux as $row) {
print_r($row);
}

how to display multiple rows from mysql using php oop?

I'm a newbie in oop style. I start practicing it since last week and I make simple CRUD website. but i got a problem when i tried fetching rows from mysql db its always display 1 row.
my created a class named class.user.php
and it shows here:
include "db_config.php";
class User{
private $db;
public function __construct(){
$this->connect();
}
private function connect($db_connect=true){
if ($db_connect){
$this->db = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
if(mysqli_connect_errno()) {
printf("DB Connect failed: %s\n", mysqli_connect_error());
exit;
}
}
}
public function get_tutoriallist(){
$db = $this->db;
if(empty($db)){
$this->connect();
$db = $this->db;
}
try {
$stmt = $this->db->prepare('SELECT * FROM `topic`');
$stmt->execute();
$result = $stmt->get_result();
$dataArray = array();
while($row = $result->fetch_assoc()){
$count_row = $result->num_rows;
if ($count_row == 1) {
$dataArray[] = $row;
}
}
return ($dataArray);
mysqli_close($db);
$this->db = null;
} catch (Exception $e) {
echo $e->errorMessage();
}
}
}
and i call it using this:
$data = $user->get_tutoriallist();
if (!empty($data)) {
foreach ($data as $row){
echo "<tr>";
echo"<td>".$row['category']."</td>";
echo"<td>".$row['title']."</td>";
echo"<td>".$row['detail']."</td>";
echo"<td>".$row['photo']."</td>";
echo"<td>".$row['video_link']."</td>";
echo"<td>".$row['date_post']."</td>";
echo"<td class='option'><center><a href ='#' class='edit'>Edit</a>
<a href='#'>Delete</a></center></td>";
echo "</tr>";
}
}else{
echo '<tr><td colspan="6"><center><h2>No entries</h2></center></td></tr>';
}
I'm not quite sure what is going on here:
while($row = $result->fetch_assoc()){
$count_row = $result->num_rows;
if ($count_row == 1) {
$dataArray[] = $row;
}
But normally, you just iterate through the results and append them to an array:
while($row = $result->fetch_assoc()){
$dataArray[] = $row;
}
Then your $datArray has all the rows in it.
This is because you are appending to the result array only when $current_row == 1.
Try changing your while loop like this:
while($row = $result->fetch_assoc()){
$dataArray[] = $row;
}
Also, you are not closing the db connection correctly, you are mixing OOP style with procedural mysqli functions. This is how it should be:
$this->db->close();
$this->db = null;
Finally, you should return the data array after you closed the connection. If you returned the data array first and closed the connection after, that code wont get executed.
So your last three lines should look like this:
$this->db->close();
$this->db = null;
return $dataArray;

foreach is not working in php with pdo

I am using PDO with my PHP project and I don't know why this is not working. It is not showing any error.
I have a function to read data from a database:
function Read_post($con,$table,$limit=6){
try {
$query = "SELECT * FROM {$table} ORDER BY id DESC LIMIT {$limit}";
$stmt = $con->prepare( $query );
$stmt->execute();
return $stmt->fetch(PDO::FETCH_ASSOC);
} catch (Exception $e) {
return "ERROR". $e->getMessage();
}
}
and I use a foreach loop to display the data. But it is not showing anything:
<?php $posts = Read_post($con,"posts"); ?>
<?php foreach ($posts as $key) {
echo "something ";
echo $key["title"];
} ?>
It is not showing the other text as well like if i echo something else only text.
Inside your function Read_post, you have this line:
return $stmt->fetch(PDO::FETCH_ASSOC);
It will not return an array, it will return a PDO object. You can't iterate over a PDO object in the same way as an array. Try this:
$result = $stmt->fetch(PDO::FETCH_ASSOC);
return $result;
echo the $value of the array in foreach or var_dump($post) to check the array contains
something
<?php foreach ($posts as $value) {
echo "something ";
echo $value;
} ?>

Categories