Count empty mysql columns in PHP - php

I'm trying to create a method that counts the empty mysql columns.
My code is as follows:
public function countCompletion() {
$userData = $this->find(Session::get('user'));
$userData = $this->_data;
$completion = 0;
foreach($userData as $item) {
if(empty($item)) {
$completion++;
}
}
die($completion);
}
The problem is, when I die $completion it just shows nothing, while it should show 2.

According to the documentation, when die (or exit) is called with an integer argument the argument is not printed but is instead passed back to the operating system as an exit code. To get the value to display you will need to return it, then print it from the calling routine.

first check with "echo" inside "foreach" to display column content then you can do a loop to incremente number of empty column
foreach($userData as $item) {
echo 'data: '.$item.'<br>';
if(empty($item)) {
$completion++;
}
}
bacause you have to verify that your function is executing successfully

you can use "var_dump()" also to test what variable contains
var_dump($completion);
die();

Related

Why is print_r return value and 1

My class getting the name
public function getGameName($gameID){
$gameIDValid = false;
try {
$db = database::databaseConnect();
$getGame_stmt = $db->prepare('SELECT gameID, shortTitle FROM games WHERE gameID =:gameID');
$getGame_stmt->bindParam(':gameID', $gameID, PDO::PARAM_INT);
$getGame_stmt->execute();
if($getGame_stmt->rowCount() == 1){
$gameIDValid = true;
}
$db = NULL;
} catch (PDOException $e) {
$gameIDValid = false;
}
return $gameIDValid;
}
From my class doing error checking
public function validategameID($gameID) {
$validGame = userValidation::getGameName($gameID);
if($validGame === false){
return 'Problem adding your game';
}
}
My Validation code:
$validatedGameID = $validateUserInput->validategameID($gameID);
die($validatedGameID);
If I choose a wrong Game ID I get the error message. However when I use:
die(print_r($validatedGameID));
I get the following output:
Problem adding your game1
If I use the correct Game ID I can't execute any other code after the:
die($validatedGameID);
Can anyone please help? Why is the function returning a 1 at the end of the error message when I use print_r and why can't I execute any code after the die even with a correct game id?
The print_r function prints all its output to the screen and returns true as a value. If you want it to return the data rather than print to screen add true as the second parameter
$dump = print_r($var, true);
See http://php.net/manual/en/function.print-r.php
The line:
die(print_r($validateGameID));
performs the following steps:
Call print_r($validateGameID). This prints the value of $validateGameID, because that's what print_r() does when called with 1 argument.
Call die() with the return value of print_r(). print_r() returns TRUE when called with 1 argument. This performs the following steps:
Print 1, because TRUE becomes 1 when converted to a string.
Exit the script, because that's what die() does (it's just an alternate name for exit(), but by convention used when exiting because of an error)
So all together it prints $validateGameID, then prints 1, then exits the script.
Since it exits the script, nothing after it executes.
You can give print_r() a second argument to make it return the formatted version of its argument, rather than printing it:
die(print_r($validateGameID, true));
Or you could simply call print_r() and die() seperately:
print_r($validateGameID);
die();

INSERT if doesn't already exist in database

I created a function that looks for all rows (records) in a specific column,
generates a random number and then checks if it already exists withing that column, if the generated random number exists restart the function (recursive)
if it doesn't exist then insert it as new.
$verifs = mysqli_query($conlink, 'SELECT verif FROM memebers');
$records = array();
while($record = mysqli_fetch_array($verifs,MYSQLI_NUM)) {
$records[] = $record[0];
}
function randomize(){
$rand= rand(1,5);
if(in_array($rand, $GLOBALS['records'])){
randomize();
}else{
return $rand;
}
}
mysqli_query($conlink, "INSERT INTO `memebers`(`verif`) VALUES (".randomize().")");
i expected that a number MUST be added EACH time i refresh my php page
and it was the case, but when i reach 3 or 4 records, refreshing the page doesn't add any ! so the return statement must prevent the function from being recursive.
am i having anything wrong with my logic
thanks
It appears to me that you are not using the callback function correctly. If you didn't know, when you use a function within a function, you actually have to pass that function inside the parameters. Functions that have a function in the parameter are called callback functions and you can read more about them in the following post: What is a callback function and how do I use it with OOP
I would then change your randomize function to the following code:
function randomize($callbackRandomize){
$rand= rand(1,5);
if(in_array($rand, $GLOBALS['records'])){
return $callbackRandomize($callbackRandomize);
}else{
return $rand;
}
}
and also change your last line of code to:
mysqli_query($conlink, "INSERT INTO `memebers`(`verif`) VALUES (".randomize('randomize').")");
Let me know if that worked for you.

PHP scope issue within while loop

Trying to teach myself php and I am struggling with what I think is a scoping issue?
I have a query, while loop, if/else and a function.
I would like to echo the results of the function get_patronapi_data($id) within my while loop.
My code so far is as follows (stripped for legibility);
$stmt = $conn->prepare("SELECT... ..."); //QUERY here ...
if( $stmt->num_rows > 0 )
{
while ($stmt->fetch()) {
if (SomethingIsTrue){
echo get_patronapi_data($id);
}
else {
echo $somethingElse;
}
}//end while
}//end if
define("APISERVER", "http://mydomain:4500");
function get_patronapi_data($id) {
$apiurl = "APISERVER" . "/PATRONAPI/$id/dump";//line 135
$api_contents = get_api_contents($apiurl);
$api_array_lines = explode("\n", $api_contents);
foreach($api_array_lines as $line){
if(strpos($line, "EXP DATE") !== false){
$data = explode("=", $line);
return $data[1];
}//end if
}//end foreach
}//end function
function get_api_contents($apiurl) {
$api_contents = file_get_contents($apiurl);//line 154
$api_contents = trim(strip_tags($api_contents));
return $api_contents;
}//end function
echo get_patronapi_data($id); // this works and echoes $data on screen
Whenever I echo get_patronapi_data($id); outside of the functions I successfully see the data on screen. However when I echo get_patronapi_data($id); within the loop I receive the following errors;
Notice: Use of undefined constant APISERVER - assumed 'APISERVER' in
C:\xampp...search_1.php on line 135
Warning: file_get_contents(APISERVER/PATRONAPI/3047468/dump): failed
to open stream: No such file or directory in C:\xampp...search_1.php
on line 154
I'm sure I am doing something very silly however any help is appreciated.
Putting some of my comments to an answer.
You need to remove the quotes from:
$apiurl = "APISERVER" . "/PATRONAPI/$id/dump";
^ ^ <<< remove those
since that's treated as a string literal, rather than a constant.
It is declared in:
define("APISERVER", "http://mydomain:4500");
Reference:
http://php.net/manual/en/function.constant.php
Then your connection is out of scope and should be used inside your function(s).
I.e.:
function get_patronapi_data($conn, $id)
and do that for all your functions requiring a connection for them.
You will need to make sure that all folders/files have proper permissions to be written to.
The missing link is the statement:
$data = get_patronapi_data($id);
you should put before echo $data;.
It calls the function get_patronapi_data() passing the value of variable $id as argument and stores the values the function returns in the variable $data.
The variable $data you echo() is not the same as the one used by the function. They use the same name but they are different (I hope you don't use the keyword global in the function).
Read more about functions in the PHP documentation.
The updated (fragment of) code looks like:
if (SomethingIsTrue) {
$data = get_patronapi_data($id);
echo $data;
} else {
echo $somethingElse;
}
If you don't do further processing on the value returned by the function, you can, as well, remove the temporary variable $data from the code fragment above and just use:
if (SomethingIsTrue) {
echo get_patronapi_data($id);
} else {
echo $somethingElse;
}
Assuming you want to print the data from the get_patronapi_data() every iteration in the while loop, you need to actually call the method instead of using $data. Right now you're trying to print something called $data, though you never set a value to it. The $data you return in the function cannot be used outside of that function, so it does not exist in the while loop.
What you could do in your while loop is $data = get_patronapi_data();, and then echo $data. However, you can just echo get_patronapi_data(); first.
If you only want to call your function once, you need to set a variable before you start your while loop (i.e. $variable = get_patronapi_data()), and then use that variable in your while loop (i.e. echo $variable);
I'm not sure I fully understand your question. What happens if you just put
echo get_patronapi_data($id);
in the loop instead of
echo $data;
? As written, you're not calling the function in the loop.

Why this if else condition is not not working properly

$taskid=$this->privacy();
if($taskid){I returning something in one function and then by reference to this return,I am fetching data from another table in second function using if condition in such a way that if data(return) found in first table then execute else leave empty
But I data found in first table then every thing is fine,hower data not found in first table then it shows as Notice: Undefined variable: task in....
I think error is in if else condition.Please help or suggest any alternative approach.
Plz also note that that I am working on pricacy table
first function returning rows
function privacy()
{
$session=new session();
$sql2=mysqli_query($this->db->connection,"SELECT * from privacy where viewerid='$session->userid'");
while($row2=mysqli_fetch_array($sql2)){
$task[]=$row2['task'];
}
return $task;
}
function 2.. if found something then do something else do nothing(but error appears as undefined variable)
function showactivityo4apply()
{
$session=new session();
$taskid=$this->privacy();
if($taskid){
foreach($taskid as $fvid){
$sql=mysqli_query($this->db->connection,"SELECT * FROM activity where id='$fvid'");
while($row=mysqli_fetch_array($sql)){
$name_id=$row['sub_id'];
echo $name;
}
}
}
else{}
}
if($taskid=$this->privacy()) is assigning a value of $this->privacy() to $taskid
I think you mean
if($taskid == $this->privacy())
If condition have == sign not = sign
if($taskid==$this->privacy()){
}
else
{
}
= means assign value to another
== check the value to other variable
it is showing notice because php is not getting value in array on key "task" use isset() function to check whether data is available or not
use like this
$task[] = (isset($row2['task'])?$row2['task']:'';
if value is not set in $row2['task'] then it will assign blank value in $task[] array.
and one more change you have to do
instead of if($taskid) condition use
if( count($taskid) > 0){
}
so that if record not found in array it will not inter in to the loop
please change this line of your code like:
$sql2=mysqli_query($this->db->connection,"SELECT * from privacy where
viewerid='$session->userid'");
=========================================
to
=============================
$sql2=mysqli_query($this->db->connection,"SELECT * from privacy where
viewerid='" . $session->userid . "'");
=======================
conclution: Here $session->userid is not found thats why you not get result.

PHP function returns unexpected values

Okay I'm new here and I have been trying to figure this out all day I have two functions one calling the other but my functions only returns the last value for example 29 when it should return multiple values. As wondering how can I fix this problem so that my functions return all the values.
Here is my PHP code.
function parent_comments(){
if(articles_parent_comments_info($_GET['article_id']) !== false){
foreach(articles_parent_comments_info($_GET['article_id']) as $comment_info){
$comment_id = filternum($comment_info['comment_id']);
reply_comment_count($comment_id);
}
}
}
function reply_comment_count($parent_id){
if(articles_reply_comments_info($_GET['article_id']) !== false){
foreach(articles_reply_comments_info($_GET['article_id']) as $reply_info){
$comment_id = filternum($reply_info['comment_id']);
$reply_id = filternum($reply_info['parent_id']);
if($parent_id === $reply_id){
reply_comment_count($comment_id);
}
}
}
return $comment_id;
}
You use recursivity to return your $comment_id. If I understand your needs, you want to get every reply id linked to one article id.
In reply_comment_count you return $comment_id but as it rescursively used and you don't keep the previous id returned you only get the last.
If you want to get numerous $comment_id instead of only one, I suggest you to return an array where you push $comment_id every time you find one. Something like that:
func parent_comments(){
loop in articles to get comment_id {
count_array = reply_comment_count(comment_id, count_array)
}
}
func reply_comment_count(parent_id, count_array) {
loop to get id linked to parent_id {
if id is an article {
count_array = reply_comment_count(id, count_array) #recursive call
}
else {
count_comment = count comment linked
count_array.push(count_comment)
}
}
return count_array # when you return your count_array due to recursive call it will be filled with every count, and not only the last
}
I hope this pseudo langage is clear for you. But as you only return the last count you found, you will only have this one.

Categories