PHP populate array inside a function - php

i have a small problem with my php code.
i've created a class for Clients, to return me a list with all clients. The problem is when i call the function from outsite, it dont show me the clietsList.
<?php
$returnData = array();
class Clients
{
public function readAll(){
$query = "SELECT * FROM clients";
$result = $this->con->query($query);
if ($result->num_rows > 0){
while ($row = $result->fetch_assoc()){
$returnData['clientsList'][] = $row;
}
return $returnData;
}
else{
echo "No found records";
}
}
}
if ($auth->isAuth()){
$returnData['message'] = "you are loggedin, so is ok";
$clientsObj = new Clients();
$clientsObj->readAll();
}
echo json_encode($returnData);
?>
and the result is like that, but without clietslist
{
"message": "you are loggedin, so is ok"
}
Where im doing wrong? Thanks for your answer. i want to learn php, im begginer. thanks in advance.

You need to get return value of function in a variable:
$returnData['message'] = "you are loggedin, so is ok";
$clientsObj = new Clients();
$returnData['clients'] = $clientsObj->readAll();

$returnData on you first line will not be same as $returnData in your function. $returnData in readAll function will be a new variable.
I suggest you to read about variable scope in php.
https://www.php.net/manual/en/language.variables.scope.php
Now, You will need to store returned value from function in a variable
like this
$returnData['message'] = "you are loggedin, so is ok";
$clientsObj = new Clients();
$clientListArray = $clientsObj->readAll(); //store returned value in a variable
$returnData['clientsList'] = $clientListArray['clientsList'];

Related

Implement If condition in PHP array

I am new to PHP function. I think following problem can be solved using function. Here I am able to store html form data in database which is passed from ajax using following code. But I am little bit confused where to implement if condition. If Data has been submitted, I want to stop data replication.
My working php code
if(isset($_POST["section_name"])){
$section_name = $_POST["section_name"];
$class_id = $_POST["class_id"];
for($count = 0; $count<count($section_name); $count++)
{
$query =$con->prepare('INSERT INTO section(class_id, section_name) VALUES (:class_id, :section_name)');
$query->bindParam(':class_id', $class_id);
$query->bindParam(':section_name', $section_name[$count]);
$query->execute();
echo "Section has been assigned";
}
}
Now, I want to include above code in following else condition.
$query =$con->query('SELECT * FROM section');
while($row=$query->fetch(PDO::FETCH_ASSOC)){
if(($_POST["class_id"]==$row["class_id"])&&($_POST["section_name"]==$row["section_name"])){
echo "Section has already assigned in this class ";
}
else{
// insert...
}
}
When I try to merge code, I can't handle. Please help me
You have pretty much everything, you just need to wrap it in a function like this:
function insert() {
if(isset($_POST["section_name"])){
$section_name = $_POST["section_name"];
$class_id = $_POST["class_id"];
for($count = 0; $count<count($section_name); $count++)
{
$query =$con->prepare('INSERT INTO section(class_id, section_name) VALUES (:class_id, :section_name)');
$query->bindParam(':class_id', $class_id);
$query->bindParam(':section_name', $section_name[$count]);
$query->execute();
echo "Section has been assigned";
}
}
}
And then you call it like this:
$query =$con->query('SELECT * FROM section');
while($row=$query->fetch(PDO::FETCH_ASSOC)){
if(($_POST["class_id"]==$row["class_id"])&&($_POST["section_name"]==$row["section_name"])){
echo "Section has already assigned in this class ";
}
else{
insert();
}
}

Trying to retreive int type from function and compare it with $_Get value (mysql PHP)

I trying to retreive int type from database and compare it with $_Get value
Here is the code for when the user click on the button
if(isset($_GET['btn_placeorder']))
{
$Quantity_Ordered=(int)$_GET['Quantity_Ordered'];
**# retreivng another value from function to compare it as integer**
$number= (int)$auth_user->Blood_Bankavaliable ($Blood_BankID,$Type_Ordered);
try
{
if ($Type_Ordered=="" || $Quantity_Ordered=="")
{
$error[] = "Valid data is required!";
}
else if($Quantity_Ordered >$number) {
$error[] = "This Number is not avaliable in our Stock !";
}
Here is the code for the function
function Blood_Bankavaliable($blood_bankID,$Type_Ordered) {
global $conn;
# query for getting the value from the database
$query = "select sum(Blood_quantity) as d from Donor_Blood_Bank where Blood_Type=$Type_Ordered and blood_bankID= $blood_bankID";
try {
$statement = $this->conn->prepare($query);
$statement->execute();
$result = $statement->fetchall;
return $result;
} catch(PDOException $e)
{
echo $e->getMessage();
}
}
I don't know what is the problem with my code any help?
First, it should be $result = $statement->fetchAll();(a function or method), not $result = $statement->fetchall (a property).
Second, please read the manul, fetchall() return an array. therefore you can't cast it to int directly. run print_r( $auth_user->Blood_Bankavaliable($Blood_BankID,$Type_Ordered) ); to see yourself.

Php webservice inserting data to a database

In my Authentication.php class I hava a code like below;
public function prepareTicket($data){
if(array_key_exists('tickettype', $data))
$this->tickettype = $data['tickettype'];
if(array_key_exists('ticketinfo', $data))
$this->ticketinfo = $data['ticketinfo'];
}
function createTicket(){
$sql = "INSERT INTO ticket_test (tickettype, ticketinfo) VALUES ('$this->tickettype','$this->ticketinfo')";
$result = mysqli_query($this->DB_CONNECTION,$sql);
}
function createTicketControl(){
$sql = "SELECT * FROM `ticket_test` WHERE tickettype = '".$this->tickettype."'AND ticketinfo ='".$this->ticketinfo."'";
$result = mysqli_query($this->DB_CONNECTION,$sql);
if(mysqli_num_rows($result) >0){
return true;
}else{
return false;
}
}
and in the other php file I have a code like this;
<?php
include_once 'Authentication.php';
use user\Authentication;
$auth = new Authentication();
$auth->prepareTicket($_POST);
$ticketStatus = $auth->createTicketControl();
if($ticketStatus){
$json['success'] = 1;
$json['message'] = 'Destek kaydı oluşturuldu';
}else{
$json['success'] = 0;
$json['message'] = 'Error!';
}
echo json_encode($json);
Now my problem is that whenever I try to insert data to my database it returns 'success' = '0' , 'message' = 'Error' and the data couldnt be inserted on the database.I mean the service is not working properly.Any help is appreciated...
P.S.= I am aware of sql injection threat on this code bu it is for android app so no need to worry about it.
Found the solution.I realised that in CreateTicket.php I didint call createTicket function from Authentication.php :/

display data from phpmyadmin

I'm a beginner in PHP5 and I'would like to have some help to get the code correct. Check the code and I'will be grateful for your support.
index.php:
if ($tag == 'AfficherMesAnnonce')
{
$Id_Utilisateur= $_GET['Id_Utilisateur'];
$annonce = $db->MesAnnonces($Id_Utilisateur);
if ($annonce)
{
$response["success"] = 1;
$response["annonce"]["Departure_place"] =$annonce["Departure_place"];
$response["annonce"]["Departure_date"] = $annonce["Departure_date"];
$response["annonce"]["Arrival_place"] = $annonce["Arrival_place"];
$response["annonce"]["Path_type"] = $annonce["Path_type"];
echo json_encode($response);
// annonce stored successfully
}else
{
$response["error_msg"] ="No annonce found";
return false;
echo json_encode($response);
}
}
DB_Function.php:
public function MesAnnonces($Id_Utilisateur)
{
$result = mysql_query("SELECT * FROM annonce WHERE Utilisateur_Id_Utilisateur = $Id_Utilisateur") or die(mysql_error());
// check for result
while($row = mysql_fetch_assoc($result))
{
$dd[]=$row;
}
$response=array('annonce'=> $dd);
return $response;
}
and thank you in advance.
You DB function is creating the dd array as a collection of rows, and then nesting that as an element of what's returned. But in your calling script you're assigning
$response["annonce"]["Departure_place"] = $annonce["Departure_place"]
--but the right side of that doesn't exist. You could instead assign:
$response["annonce"]["Departure_place"] = $annonce[0][0]["Departure_place"]
which would be the first row. You're not iterating through the rows in the client script, or using any kind of index to select a row.

returning array and message to function

please help me out regarding this function. I want to fetch data from the database and if there are results, I want to return a message and data array.
$this->query=("select * from user where pno='".$search."'");
$rd = $this->executeQuery();
$data = $rd->fetch_assoc();
if ($data) {
$message = "Record found.";
} else {
$message = "Record not found.";
}
return array($data, $message);
I am calling it this way:
list($data, $message)=$user->search($result);
echo $message
echo $data['name'];
I am getting the message but I am unable to fetch the array.
Please help me out if there is a problem in the function or if I can improve it.
Never do it this way
you should put your message setting code outside of the function.
function getData(){
$this->query=("select * from user where pno='".$search."'");
$rd = $this->executeQuery();
return $rd->fetch_assoc();
}
if ($data = getData()){
$message = "Record found.";
echo $message;
echo $data['name'];
} else {
$message = "Record not found.";
echo $message;
}
I'm not sure what you're using, but most likely you'll have an array of rows in $data, even if there is only single row. Try $data[0]['name']. Besides, I'd suggest that you move that message from your function to the place where it's called, and make the function return NULL or FALSE if nothing found.
$this->query=("select * from user where pno='".$search."'");
$rd = $this->executeQuery();
$data = $rd->fetch_assoc();
return empty($data)?FALSE:$data;
You’re missing a semicolon after echo $message in your code example.
Try appending this to your code and tell us what it returns:
var_dump($data);

Categories