INSERT if doesn't already exist in database - php

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.

Related

Return variable not working in PHP (i.e. no value returned!)

I prefer to program in Python language, but have to work in PHP for a specific web site app project.
In PHP I am trying to "return" a value from a function to the main program environment (to be used for subsequent calculations), but no matter what I try the value calculated in my function is not returning the value (but echoing from function works fine).
In Python I never had an issue with returning variables: i.e. all values returned from functions were available and accessible to the main program and/or other functions that called the function that produces the return value.
Can someone please tell me how I can solve this issue? I have been searching google and sites ike stackoverflow for the last 2 days with no success. I have many O'Reilly computer books including many on PHP where I have cross referenced my research and read everything I can about the RETURN function - it seems I am doing everything right and even specifically declaring the value to be returned. It is critical that I am able to return values and have access to those values in order to proceed with development on this project - else I am stuck if I cannot return values to be processed further!!
Here is the relevant code pieces:
// DECLARE FUNCTIONS
// FUNCTION
function Calculation_IsArray ($ArrayAny){
if (is_array($ArrayAny)) {
echo '<div>THIS VAR IS AN ARRAY</div>';
$Var_IsArray = TRUE;
return $Var_IsArray;
} else {
echo '<div>THIS VAR IS **NOT** AN ARRAY</div>';
}
}
After declaring the functions and doing some initial calculations to grab an array for checking, I call the above function as follows:
// CALL FUNCTION
Calculation_IsArray($ArrayOfValues);
I am expecting the program to call the function Calculation_IsArray() and pass it the array to be checked ($ArrayOfValues). You can see from the output below that the array is passed and checked and confirmed to be of array type, and both the FOREACH loop as well as the IF/ELSE conditions are working fine and echoing the correct output. However, the above code does not return any values as you can see the NULL values that are echoed when I check for returned values (i.e. that array that was checked) accessible from the main program after the "return".
And here are the results echoed to browser screen (output):
THIS VAR IS AN ARRAY
RETURNED ARRAY =
NULL
VALUE OF $Var_IsArray =
NULL
COUNT OF ARRAY KEY ELEMENTS = 2
ARRAY KEY ELEMENTS ARE NUMERIC
KEY = 0, VALUE = Array
COUNT OF ARRAY KEY ELEMENTS = 2
ARRAY KEY ELEMENTS ARE NUMERIC
KEY = 1, VALUE = Array
I have searched here at stackoverflow and found reports of similar problems (and I even tried to test those suggestions for solutions, e.g. placing return at various places in my function to test where it would work), but nothing is working, and this failure to return value is not logical according to what I have read that PHP returns values if expliciting told to RETURN.
Thank you very much for any help in this matter!
[After submission of the original question above]:
I am now trying to isolate my problem by creating a test script called TestReturn.php.
In that script I have placed the following code, but still there is no value returned!!
// DECLARE FUNCTIONS
// FUNCTION
function Calculation_IsArray ($ArrayAny){
if (is_array($ArrayAny)) {
echo '<div>THIS VAR IS AN ARRAY</div>';
$Var_IsArray = TRUE;
return $Var_IsArray;
} else {
echo '<div>THIS VAR IS **NOT** AN ARRAY</div>';
}
}
// BEGIN MAIN PROGRAM
$x = array(1, 2, 3, 4, 5, 6, 7);
Calculation_IsArray($x);
// COME BACK TO HERE AFTER THE FUNCTION RETURNS CALCULATED VALUE
echo '<div>HERE IS THE RETURNED VALUE AND VAR_DUMP BELOW:' . $Var_IsArray . '</div>';
var_dump($Var_IsArray);
And here is the output in HTML to browser tab/window/terminal:
THIS VAR IS AN ARRAY
HERE IS THE RETURNED VALUE AND VAR_DUMP BELOW:
NULL
"Captain, this does not compute!", i.e. this doesn't make sense to me why PHP is not returning my value that I specifically tell it to return to main program!
I have tried all possibilities of coding including:
return $variable;
return ($variable);
return() ; // i.e. I read somewhere that PHP by default returns the last calculated value in a function.
return ;
Why is PHP not returning my value/variable back to main program?
When you return something from a function, it doesn't make the variable itself available in the calling scope (i.e. outside the function). In other words, $Var_IsArray only exists inside the function.
Only the contents of the variable are returned, and you must use the result immediately where you call the function; e.g. store it for future reference, pass it to another function, or test it in a condition.
For example:
function foo()
{
$vals = ['red', 'green', 'blue'];
return $vals;
}
$somedata = foo();
In this example, $somedata will end up holding the array that previously was stored in $vals.
This is the standard behaviour for return statements (or equivalent functionality) in most programming languages. There are other ways to get variables out of a function, e.g. by using global variables. Generally, they're not good practice though.
I've used Python before too, and I don't think it's any different (unless I've missed a major language feature). You might want to double-check that your Python code is doing what you think it's doing, otherwise you could end up with some nasty bugs in future.
you could simplify the function to the following so it always returns something ( true,false )
function Calculation_IsArray( $ArrayAny ){
echo is_array($ArrayAny) ? '<div>THIS VAR IS AN ARRAY</div>' : '<div>THIS VAR IS **NOT** AN ARRAY</div>';
return is_array($ArrayAny);
}
Hope this will help:
// FUNCTION
function Calculation_IsArray ($ArrayAny){
if (is_array($ArrayAny)) {
echo '<div>THIS VAR IS AN ARRAY</div>';
return true;
} else {
echo '<div>THIS VAR IS **NOT** AN ARRAY</div>';
return false;
}
}
$array = array(1, 1, 1);
if ( Calculation_IsArray($array) ){
print_r( $array );
}
<?php
// DECLARE FUNCTIONS
// FUNCTION
function Calculation_IsArray ($ArrayAny){
if (is_array($ArrayAny)) {
echo '<div>THIS VAR IS AN ARRAY</div>';
//$Var_IsArray = TRUE;
return true;
} else {
echo '<div>THIS VAR IS **NOT** AN ARRAY</div>';
}
}
// BEGIN MAIN PROGRAM
$x = array(1, 2, 3, 4, 5, 6, 7);
$status = Calculation_IsArray($x);
if($status == true){
// COME BACK TO HERE AFTER THE FUNCTION RETURNS CALCULATED VALUE
echo '<div>HERE IS THE RETURNED VALUE AND VAR_DUMP BELOW:<br />' . print_r($x) . '</div>';
var_dump($x);
}
ok, so while Peter Bloomfield was responding and writing his CORRECT answer, I was hacking away myself and trying different things and remembered that what I also do in Python is make a variable equal to the function call!! I tried that and now it is returning fine anything I do with that function, thank GOD!!
Here is the updated code in main program now that received ok the returned value (it is no longer returning just NULL):
// BEGIN MAIN PROGRAM
$x = array(1, 2, 3, 4, 5, 6, 7);
$ResultOfCalculation = Calculation_IsArray($x);
// COME BACK TO HERE AFTER THE FUNCTION RETURNS CALCULATED VALUE
echo '<div>HERE IS THE RETURNED VALUE AND VAR_DUMP BELOW:' . $ResultOfCalculation . '</div>';
var_dump($ResultOfCalculation);

Count empty mysql columns in 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();

How to use return inside a recursive function in PHP

Here is my question: I am trying to create a random bar code for my application. I want to check that if that code is already in the column, then generate a new number. Check it again. If it's unique, return it to the caller, else generate again.
I am using a recursive function for this purpose. I have added numbers 1,2,3,4 inside my database so every time it runs. It has to show me 5,6,7,8,9 or 10.
Here is my function:
function generate_barcode(){
$barcode = rand(1,10);
$bquery = mysql_num_rows(mysql_query("SELECT * FROM stock_item WHERE barcode='$barcode'"));
if($bquery==1){
generate_barcode();
}else{
return $barcode;
}
}
And I just tested it like this:
$a = generate_barcode();
if(isset($a))
{
echo $a;
}
else
{
echo 'Not Set';
}
So the problem is that it is sometimes showing me "Not Set", but I want it to always generate a unique number. I am not inserting the data, so it's not a problem that all of the numbers are reserved.
Someone just guide me and let me know what is wrong with the code. I can use other approaches to do that, but I need to know what is wrong with the supplied code.
You need to return the generated number from your recursive call too, like:
function generate_barcode() {
$barcode = rand(1, 10);
$bquery = mysql_num_rows(mysql_query("SELECT * FROM stock_item WHERE barcode='$barcode'"));
if ($bquery == 1) {
return generate_barcode(); // changed!
}
else {
return $barcode;
}
}
(You should include some kind of exit for the case that all numbers are 'taken'. This current version will call itself recursively until the PHP recursion limit is reached and will then throw an error.)
A return statement passes a value back to the immediate caller of the current function's call-frame. In the case of recursion, this immediate caller can be another invocation of that same function.
You can counter this by doing the following:
Change:
generate_barcode();
to:
return generate_barcode();
Do it like this:
$hash = md5( microtime().rand(0, 1000) );
Adding a time component means it will pretty much be unique. Unless you have like 32^32 of them.
If it has to be just numbers, just use the pkey and add like 10000 on to it for looks. or such.
After careful analysis - there is nothing wrong with it, but:
$a = generate_barcode();
if(isset($a)) <<< this bit
See you return the unique value and then you say it's isset my unique value, and $a will always be set, because if it's not you recurse the function until it is, and then you return it. Therefore it is always set...
You are trying to do:
while(true) {
$barcode = rand(1,10);
$bquery = mysql_num_rows(mysql_query("SELECT * FROM stock_item WHERE barcode='$barcode'"));
if($bquery===0){
break;
}
}
echo $barcode;
However, this will obviously only work for 10 bar codes and leading to an endless loop after that - meaning it is not the right approach to create a large number of bar codes.
Instead I would suggest to use an auto_increment to generate the bar code.
Btw, the mysql extension is deprecated. Use mysqli or PDO for new code.

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