How to use PHP function parameter inside array? - php

I am trying to declare a function parameter inside my array, but I'm having trouble getting it to work. I've trimmed it down for simplicity purposes, and I have something like:
function taken_value($value, $table, $row, $desc) {
$value = trim($value);
$response = array();
if (!$value) {
$response = array(
'ok' => false,
'msg' => "This can not be blank."
);
} else if (mysql_num_rows(
mysql_query(
"SELECT * FROM $table WHERE $row = '$value'"))) {
$response = array(
'ok' => false,
'msg' => $desc." is already taken."
);
} else {
$response = array(
'ok' => true,
'msg' => ""
);
}
echo json_encode($response);
}
Notice the function parameter $desc trying to be used in the array here:
'msg' => $desc." is already taken.");
The whole function works fine EXCEPT when I try to add the $desc to the array results.
How could this be done?

Do you have an open resource handle to your database? You are not passing one to the query function.

Related

Post data using php

I made a API to fetch and store data, I can fetch data without problem, but everything changes when I try to store data, when I send the data it returns [{"success":"0"}]. In the beginning it worked well, used accepted to store data, but suddenly everything changed. I've tried everything, compare the new with the old, changed the code, tables, but even so it always returns [{"success":"0"}] after comparing both (old and new) code I couldn't see much difference. What could I be doing wrong?
Insert data:
function insertloin()
{
if(isset($_POST["loincode"]))
{
$form_data = array(
':loincode' => $_POST["loincode"],
':code' => $_POST["code"],
':specie' => $_POST["specie"],
':grade' => $_POST["grade"],
':vesselname' => $_POST["vesselname"],
':type' => $_POST["type"],
':productformat' => $_POST["productformat"],
':dateprocessed' => $_POST["dateprocessed"],
':datebb' => $_POST["datebb"],
':projectcode' => $_POST["projectcode"],
':netweight' => $_POST["netweight"],
':producttype' => $_POST["producttype"],
':oldoc' => $_POST["oldoc"]
);
$query = "
INSERT INTO loins
(loincode, code, specie, grade, vesselname, type, productformat, dateprocessed, datebb, projectcode, netweight, producttype, oldoc) VALUES
(:loincode, :code, :specie, :grade, :vesselname, :type, :productformat, :dateprocessed, :datebb, :projectcode, :netweight, :producttype, :oldoc)
";
$statement = $this->connect->prepare($query);
if($statement->execute($form_data))
{
$data[] = array(
'success' => '1'
);
}
else
{
$data[] = array(
'success' => '0'
);
}
}
else
{
$data[] = array(
'success' => '0'
);
}
return $data;
}
Test:
if($_GET["action"] == 'insertloin')
{
$data = $api_object->insertloin();
}
Action:
if(isset($_POST["action"]))
{
if($_POST["action"] == 'insertloin')
{
$form_data = array(
'loincode' => $_POST["loincode"],
'code' => $_POST["code"],
'specie' => $_POST["specie"],
'grade' => $_POST["grade"],
'vesselname' => $_POST["vesselname"],
'type' => $_POST["type"],
'productformat' => $_POST["productformat"],
'dateprocessed' => $_POST["dateprocessed"],
'datebb' => $_POST["datebb"],
'projectcode' => $_POST["projectcode"],
'netweight' => $_POST["netweight"],
'producttype' => $_POST["producttype"],
'oldoc' => $_POST["oldoc"]
);
$api_url = "http://192.168.85.160/API/v2/api/test_api.php?action=insertloin";
$client = curl_init($api_url);
curl_setopt($client, CURLOPT_POST, true);
curl_setopt($client, CURLOPT_POSTFIELDS, $form_data);
curl_setopt($client, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($client);
curl_close($client);
$result = json_decode($response, true);
foreach($result as $keys => $values)
{
if($result[$keys]['success'] == '1')
{
echo 'insert';
}
else
{
echo 'error';
}
}
}
Please, help me find the bug.
Kind regards,
Abd
When $statement->execute() returns a false value it means your SQL had some sort of error. But you ignore that false value and instead return the same success status in both your if and your else clause.
To see your error codes try something like this:
if($statement->execute($form_data))
{
$data[] = array(
'success' => '1'
);
}
else
{
echo $statement->errorInfo();
print_r ( $statement->errorInfo() );
die(1);
}
You'll need to look at the error codes you get to see what's wrong and then do something smarter than echo / print_r / die.

Turn a array into a variable for send in PHPMailer

Im trying to turn a array that haves another array from a SQL select into a unique variable to send it for users by PHPMailer, I tried to place the array on variable of PHPMailer so didnt works, thats why Im trying this way that looks a little bit difficult
public static function getUsersByEmail($email) {
$sql = DB::prepare(
"SELECT username FROM users WHERE email=:email ORDER BY id LIMIT 10"
);
$sql->bindParam('email', $email);
$sql->execute();
$accounts = $sql->fetchAll(PDO::FETCH_ASSOC);
return $accounts; // its array
}
public function recoverUsername($email) {
if (User::emailHasAccounts($email) == true) {
$accounts = [User::getUsersByEmail($email)];
$str = implode(",", $accounts); // imploding array
$mail = new Mail([
'email' => $email,
'subject' => SITENAME,
'template' => 'accountslist',
'variables' => json_encode([
'email' => $email,
'accountList' => $str,
'date' => date('d/m/y h:i')
]),
'time' => time(),
'next_attemp' => time(),
'attemps' => 0,
'status' => 0
]);
// $mail->dbInsert();
return true;
} else {
echo "erro";
return false;
}
}
Solution (for PHP 5.5 <)
$accounts = getAccounts();
$rr = array_column($accounts, 'username');
$array = implode(',', $accounts);
$getaccounts = array_map(function ($accounts) {
return $accounts['username'];
}, $accounts);
$var = implode('<br>', $getaccounts);

Issue with storing string with a backslash(\) in session

Here is a quick example:
function step1() {
$data = array(
'level_1' => array(
'level_2' => 'abc\def'
),
);
$this->session->set_userdata("data", $data);
}
function step2() {
echo '<pre>';
print_r($this->session->all_userdata());
}
As end result, data is not stored in session.
You can separate with '\' using '.'...Think this may work
function step1() {
$data = array(
'level_1' => array(
'level_2' => 'abc'.'\'.'def'
),
);
$this->session->set_userdata($data);
}
function step2() {
echo '<pre>';
print_r($this->session->all_userdata());
}

Zabbix Reading the Api

I'm getting Informations from the Zabbix Api with a PHP library. At the moment I get the "lastvalue" from the json Array:
try {
// connect to Zabbix-API
$api = new ZabbixApi($api_url, $username, $password);
$params = array(
'groupids' => '2',
'real_items' =>TRUE,
'monitored_items' =>TRUE,
'search' => array('name' => 'Disk root used p'),
'selectFunctions' => 'extend',
'output' => 'extend',
'sortfield' => 'name',
'limit' => '1'
);
$trends = $api->itemGet($params); // get data from api
$names = array();
foreach($trends as $trend) { // loop through the returned data
$names[] = $trend->lastvalue;
}
//print_r($names);
} catch(Exception $e) {
// Exception in ZabbixApi catched
echo $e->getMessage();
}
But now I want to get the "lastvalue" plus the "name" of the Item in this Array for example like that: "name"+"lastvalue". How can I get both of them into my array $names[]?
Here is my answer from my comments, hope its what you are looking for!
$trends = $api->itemGet($params);
$names = array();
foreach($trends as $trendKey => $trendValue)
{
$names[$trendKey] = $trendValue;
}
#Test the names array
foreach ($names as $nameKey => $nameValue)
{
print("{$nameKey} = {$nameValue}<br />");
}
Return value:
groupids = 2
real_items = TRUE
...
sortfield = name
limit = 1

I am using CodeIgniter and trying to set a variable based on a return from a query

I am able to use print_r and return this data:
Array (
[array] => Array (
[status] => false
[message] => The %s subscription code is out of date.
)
)
I need to be able to set the elements "status" and "message" to variables. (in this case status = false)
$data = array(
'status' => 'false',
'message' => 'The %s subscription code is out of date.'
);
extract($data);
echo $status; // output 'false' because if you status is string.
echo "<br />";
echo $message; // output %s subscription code is out of date.
Extract() is a very popular function that converts elements in an array into variables in their own righ
If I understand correctly, you want $status and $message to hold the corresponding values?
$input = array(
'status' => false,
'message' => 'The %s subscription code is out of date.'
);
$output = array();
foreach ($input as $key => $value) {
$$key = $value; // assign $value using variable variable
}
print($status); // prints nothing because it's false
print($message); // The %s subscription code is out of date.

Categories