PHP Foreach with mysql_fetch_array server status - php

Im trying to create a cronjob script, which checks the status of a few servers.
Somehow it only uses the first ip in my table.
$aQ = db::aQuery("SELECT hostIp FROM `gh_server_hosts`");
$a = mysql_fetch_array($aQ);
foreach ($a as $value) {
$timeout = "10";
$ssh= #fsockopen("$value","22",$timeout);
if($ssh) {
$status = 1;
}
else {
$status = 0;
}
$time = time();
if(db::aQuery("UPDATE `gh_server_hosts` SET hostLastScanned='".$time."', hostLastStatus='".$status."' WHERE hostIp = '".$value."'")) {
echo "scanned";
} else {
echo "error";
}
}

You have to put mysql_fetch_array in loop to get all records like this:
$aQ = db::aQuery("SELECT hostIp FROM `gh_server_hosts`");
while ($value = mysql_fetch_assoc($aQ)) {
$timeout = "10";
$ssh= #fsockopen($value['hostIp'],"22",$timeout);
// Rest of your code
}
I have used mysql_fetch_assoc instead of mysql_fetch_array to limit the output array. Also, as mentioned by others mysql_* functions are deprecated so kindly update your code before running this code on PHP 5.5+...

mysql_fetch_assoc() will work instead of mysql_fetch_array() but do note about the deprecation warning with mysql. (Aside from the security concerns, your code will fail if PHP is upgraded to 7.0).

Related

Can I fetch multiple different SQL statements in one times loop? in PHP

I have to query SQL-SERVER's Query and MYSQL's Query (That have the same result format but it's difference database)
, But I want to call them in one while loop in PHP, Can I do that?
Ex.
$mssql_query = mssql_query(..mssql..);
$mysql_query = mysql_query(..mysql..);
while( $mssql_rs = mssql_fetch_assoc($mssql_query)|| $mysql_sql = mysql_fetch_assoc($mysql_query) )
{
..some action..
}
EDITED :
I just have an solved answer. It's work for me Idea from #Drew while(bContinue)
this my code
$mssql_query = mssql_query(..mssql..);
$mysql_query = mysql_query(..mysql..);
$continue = true;
while( $continue ){
$ms_rs = mssql_fetch_assoc($mssql_query);
$my_rs = mysql_fetch_assoc($mysql_query);
if($ms_rs){ ..some action.. }
if($my_rs ){ ..some action.. }
$continue = $ms_rs|| $my_rs;
}
Thank you for all ideas.
You can shoot in the dark and try to use both data_seek flavors of each, if they have both the same number of rows and same column names.
Here's the idea / here's some pseudo code too (untested of course):
$mssql_query = mssql_query(< the mssql query statement >);
$mysql_query = mysql_query(< the mysql query statement >);
$ms_num_rows = mssql_num_rows($mssql_query);
$my_num_rows = mssql_num_rows($mysql_query);
if($ms_num_rows === $my_num_rows) { // same number of rows on both result sets
for($i = 0; $i < $my_num_rows; $i++) {
mssql_data_seek($mssql_query, $i);
mysql_data_seek($mysql_query, $i);
$ms_row = mysql_fetch_assoc($mssql_query);
$my_row = mysql_fetch_assoc($mysql_query);
echo $ms_row['same_field_1'];
echo $my_row['same_field_1'];
// and others
}
}
Note: Of course you might get deprecation warnings for using these functions, most likely these functions have their PDO counterparts and you could port them into using those instead.
Manual entries:
http://php.net/manual/en/function.mssql-data-seek.php
http://php.net/manual/en/function.mysql-data-seek.php
I just had an answer. It's working for me
Idea from #Drew while($continue)
Here is my code
$mssql_query = mssql_query(..mssql..);
$mysql_query = mysql_query(..mysql..);
$continue = true;
while( $continue )
{
$ms_rs = mssql_fetch_assoc($mssql_query);
$my_rs = mysql_fetch_assoc($mysql_query);
if($ms_rs){ ..some action.. }
if($my_rs ){ ..some action.. }
$continue = $ms_rs|| $my_rs;
}
Thank you for all the ideas.

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"] : "";

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.

Using mysql_fetch_array multiple times PHP

When I'm trying to use the if statement below it wont work. Can I somehow compare the data I fetch in the mysql_fetch functions?
if (mysql_num_rows($select_projects) > 0) {
while($all_objects = mysql_fetch_array($select_projects)) {
if($all_objects['Team'] !== ""){
$current_team == $all_objects['Team'];
echo '<tr id="'.$all_objects['Team'].'"> <td>'.$all_objects['Team'].'</td><td>';
while($test = mysql_fetch_array($select_projects)){
if($test['PlannedSprint'] == "544" and $all_objects['Team'] == $test['Team']){ // problem whit the last part of the ifstatement. it is never true.
echo 'Testtest'.$all_objects['Team'].'</br>';
}
}
echo '</td></tr>';
echo '';
array_push($team, $all_objects['Team']);
//}
}
}
}
You're popping two items off the return stack
while($all_objects = mysql_fetch_array($select_projects))
And
while($test = mysql_fetch_array($select_projects))
So you're pulling the first record off into $all_objects and then looping through the rest in $test.
You also need to stop using mysql_ functions as they are deprecated

Baffled as to why PHP is giving simple logic error on if statement

Like the title says, PHP is really confusing me on a simple if comparison statement that's returning the opposite of what it should be returning. I'm trying to compare 2 datetime's that are first converted to strings:
//Fetched db query, this returns 2012-06-23 16:00:00
$databaseDateTime = strtotime($row['time']);
//This now returns 1340481600
//today's date and time I'm comparing to, this returns 2012-06-22 17:14:46
$todaysDateTime = strtotime(date("Y-m-d H:i:s"));
//this now returns 1340399686
Great, everything works perfect so far. Now here's where things get hairy:
if ($databaseDateTime < $todaysDateTime) { $eventType = 'past'; }
And this returns 'past', which of course it shouldn't. Please tell me I'm missing something. My project kind of depends on this functionality being airtight.
**EDIT***
Thanks guys for taking the time to help me out. Let me post the entire code because a few of you need more context. The request is coming from an IOS5 to my backend code and json is being sent back to the phone.
<?php
//all included files including $link to mysqli_db and function sendResponse()
function getEvents($eventType, $eventArray) {
global $link;
global $result;
global $i;
global $todaysDateTime;
foreach ($eventArray as $key => $value) {
$sqlGetDeal = mysqli_query($link, "SELECT time FROM deals WHERE id='$value' AND active='y' LIMIT 1") or die ("Sorry there has been an error!");
while ($row = mysqli_fetch_array($sqlGetDeal)) {
//compare times to check if event already happened
$databaseDateTime = strtotime($row['time']);
if ($databaseDateTime < $todaysDateTime) { $eventType = 'past'; }
$result[$i] = array(
'whenDeal' => $eventType,
'time' => $databaseDateTime,
);
$i++;
}//end while
}//end foreach
}
if (isset($_GET['my'])) {
//$_GET['my'] comes in as a string of numbers separated by commas e.g. 3,2,6,3
$myDeals = preg_replace('#[^0-9,]#', '', $_GET['my']);
$todaysDateTime = strtotime(date("Y-m-d H:i:s"));
$result = array();
$kaboomMy = explode(",", $myDeals);
$i = 1;
if ($myEvents != "") {
getEvents('future', $kaboomMy);
}//end if
sendResponse(200, json_encode($result));
} else {
sendResponse(400, 'Invalid request');
} //end $_POST isset
?>
Found a quick hack around the issue. I just added a local variable to my function and rearranged my compare statement
//added local variable $eventTyppe to function
$eventTyppe;
changed compare from:
if ($databaseDateTime < $todaysDateTime) { $eventType = 'past'; }
to:
if ($todaysDateTime < $databaseDateTime ) {
$eventTyppe = $eventType;
} else {
$eventTyppe = 'past';
}
Notice if I rearrange compare:
if ($databaseDateTime < $todaysDateTime ) {
$eventTyppe = 'past';
} else {
$eventTyppe = $eventType;
}
I still get the same error. This is the weirdest thing I've ever seen and the first PHP bug I've run into (I'm assuming it's a PHP bug).
Could you print the values of the times right before this line?
if ($databaseDateTime < $todaysDateTime) { $eventType = 'past'; }
Since that one is declared as global I'm wondering if is it coming back incorrectly.

Categories