I need help...I'm trying to retrieve data from sql table and compare it with if statement for certain IDs and updating a variable accordinly. But it seems that the variable is not updating for some reason. Below is my code..
$query2 = "SELECT prcID, tProDone
FROM vw_fdwTracker
WHERE AgrNo = '$agreement'";
$result2= sqlsrv_query($conn, $query2);
if ($result2==false){
die( "<pre>".print_r(sqlsrv_errors(), true));
}
$current = 0;
while($id= sqlsrv_fetch_array($result2, SQLSRV_FETCH_ASSOC)){
//echo $id['prcID']." ". $id['tProDone'].'<br>';
if(($id['prcID']===3) && ($id['tProDone']===TRUE)){
$current=12.5;
}elseif(($id['prcID']===4) && ($id['tProDone']===TRUE)){
$current=25;
}elseif(($id['prcID']===5) && ($id['tProDone']===TRUE)){
$current=37.5;
}elseif(($id['prcID']===9) && ($id['tProDone']===TRUE)){
$current=50;
}elseif(($id['prcID']===10) && ($id['tProDone']===TRUE)){
$current=62.5;
}elseif(($id['prcID']===14) && ($id['tProDone']===TRUE)){
$current=75;
}elseif(($id['prcID']===12) && ($id['tProDone']===TRUE)){
$current=87.5;
}elseif(($id['prcID']===17) && ($id['tProDone']===TRUE)){
$current=100;
}else{
$current=0;
}
}
Try saving to an array so you know if it's working or not:
function getCurrentArr($agreement,$conn)
{
$query = "SELECT prcID, tProDone FROM vw_fdwTracker WHERE AgrNo = '$agreement'";
$result = sqlsrv_query($conn, $query);
if(!$result){
die( "<pre>".print_r(sqlsrv_errors(), true));
}
return $result;
}
function getCurrVal($value)
{
$return[3] = 12.5;
$return[4] = 25;
$return[5] = 37.5;
$return[9] = 50;
$return[10] = 62.5;
$return[14] = 75;
$return[12] = 87.5;
$return[17] = 100;
return (isset($return[$value]))? $return[$value] : 0;
}
$curr = array();
$result = getCurrentArr($agreement,$conn);
while($id= sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC)){
if(!$id['tProDone']) {
$curr[] = 0;
continue;
}
$curr[] = getCurrVal($id['prcID']);
}
// See what this gets you for an array
// If what is in this array is what you expect, then
// make the $curr array the variable, but you will overwrite
// every time it loops, just keep that in mind
print_r($curr);
You don't need to define $current variable value at starting of code just do your code like below it will also work on loop
$id['prcID']=3;
$id['tProDone']=false;
if(($id['prcID']==3) && ($id['tProDone']==true)){
$current=12.5;
}else{
$current=0;
}
echo $current;
Related
Hi i am iterating over Episodes getting array of authors and inside this loop i want to gather information about each author. But there is problem, i just need the information about each author once.
This is my approatch, but wrong. and the code i am trying to make. Please help. I tried also in_array, and array_filter but without success.
$presentUsers = [];
$pUi = 0;
if ($isAuthor == true){
if ($project->getType() == 1) {
$episodes = $project->getComic()->getComicEpisodes();
foreach ($episodes as $comicEpisode) {
foreach ($comicEpisode->getProject()->getAccount() as $author) {
if ($author->getUser()->getId() == $this->getUser()->getId()) {
$comicEpisode->setIsMine(true);
$comicEpisode->setRevenue($author->getRevenue());
$comicEpisode->setIncome($author->getIncome());
}
if (empty($presentUsers)){
$presentUsers[$pUi]['Id'] = $author->getUser()->getId();
$presentUsers[$pUi]['Username'] = $author->getUser()->getUsername();
$presentUsers[$pUi]['FirstName'] = $author->getUser()->getFirstName();
$presentUsers[$pUi]['LastName'] = $author->getUser()->getLastName();
$presentUsers[$pUi]['VisibleName'] = $author->getUser()->getVisibleName();
$presentUsers[$pUi]['AvatarFileName'] = $author->getUser()->getAvatarFileName();
$presentUsers[$pUi]['Occupation'] = $author->getUser()->getOccupation();
$presentUsers[$pUi]['LastOnline'] = $author->getUser()->getLastOnline();
$pUi++;
}else{
if (!in_array($presentUsers, ['Id'=>$author->getUser()->getId()]))
{
$presentUsers[$pUi]['Id'] = $author->getUser()->getId();
$presentUsers[$pUi]['Username'] = $author->getUser()->getUsername();
$presentUsers[$pUi]['FirstName'] = $author->getUser()->getFirstName();
$presentUsers[$pUi]['LastName'] = $author->getUser()->getLastName();
$presentUsers[$pUi]['VisibleName'] = $author->getUser()->getVisibleName();
$presentUsers[$pUi]['AvatarFileName'] = $author->getUser()->getAvatarFileName();
$presentUsers[$pUi]['Occupation'] = $author->getUser()->getOccupation();
$presentUsers[$pUi]['LastOnline'] = $author->getUser()->getLastOnline();
$pUi++;
}
}
}
}
}
}else{
die('You are not the author of this project.');
}
Okay i done it like this
if (empty($presentUsers)){
$presentUsers[$pUi]['Id'] = $author->getUser()->getId();
$presentUsers[$pUi]['Username'] = $author->getUser()->getUsername();
$presentUsers[$pUi]['FirstName'] = $author->getUser()->getFirstName();
$presentUsers[$pUi]['LastName'] = $author->getUser()->getLastName();
$presentUsers[$pUi]['VisibleName'] = $author->getUser()->getVisibleName();
$presentUsers[$pUi]['AvatarFileName'] = $author->getUser()->getAvatarFileName();
$presentUsers[$pUi]['Occupation'] = $author->getUser()->getOccupation();
$presentUsers[$pUi]['LastOnline'] = $author->getUser()->getLastOnline();
$pUi++;
}else{
$found = 0;
foreach ($presentUsers as $presentUser){
if ($presentUser['Id'] == $author->getUser()->getId()){
$found = 1;
break;
}
}
if ($found != 1)
{
$presentUsers[$pUi]['Id'] = $author->getUser()->getId();
$presentUsers[$pUi]['Username'] = $author->getUser()->getUsername();
$presentUsers[$pUi]['FirstName'] = $author->getUser()->getFirstName();
$presentUsers[$pUi]['LastName'] = $author->getUser()->getLastName();
$presentUsers[$pUi]['VisibleName'] = $author->getUser()->getVisibleName();
$presentUsers[$pUi]['AvatarFileName'] = $author->getUser()->getAvatarFileName();
$presentUsers[$pUi]['Occupation'] = $author->getUser()->getOccupation();
$presentUsers[$pUi]['LastOnline'] = $author->getUser()->getLastOnline();
$pUi++;
}
}
I am trying to do backtracking to solved a problem but I get this error:
Error: genator hasn´t returned
Fisrt I will introduce the main problem that the software must resolve:
I have been trying to create the software for a hospital, this
software must create a schedule with the doctors for each day. Each
day must have 5 assigned doctors, one for a specialty called "trauma",
another for "ucr" and another for "box13".
Before assigning doctors, the user must enter the number of holes of
each type that doctor can do that month. So I know how many "trauma",
"ucr" or "box13" have any doctor that month.
Aaah! one more thing, you can not assign a doctor two days in a row.
So I decided to create a backtracking algorithm, the problem is that I am getting a Generator object at the end of the execution but I don´t get a valid return.
function bt($ps){
if($ps->is_solution()){
return $ps->get_solution();
}
else{
yield from $ps->successors();
}
}
class Briker_vc_PS{
public function __construct( $decisiones, $diasTotalFinal, $fechaInicio, $box13, $ucr, $trauma, $numGuardiasAsig){
$this->decisiones= $decisiones;
$this->diasTotalFinal = $diasTotalFinal;
$this->fechaInicio = $fechaInicio;
$this->box13 = $box13;
$this->ucr = $ucr;
$this->trauma = $trauma;
$this->numGuardiasAsig = $numGuardiasAsig;
}
public function is_solution(){
return $this->numGuardiasAsig == $this->diasTotalFinal*5;
}
public function get_solution(){
return $this->decisiones;
}
public function state(){
return $this->decisiones[$this->fechaInicio];
}
public function successors(){
if( array_key_exists( $this->fechaInicio, $this->decisiones) == false ){
$this->decisiones[$this->fechaInicio] = [];
}
if( array_key_exists( 'ids', $this->decisiones[$this->fechaInicio]) == false ){
$this->decisiones[$this->fechaInicio]['ids'] = [];
}
if( array_key_exists( $this->fechaInicio ,$this->decisiones) and array_key_exists( 'box13' ,$this->decisiones) and array_key_exists( 'trauma' ,$this->decisiones) and array_key_exists( 'ucr' ,$this->decisiones)){
if( (count($this->decisiones['trauma'])==1) and (count($this->decisiones['ucr'])==2) and (count($this->decisiones['box13'])==2) ){
$this->fechaInicio = date("Y-m-d",strtotime($this->fechaInicio." +1 day"));
$this->decisiones[$this->fechaInicio]['date'] = $this->fechaInicio;
}
}
$anterior = date("Y-m-d",strtotime($this->fechaInicio." -1 day"));
$Lista=[];
if( array_key_exists( 'trauma' ,$this->decisiones) == false ){
foreach($this->trauma as $key => $val){
if( (in_array($key, $this->decisiones[$this->fechaInicio]['ids']) == false) and (in_array($key, $this->decisiones[$anterior]['ids']) == false) ){
$decisions= $this->decisiones;
$decisions[$this->fechaInicio]['trauma'] = [$key];
$auxtra= $this->trauma;
if($auxtra[$key] -1 == 0){
unset($auxtra[$key]);
}else{
$auxtra[$key] = $auxtra[$key] -1;
}
$num = $this->numGuardiasAsig +1 ;
$decisions[$this->fechaInicio]['ids'][] = $key;
yield from bt(new Briker_vc_PS( $decisions, $this->diasTotalFinal, $this->fechaInicio, $this->box13, $this->ucr, $auxtra, $num));
}
}
}
if( (array_key_exists( 'box13' ,$this->decisiones) == false) or (count($this->decisiones['box13'])<2) ){
foreach($this->box13 as $key => $val){
if( (in_array($key, $this->decisiones[$this->fechaInicio]['ids']) == false) and (in_array($key, $this->decisiones[$anterior]['ids']) == false) ){
$decisions= $this->decisiones;
if(array_key_exists( 'box13' ,$this->decisiones) == false){
$decisions[$this->fechaInicio]['box13'] = array();
}
$decisions[$this->fechaInicio]['box13'][] = $key;
$auxbox13= $this->box13;
if($auxbox13[$key] -1 == 0){
unset($auxbox13[$key]);
}else{
$auxbox13[$key] = $auxbox13[$key] -1;
}
$num = $this->numGuardiasAsig +1 ;
$decisions[$this->fechaInicio]['ids'][] = $key;
yield from bt( new Briker_vc_PS( $decisions, $this->diasTotalFinal, $this->fechaInicio, $auxbox13, $this->ucr, $this->trauma, $num));
}
}
}
if( (array_key_exists( 'ucr' ,$this->decisiones) == false) or (count($this->decisiones['ucr'])<2) ){
foreach($this->ucr as $key => $val){
if( (in_array($key, $this->decisiones[$this->fechaInicio]['ids']) == false) and (in_array($key, $this->decisiones[$anterior]['ids']) == false) ){
$decisions= $this->decisiones;
if(array_key_exists( 'ucr' ,$this->decisiones) == false){
$decisions[$this->fechaInicio]['ucr'] = array();
}
$decisions[$this->fechaInicio]['ucr'][] = $key;
$auxucr= $this->ucr;
if($auxucr[$key] -1 == 0){
unset($auxucr[$key]);
}else{
$auxucr[$key] = $auxucr[$key] -1;
}
$decisions[$this->fechaInicio]['ids'][] = $key;
$num = $this->numGuardiasAsig +1 ;
yield from bt(new Briker_vc_PS( $decisions, $this->diasTotalFinal, $this->fechaInicio, $this->box13, $auxucr, $this->trauma, $num));
}
}
}
}
protected $GuardiasMedico;
protected $decisiones;
}
And this is the main program
$month = $_REQUEST['mes'];
$year = $_REQUEST['any'];
$fecha_inicio = "01-".$month."-".$year;
// fisrt i get the number of "trauma", "ucr" and "box13" for each doctor
// And i create a array with it with key the doctor_id
$db = new SQLite3($dbname);
$result = $db->query('SELECT m.id, m.nombre, m.apellido, mgm.ucr, mgm.trauma, mgm.box13 FROM medico AS m INNER JOIN MedicoGuardiaMes AS mgm ON m.id = mgm.doctor_id WHERE m.borrado = 0 AND mgm.mes = '.$month.' AND mgm.any = '.$year);
$box13 = [];
$ucr = [];
$trauma = [];
while($res = $result->fetchArray()){
$box13[$res['id']] = $res['box13'];
$ucr[$res['id']] = $res['ucr'];
$trauma[$res['id']] = $res['trauma'];
}
// I create the solution array and add the last day from the previous month
$dataBaseDecisiones = [];
$anterior = date("Y-m-d",strtotime($fecha_inicio." -1 day"));
$dataBaseDecisiones[$anterior] = [];
$dataBaseDecisiones[$anterior]['ids'] = [];
$diasTotalFinal=cal_days_in_month(CAL_GREGORIAN, $month, $year);
// Finally I create the initial object and starts the backtracking
$initial_ps = new Briker_vc_PS($dataBaseDecisiones, $diasTotalFinal, $fecha_inicio, $box13, $ucr, $trauma, $numGuardiasAsig);
var_dump( bt($initial_ps)->getReturn() );
I don´t know why this code is not working or if I am using yield the right way.
The problem that is reported happens because of the last line in your code:
bt($initial_ps)->getReturn();
When bt executes the else part it performs a recursive search until there is a return, and then it yields that value. But that does not finish the iterator's results and this yielded value is not considered the iterator's return value. So getReturn() triggers the exception you got.
You don't explain what you intend to get as output in that var_dump. If you want to output all the yielded results, then collect all those results first, for instance with iterator_to_array:
$iter = bt($initial_ps);
print_r(iterator_to_array($iter));
And only then you can execute:
print_r($iter->getReturn());
Please apologyze my English.
I'm developing a kind of sitemap.xml system for my website to include products to my database from external websites, like Google did with his "Spiders", I just developed this whole script to verify if an specific sitemap.xml contains every required tags, and It works: If any tag is missing, the script returns an error, but if all "products" has the required tags, the script returns a success message.
But I only have one problem: if the xml external file has any error like a missing "close" tags, the script stop working and returns an error.
I need to verify the if the external xml file contais any error, and then proceed with the rest of the code that I wrote, if the result is "NO".
this is my developed script:
<?
$sitemap = htmlspecialchars(addslashes(stripslashes(strip_tags(trim($_POST['sitemap'])))));
$ref = htmlspecialchars(addslashes(stripslashes(strip_tags(trim($_POST['ver_id'])))));
error_reporting(E_ALL);
ini_set('display_errors', '1');
session_start();
include dirname(dirname(__FILE__))."/connectdb.php";
$query = "SELECT * FROM website WHERE `ver_id` = '$ref'";
$result = $mysqli->query($query);
/* array asociativo */
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
$url = $row['url'];
$long_url = $url.'/'.$sitemap;
?>
<?php
$total = 0;
$xml=simplexml_load_file("$long_url") or die("Error: Cannot create object");
$count = $xml->count();
foreach($xml->children() as $producto) {
$id = $producto->id;
$titulo = $producto->titulo;
$descripcion = $producto->descripcion;
$fotografia = $producto->fotografia;
$precio = $producto->precio;
$costo = $producto->costo;
$horario = $producto->horario;
$tiempo = $producto->tiempo;
$cobertura = $producto->cobertura;
$keywords = $producto->keywords;
$destacar = $producto->destacar;
$delivery = $producto->delivery;
if (!empty($id) && !empty($titulo) && !empty($descripcion) && !empty($fotografia) && !empty($precio) && !empty($costo) && !empty($horario) && !empty($tiempo) && !empty($cobertura) && !empty($keywords) && !empty($destacar) && !empty($delivery)) {
$total = $total + 1; } else { $total = $total - 1; }
}
if($total < $count){ header("Location:/user/sitio.php?id=$ref&mensaje=1"); } else
if($total == $count){
$query = "UPDATE website SET sitemap='$sitemap',sitemap_status='active' WHERE ver_id='$ref'";
$result = $mysqli->query($query);
header("Location:/user/sitio.php?id=$ref&mensaje=2");
}
?>
Solved with this simple script!
<?
$dom = new DOMDocument;
$dom->Load($long_url);
if ($dom->validate()) {
echo "Valid File";
} else { echo "Invalid File"; }
?>
thanks to everyone.
I have a php which will include my datas inside my database.
But in my page I have a div which can be replicated, so I send this informations into an array (imploded with a "#!#" to avoid any kind of wrong explode when I insert it on my database).
My problem is that if the user doesn't insert anything on the first div content fields I shall not do the insert, and it still does.
if ($_GET['action_ent'] != "#!##!##!#")
{
$myInputs = $_GET['action_ent'];
foreach ($myInputs as $eachInput)
{
$valores = $eachInput;
print_r($valores);
$dummy = explode('#!#', $valores);
$acao = $dummy[0];
$resp_acao = $dummy[1];
$inic_plan_acao = $dummy[2];
$fim_plan_acao = $dummy[3];
$inicio_acc = explode("/", $inic_plan_acao);
$fim_acc = explode("/", $fim_plan_acao);
$inicio_action = $inicio_acc[2]."-".$inicio_acc[1]."-".$inicio_acc[0];
$fim_action = $fim_acc[2]."-".$fim_acc[1]."-".$fim_acc[0];
$result2 = mysql_query("INSERT INTO `demv3`.`entraves_action` (`action_id`, `ent_id`, `resp_ent`, `data_fim`,`action_desc`,`action_resp`,`action_comeco`,`action_fim`) VALUES ('0', '$ent_id', '$resp_ent', '$data_fim', '$acao', '$resp_acao', '$inicio_action', '$fim_action')");
}
}
else
{
echo "NOTHING";
}
Try checking the first item in the foreach:
if ($_GET['action_ent'] != "#!##!##!#")
{
$myInputs = $_GET['action_ent'];
foreach ($myInputs as $eachInput)
{
if(empty($eachInput)) {
echo 'NOTHING';
break;
}
$valores = $eachInput;
print_r($valores);
$dummy = explode('#!#', $valores);
$acao = $dummy[0];
$resp_acao = $dummy[1];
$inic_plan_acao = $dummy[2];
$fim_plan_acao = $dummy[3];
$inicio_acc = explode("/", $inic_plan_acao);
$fim_acc = explode("/", $fim_plan_acao);
$inicio_action = $inicio_acc[2]."-".$inicio_acc[1]."-".$inicio_acc[0];
$fim_action = $fim_acc[2]."-".$fim_acc[1]."-".$fim_acc[0];
$result2 = mysql_query("INSERT INTO `demv3`.`entraves_action` (`action_id`, `ent_id`, `resp_ent`, `data_fim`,`action_desc`,`action_resp`,`action_comeco`,`action_fim`) VALUES ('0', '$ent_id', '$resp_ent', '$data_fim', '$acao', '$resp_acao', '$inicio_action', '$fim_action')");
}
}
else
{
echo "NOTHING";
}
Just be aware that if any other input besides the first one is empty it will break the loop. In order to avoid major changes in your logic you can resolve this with a counter or a boolean flag:
if(empty($eachInput) && $counter == 0) {
echo 'NOTHING';
break;
}
Here is my code for the function
function multiple_delete($checkbox, $table = 0, $url = 0, $picture1 = 0, $picture2 = 0, $picture3 = 0){
echo $count = count($checkbox);
for( $j=0;$j<$count;$j++)
{
$delete_id = $checkbox[$j];
$query = "SELECT * FROM $table WHERE id = '$delete_id'";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
if( $picture1 !== 0 && $picture2 !== 0 && $picture3 !== 0)
{
$pic_1 = $picture1;
$pic_2 = $picture2;
$pic_3 = $picture3;
unlink($pic_1);
unlink($pic_2);
unlink($pic_3);
continue;
}
if( $picture1 !== 0 && $picture2 !== 0 && $picture3 == 0 )
{
$pic_1 = $picture1;
$pic_2 = $picture2;
unlink($pic_1);
unlink($pic_2);
continue;
}
}
for($i=0;$i<$count;$i++) {
$del_id = $checkbox[$i];
$sql = "DELETE FROM $table WHERE id='$del_id'";
$result_delete_data = mysql_query($sql);
}
alert('Deleted Successfully');
redirect_url($url);
return true;
}
My Problem is when i call the function using the following code.
#multiple_delete($_POST['checkbox'], 'news', 'news.php', '$row[\'pic_title\']', '$row[\'pic_brief\']', '$row[\'pic_detail\']');
the three array variables $row['pic_title'], $row['pic_brief'], $row['pic_detail'] , does not parse as the value in the function in first for loop, instead it just print the string and hence is not able to fetch the value stored in the database. for example
in the first if condition i have defined 3 variables,
$pic_1 = $picture1;
$pic_2 = $picture2;
$pic_3 = $picture3;
$picture1, $picture2, and $picture3 holds the value that i declared in the function , now when i do something like this echo $pic_1 = $picture1; it prints $row['pic_title'] the exact value which i declared in the function instead of parsing the value which is actually upload/news/title/pic_title1.jpg i tried testing it like this, instead of declaring the value in the defined function i actually just changed the value of the three variables to
$pic_1 = $row['pic_title'];
$pic_2 = $row['pic_brief'];
$pic_3 = $row['pic_detail'];
this works very fine without any problem. why is that variable $picture1 which holds the value $row['pic_title']; refuses to parse it and force it to just print the string while if i change it manually it works? where i am going wrong?
apart from the last three parameters i dont have any problem parsing the first three parameters it works perfectly fine i have tested it in many ways. the only problem i am facing is of the last three parameters
Edit : i tried double quotes, single quotes, and single quotes with double quote with the combination of concatenation operator. without quotes. nothing works.
P.S : thanks in advance
Try this:
function multiple_delete($checkbox, $table, $url, $picture1, $picture2, $picture3){
echo $count = count($checkbox);
for($j=0; $j<$count; $j++)
{
$delete_id = $checkbox[$j];
$query = "SELECT * FROM $table WHERE id = '$delete_id'";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
$pic1 = $row[$picture1];
$pic2 = $row[$picture2];
$pic3 = $row[$picture3];
if(!empty($pic1) && !empty($pic2) && !empty($pic3))
{
unlink($pic1);
unlink($pic2);
unlink($pic3);
}
else if(!empty($pic1) && !empty($pic2))
{
unlink($pic1);
unlink($pic2);
}
$sql = "DELETE FROM $table WHERE id='$delete_id'";
$result_delete_data = mysql_query($sql);
}
// this is javascript, not php
// alert('Deleted Successfully');
redirect_url($url);
return true;
}
Call the function like this:
multiple_delete($_POST['checkbox_name'], 'table_name', 'redirect_url', 'column_name_pic_1', 'column_name_pic_2', 'column_name_pic_3');
get rid of the apostrophes around your variable names in the function call, ie try
, $row[\'pic_title\'],
instead of
, '$row[\'pic_title\']',
I got the solution for this problem. in case it can benefit anyone here is the link to the solution.
How do i parse the the value from a string in the function call?