$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;
}
Related
I have a method written in PHP PDO (5.6) that should return the last inserted id.
The issue is that the insertion is accomplished but it returns 0 "string".
There is a lot of posts here in stackoverflow with the same issue, but I could not find a solution for me.
What am I missing?
Here is the code:
public static function set_values(array $arrSql = NULL) {
try {
$fields="";
$bindParamStr = "";
$values = "";
foreach ($arrSql as $tableName => $arrSetValues) {
$table=$tableName; //Inside 1 table
foreach ($arrSetValues as $fieldName => $arrParam) {
$fields .= $fieldName.","; //Inside 1 field
$values .= "?,";
$bindParamStr[]=$arrParam;
}
}
self::$sql= "INSERT INTO $tableName (".rtrim($fields,",").") VALUES (".rtrim($values,",").")";
$stmt = self::$conn->prepare(self::$sql);
$i=1;
foreach ($bindParamStr as $bindPar) {
if(count($bindPar)==1){
$stmt->bindValue($i,$bindPar[0]);
}
else{
$stmt->bindValue($i,$bindPar[0],$bindPar[1]);
}
$i++;
}
self::$conn->beginTransaction();
if($stmt->execute()){
self::$conn->commit();
$id= self::$conn->lastInsertId();
return $id;
}
else{
return FALSE;
}
}
catch (PDOException $e) {
self::$arrCatchConnResult = self::saveLogMsg(["exceptionObjc"=>$e,"sql"=>self::$sql]);
$msg = self::$arrCatchConnResult["displayMsgHTML"];
self::$conn = null;
if (self::$die) {
die($msg);
}
}
}
Get the insert id before committing your transaction:
$id = self::$conn->lastInsertId();
self::$conn->commit();
http://www.php.net/manual/en/pdo.lastinsertid.php#85129
I have a database at local server. I am trying to access this database. I have table of venueTypeMaster in the database. I tried to get all the venuetypes from database. But when I run the script message I get is - 'No database selected'.
I have a class in which I have created two functions in php script. For createVenue it dose not send any message and the query has been executed successfully. But for getVeunueTypes it is showing this message. Connection for both is same.
DB Script:
<?php
include_once("config.php");
include_once("exceptions.php");
class DB {
static $con;
public static function getConnection() {
try {
if ( DB::$con == null ) {
DB::$con = mysqli_connect(DB_HOSTNAME, DB_USERNAME, DB_PASSWORD);
if ( DB::$con) {
$status = mysqli_select_db(DB::$con,DB_NAME);
if (! $status ) throw new DBSelectionExcpetion(mysqli_error());
return DB::$con;
} else {
$e = new DBConnectionException(mysqli_error());
throw $e;
}
}
return DB::$con;
} catch(DBConnectionException $e) {
throw $e;
} catch(DBSelectionExcpetion $de) {
throw $de;
}
return null;
}
?>
venueTypes script
<?php
include("exceptions.php");
include("DB.php");
include("config.php");
class VenueTypes {
public function getVenueTypes() {
try {
$con = DB::getConnection();
$query = "select * from venueTypeMaster";
$rs = mysql_query($query) or die (json_encode(array("result"=>-1, "message"=>mysql_error())));
$n = mysql_num_rows($rs);
$vt = array();
if ( $n > 0 ) {
while ( $row = mysql_fetch_assoc($rs)) {
$vt[] = $row;
}
$result = array("result"=>1, "message"=>"success", "venueTypes" => $vt);
return json_encode($result);
} else {
$result = array("result"=>-1, "message"=>"Venue types list is empty");
return json_encode($result);
}
} catch(DBConnectionException $e) {
$result = array("result"=>-1, "message"=> $e -> getMessage());
return json_encode($result);
}
return null;
}
public function createVenueType($fields) {
try {
$required = array("venuetype", "active", "entry_by", "entry_date", "entry_time", "last_modify_date", "ip_addr","venue_name");
$actual = array_keys($fields);
$intersection = array_intersect($required, $actual);
$n1 = sizeof($required);
$n2 = sizeof($intersection);
if ( $n1 != $n2 ) {
throw new MissingParameterException();
}
$con = DB::getConnection();
$keys = array_keys($fields);
$values = array_values($fields);
$columns = implode(",", $keys);
$n = sizeof($values);
for($i=0;$i<$n; $i++) {
$values[$i] = "'" . mysqli_real_escape_string($con,$values[$i]) . "'";
}
$columnValues = implode(",", $values);
$query = "insert into venuetypemaster($columns) values($columnValues)";
mysqli_query($con,$query) or die (json_encode(array("result"=>-1, "message"=>mysqli_error())));
$af = mysqli_affected_rows($con);
if ( $af == 1 ) {
$venuetypeId = mysqli_insert_id($con);
$result = array("result"=>1, "message"=>"success", "venuetypeId" => $venuetypeId);
return json_encode($result);
} else {
$result = array("result"=>-1, "message"=>"Failed to register");
return json_encode($result);
}
} catch(DBConnectionException $e) {
$result = array("result"=>-1, "message"=> $e -> getMessage());
return json_encode($result);
}
return null;
}
?>
getVenueType script
<?php
header("Content-type: application/json");
if ( $_SERVER['REQUEST_METHOD']=='GET') {
include_once ("../include/VenueTypes.php");
try {
$v = new VenueTypes();
$response = $v -> getVenueTypes();
//$response is null means something went wrong as a result we got null result from above statement
if ( $response == null ) {
$response = json_encode(array("result" => -2, "message" => "Empty result"));
echo $response;
} else {
echo $response;
}
} catch(Exception $e) {
$result = array("result" => -1, "message" => $e -> getMessage());
echo json_encode($result);
}
} else {
$result = array("result" => -3, "message" => "Unsupported method : " . $_SERVER['REQUEST_METHOD']);
echo json_encode($result);
}
?>
Can anyone help please.. Thank you..
The problem is that you are mixing between the mysqli_xxx() and mysql_xxx() functions. These two libraries are not compatible with each other; you must only use one or the other throughout your code.
Since the mysql_xxx() functions are obsolete and deprecated, that means you should only use mysqli_xxx().
Change all occurrences of mysql_ in your code to mysqli_.
You will also need to make other changes to these lines of code -- notably this will include adding the DB reference variable (ie the variable returned by getConnection()), but some other syntax changes may also be necessary.
I want to make a sendmail function on my program. But first, I want to store the information: send_to, subject, and message in a table in another database(mes) where automail is performed. The problem is data fetched from another database(pqap) are not being added on the table(email_queue) in database(mes).
In this code, I have a table where all databases in the server are stored. I made a query to select a specific database.
$sql5 = "SELECT pl.database, pl.name FROM product_line pl WHERE visible = 1 AND name='PQ AP'";
$dbh = db_connect("mes");
$stmt5 = $dbh->prepare($sql5);
$stmt5->execute();
$data = $stmt5->fetchAll(PDO::FETCH_ASSOC);
$dbh=null;
Then after selecting the database,it has a query for selecting the information in the table on the selected database. Here's the code.
foreach ($data as $row5) GenerateEmail($row5['database'], $row5['name']);
Then this is part (I think) is not working. I don't know what's the problem.
function GenerateEmail($database, $line) {
$sql6 = "SELECT * FROM invalid_invoice WHERE ID=:id6";
$dbh = db_connect($database);
$stmt6 = $dbh->prepare($sql6);
$stmt6->bindParam(':id6', $_POST['idtxt'], PDO::PARAM_INT);
$stmt6->execute();
$data = $stmt6->fetchAll(PDO::FETCH_ASSOC);
$dbh=null;
foreach ($data as $row6) {
$invnumb=$row6['Invoice_Number'];
$partnumb=$row6['Part_Number'];
$issue=$row6['Issues'];
$pic=$row6['PIC_Comments'];
$emailadd= $row6['PersoninCharge'];
if($row6['Status']=="Open") {
$message = "<html><b>Invoice Number: {$invnumb}.</b><br><br>";
$message .= "<b>Part Number:</b><br><xmp>{$partnumb}</xmp><br><br>";
$message .= "<b>Issues:</b><br><xmp>{$issue}</xmp><br>";
$message .= "<b>{$pic}<b><br>";
$message .= "</html>";
if(!empty($emailadd)) {
dbInsertEmailMessage($emailadd, "Invoice Number: {$invnumb} - {$issue}.", $message);
$dbh=null;
}
}
}
}
function dbInsertEmailMessage($send_to, $subject, $message) {
$sql7 = "INSERT INTO email_queue (Send_to, Subject, Message) VALUES (:send_to, :subject, :message)";
$dbh = db_connect("mes");
$stmt7 = $dbh->prepare($sql7);
$stmt7->bindParam(':send_to', $send_to, PDO::PARAM_STR);
$stmt7->bindParam(':subject', $subject, PDO::PARAM_STR);
$stmt7->bindParam(':message', $message, PDO::PARAM_STR);
$stmt7->execute();
$dbh=null;
}
Here's my db connection:
function db_connect($DATABASE) {
session_start();
// Connection data (server_address, database, username, password)
$servername = '*****';
//$namedb = '****';
$userdb = '*****';
$passdb = '*****';
// Display message if successfully connect, otherwise retains and outputs the potential error
try {
$dbh = new PDO("mysql:host=$servername; dbname=$DATABASE", $userdb, $passdb, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
return $dbh;
//echo 'Connected to database';
}
catch(PDOException $e) {
echo $e->getMessage();
}
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
There are a couple things that may help with your failed inserts. See if this is what you are looking for, I have notated important points to consider:
<?php
// take session_start() out of your database connection function
// it draws an error when you call it more than once
session_start();
// Create a connection class
class DBConnect
{
public function connect($settings = false)
{
$host = (!empty($settings['host']))? $settings['host'] : false;
$username = (!empty($settings['username']))? $settings['username'] : false;
$password = (!empty($settings['password']))? $settings['password'] : false;
$database = (!empty($settings['database']))? $settings['database'] : false;
try {
$dbh = new PDO("mysql:host=$host; dbname=$database", $username, $password, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
// You return the connection before it hits that setting
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $dbh;
}
catch(PDOException $e) {
// Only return the error if an admin is logged in
// you may reveal too much about your database on failure
return false;
//echo $e->getMessage();
}
}
}
// Make a specific connection selector
// Put in your database credentials for all your connections
function use_db($database = false)
{
$con = new DBConnect();
if($database == 'mes')
return $con->connect(array("database"=>"db1","username"=>"u1","password"=>"p1","host"=>"localhost"));
else
return $con->connect(array("database"=>"db2","username"=>"u2","password"=>"p2","host"=>"localhost"));
}
// Create a query class to return selects
function query($con,$sql,$bind=false)
{
if(empty($bind))
$query = $con->query($sql);
else {
foreach($bind as $key => $value) {
$kBind = ":{$key}";
$bindVals[$kBind] = $value;
}
$query = $con->prepare($sql);
$query->execute($bindVals);
}
while($row = $query->fetch(PDO::FETCH_ASSOC)) {
$result[] = $row;
}
return (!empty($result))? $result:0;
}
// Create a write function that will write to database
function write($con,$sql,$bind=false)
{
if(empty($bind))
$query = $con->query($sql);
else {
foreach($bind as $key => $value) {
$kBind = ":{$key}";
$bindVals[$kBind] = $value;
}
$query = $con->prepare($sql);
$query->execute($bindVals);
}
}
// Do not create connections in your function(s), rather pass them into the functions
// so you can use the same db in and out of functions
// Also do not null the connections out
function GenerateEmail($con,$conMes,$line = false)
{
if(empty($_POST['idtxt']) || (!empty($_POST['idtxt']) && !is_numeric($_POST['idtxt'])))
return false;
$data = query($con,"SELECT * FROM `invalid_invoice` WHERE `ID` = :0", array($_POST['idtxt']));
if($data == 0)
return false;
// Instead of creating a bunch of inserts, instead create an array
// to build multiple rows, then insert only once
$i = 0;
foreach ($data as $row) {
$invnumb = $row['Invoice_Number'];
$partnumb = $row['Part_Number'];
$issue = $row['Issues'];
$pic = $row['PIC_Comments'];
$emailadd = $row['PersoninCharge'];
if($row['Status']=="Open") {
ob_start();
?><html>
<b>Invoice Number: <?php echo $invnumb;?></b><br><br>
<b>Part Number:</b><br><xmp><?php echo $partnumb; ?></xmp><br><br>
<b>Issues:</b><br><xmp><?php echo $issue; ?></xmp><br>
<b><?php echo $pic; ?><b><br>
</html>
<?php
$message = ob_get_contents();
ob_end_clean();
if(!empty($emailadd)) {
$bind["{$i}to"] = $emailadd;
$bind["{$i}subj"] = "Invoice Number: {$invnumb} - {$issue}.";
$bind["{$i}msg"] = htmlspecialchars($message,ENT_QUOTES);
$sql[] = "(:{$i}to, :{$i}subj, :{$i}msg)";
}
}
$i++;
}
if(!empty($sql))
return dbInsertEmailMessage($conMes,$sql,$bind);
return false;
}
function dbInsertEmailMessage($con,$sql_array,$bind)
{
if(!is_array($sql_array))
return false;
write($con,"INSERT INTO `email_queue` (`Send_to`, `Subject`, `Message`) VALUES ".implode(", ",$sql_array),$bind);
return true;
}
// Create connections
$con = use_db();
$conMes = use_db('mes');
GenerateEmail($con,$conMes);
I am trying to establish a data connection to the MySql and create prepared statements, where the query_f function takes in any number of parameters, where the first parameter is the sql statement, and the other parameters are the values that would be substituted in the prepared statement.
Here is what I have. The first error I got is when I am trying to bind the values to the statement.
function query_f(/* query, [...] */){
$user = "root";
$pass = "root";
$host = "localhost";
$database = "mcnair";
$conn = mysqli_connect($host,$user,$pass);
if(!$conn)
{
echo "Cannot connect to Database";
}
else
{
mysqli_select_db($conn, $database);
}
// store query
$query = func_get_arg(0);
$parameters = array_slice(func_get_args(), 1);
$param = "'".implode("','",$parameters)."'";
// Prepare the statement
$stmt = mysqli_prepare($conn, $query);
if ($stmt == false)
{
echo "The statement could not be created";
exit;
}
// Bind the parameters
$bind = mysqli_stmt_bind_param($stmt, 's', $param);
echo mysqli_stmt_error($stmt);
if ($bind == false)
{
echo "Could not bind";
}
else
{
echo "Bind successful";
}
// Execute the statement
$execute = mysqli_stmt_execute($stmt);
if ($execute = false)
{
echo "Could not execute";
}
// fetch the data
$fetch = mysqli_stmt_fetch($stmt)
if ($fetch == false)
{
echo "Could not fetch data";
}
else
{
return $fetch;
}
}
And the function call I am using is:
query_f("SELECT Hash FROM alumni WHERE Username = '?'", "zm123");
How about using a class (instead of a function) and using mysqli in the OO way and not in the procedural way?
This is a simplified version of what I use. Not perfect, so if anyone would like to suggest improvements, I'm all ears.
class Connection {
private $connection;
public function __construct()
{
//better yet - move these to a different file
$dbhost = '';
$dbuname = '';
$dbpass = '';
$dbname = '';
$this->connection = new mysqli($dbhost, $dbuname, $dbpass, $dbname);
}
/*
* This is the main function.
*
* #param $arrayParams = array (0 => array('s' => 'Example string'), 1 => array('s' => 'Another string'), 2 => array('i' => 2), 3 => array('d' => 3.5) )
*/
public function executePrepared($sql, $arrayParams)
{
$statement = $this->prepareStatement($sql);
if ($statement) {
$this->bindParameter($statement, $arrayParams);
$this->executePreparedStatement($statement);
$result = $this->getArrayResultFromPreparedStatement($statement);
//only close if you are done with the statement
//$this->closePreparedStatement($statement);
} else {
$result = false;
}
return $result;
}
public function prepareStatement($sql)
{
$statement = $this->connection->prepare($sql) or $this->throwSqlError($this->connection->error);
return $statement;
}
public function bindParameter(&$statement, $arrayTypeValues)
{
$stringTypes = '';
$arrayParameters = array();
$arrayParameters[] = $stringTypes;
foreach ($arrayTypeValues as $currentTypeVale) {
foreach ($currentTypeVale as $type => $value) {
$stringTypes .= $type;
$arrayParameters[] = &$value;
}
}
$arrayParameters[0] = $stringTypes;
call_user_func_array(array($statement, "bind_param"), $arrayParameters);
}
public function getArrayResultFromPreparedStatement(&$statement)
{
$statement->store_result();
$variables = array();
$data = array();
$meta = $statement->result_metadata();
while($field = $meta->fetch_field())
$variables[] = &$data[$field->name]; // pass by reference
call_user_func_array(array($statement, 'bind_result'), $variables);
$i = 0;
$arrayResults = array();
while($statement->fetch())
{
$arrayResults[$i] = array();
foreach($data as $k=>$v)
{
$arrayResults[$i][$k] = $v;
}
$i++;
}
return $arrayResults;
}
public function executePreparedStatement($statement)
{
$result = $statement->execute() or $this->throwSqlError($statement->error);
return $result;
}
public function closePreparedStatement($statement)
{
$statement->close();
}
public function throwSqlError()
{ ... }
}
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();
}
}