I want to run this code :
if ($_GET['CHOOSE'] == 1)
{
$field = " 'col1' ";
}
else
{
$field = " 'col2 ' ";
}
echo mysql_result($result,0,$field);
unfortunately I got false ??
Try this
if ($_GET['CHOOSE'] == 1)
{
$field = "col1";
}
else
{
$field = "col2";
}
echo mysql_result($result,0,$field);
Related
I'm using php CRM that the following code exports the list of all users in database (this list is shown by admin users)
foreach ($rResult as $aRow) {
$row = array();
for ($i = 0; $i < count($aColumns); $i++) {
if (strpos($aColumns[$i], 'as') !== false && !isset($aRow[$aColumns[$i]])) {
$_data = $aRow[strafter($aColumns[$i], 'as ')];
} else {
$_data = $aRow[$aColumns[$i]];
}
if ($aColumns[$i] == 'last_login') {
if ($_data != null) {
$_data = time_ago($_data);
} else {
$_data = 'Never';
}
} elseif ($aColumns[$i] == 'active') {
$checked = '';
if ($aRow['active'] == 1) {
$checked = 'checked';
}
$_data = '<div class="onoffswitch">
<input type="checkbox" data-switch-url="'.admin_url().'staff/change_staff_status" name="onoffswitch" class="onoffswitch-checkbox" id="c_'.$aRow['staffid'].'" data-id="'.$aRow['staffid'].'" ' . $checked . '>
<label class="onoffswitch-label" for="c_'.$aRow['staffid'].'"></label>
</div>';
// For exporting
$_data .= '<span class="hide">' . ($checked == 'checked' ? _l('is_active_export') : _l('is_not_active_export')) . '</span>';
} elseif ($aColumns[$i] == 'firstname') {
$_data = '<a href="' . admin_url('staff/profile/' . $aRow['staffid']) . '">' . staff_profile_image($aRow['staffid'], array(
'staff-profile-image-small'
)) . '</a>';
$_data .= ' ' . $aRow['firstname'] . ' ' . $aRow['lastname'] . '';
} elseif ($aColumns[$i] == 'email') {
$_data = '' . $_data . '';
} else {
if (strpos($aColumns[$i], 'date_picker_') !== false) {
$_data = (strpos($_data, ' ') !== false ? _dt($_data) : _d($_data));
}
}
$row[] = $_data;
}
$options = icon_btn('staff/member/' . $aRow['staffid'], 'pencil-square-o');
if (has_permission('staff', '', 'delete') && $output['iTotalRecords'] > 1 && $aRow['staffid'] != get_staff_user_id()) {
$options .= icon_btn('#', 'remove', 'btn-danger', array(
'onclick'=>'delete_staff_member('.$aRow['staffid'].'); return false;',
));
}
$row[] = $options;
$output['aaData'][] = $row;
}
Ther are 5 admin in the database;
I want to hide one user with staffid = 1 as a backdoor.
How can I delete row with this staffid ?
(I'm not familiar with PHP coding)
Thanks
You can add an if() condition like below:-
foreach ($rResult as $aRow) {
if($aRow['staffid'] !=1){
//complete code inside if
}
}
Note:- I assume that $aRow have staffid as an index
I´m trying to do a checkbox in my form but its just returning the last value. What´s wrong here?
if ($type == "w") {
//check buttons
foreach ($values as $indexa => $value) {
$value = trim($value);
echo "<input type=\"checkbox\" name=\"input[$fieldno]\" value=\"$value\" ";
if (isset($input)) {
if ($input[$fieldno] == $value) {
echo " checked";
// var_dump($fieldno); die();
}
}
if ($compulsory == 1) {
echo " class=\"required\"";
}
$label = ($value == 'OTHER') ? 'OUTROS' : $value;
echo " onclick=radio_other($fieldno,\"$value\")> $label<br>";
}
if (strtoupper($value) == "OTHER") {
echo "<input type=\"text\" name=\"other[$fieldno]\" id=\"other[$fieldno]\" style=\"display:none\">";
}
}
Ps: $type == w is a checkbox type.
when I use $_POST, both the if and else statements are executed. But the weird thing is that only the foreach loop is executed and "Flag is 0" is printed to the screen. If I replace $Flag = 1 with $Flag = 0, in the else statement, the loop does not get executed. When I replace "isset($_POST['Back'])" with "1", again the loop does not execute and all is well. So how come both my else and my if statement execute when I use $_POST? Thank you for any input
File #1
$Flag = 0;
if (isset($_POST['Back']))
{ echo "Flag is 0";
$Value = sqlsrv_fetch_array(sqlsrv_query($dbhandle,'SELECT MAX([Protocol Branch]) FROM Import_Trial_Information'),SQLSRV_FETCH_NUMERIC);
$Value = $Value[0];
}
else {$Flag = 1; echo "Flag is 1"; }
if ($Flag)
{
foreach ($Database_Tables AS $Delete)
{
$Query = 'DELETE FROM Import_' . $Delete;
sqlsrv_query($dbhandle,$Query);
if ($Delete == 'Paper_Information') {$Protocol = array('','');}
else {$Protocol = array(',[Protocol Branch]',',1');}
$Query = 'INSERT INTO Import_' . $Delete . '([Paper ID]' . $Protocol[0] . ') VALUES (' . (string)$ID . $Protocol[1] .')';
sqlsrv_query($dbhandle,$Query);
}
$Value = 1;
}
File #2
<div id = "Back_Button">
<form action="Import_Article_Advanced.php" method = "POST"><button name = "Back" ID = "Back" Value = "Back">Return to Previous Page</button></form>
</div>
try this
if (isset($_POST['Back']) OR !empty($_POST['Back']) OR $_POST['Back']!="" )
{ echo "Flag is 0";
$Value = sqlsrv_fetch_array(sqlsrv_query($dbhandle,'SELECT MAX([Protocol Branch]) FROM Import_Trial_Information'),SQLSRV_FETCH_NUMERIC);
$Value = $Value[0];
}
else {$Flag = 1; echo "Flag is 1"; }
$resultUpdate = Nemesis::select("*", $table, "id = '{$id}'");
if (!$resultUpdate) {
self::show_error(QUERY_ERROR);
} elseif ($resultUpdate->num_rows > 0) {
$out .= '<div class="form-desc">' . $formDesc . '</div>';
} else {
self::show_error(QUERY_EMPTY);
}
$array = array_values($array);
print_r($array);
$out .= '<form action="' . $_SERVER['PHP_SELF'] . '?id=' . $id . '&table=' . $table . '" method="post" class="form-horizontal" ' . $formAppend . '>';
while ($row = $resultUpdate->fetch_assoc()) {
foreach ($row as $fieldname => $value) {
if (in_array($fieldname, $array)) {
$out .= generateInputField($fieldname, $value);
}
}
foreach ($row as $fieldname => $value) {
if (in_array($fieldname, $array)) {
$out .= generateTextarea($fieldname, $value, $cke);
}
}
foreach ($row as $fieldname => $value) {
if (in_array($fieldname, $array)) {
$out .= generateImgField($fieldname, $value);
}
}
}
$arr = array("last_modified"=>"input", "published"=>"input", "content"=>"textarea");
echo $automate->createArrayForm('projects', 'update', 'Some form desc', '178514825', $arr, true);
Right now all fields are outputting in every foreach when only inputs should output in the generateInputField section for example. I know this is because I need to check if the fieldtype (input, textarea) key matches with one of the values marked as input or textarea for values of the $fieldname. But I am not sure how.
I am pretty sure I have to filter the array so only values with input go into a separate array like arrayInput in which I can use as the second argument in in_array.
If I understand you and your code correctly...
This code
while ($row = $resultUpdate->fetch_assoc()) {
foreach ($row as $fieldname => $value) {
if (in_array($fieldname, $array)) {
will always return true for all your rows thats why you are getting your current output.
Instead you should be doing this:
while ($row = $resultUpdate->fetch_assoc()) {
foreach ($row as $fieldname => $value) {
if ($fieldname == 'input') {
$out .= generateInputField($fieldname, $value);
} elseif($fieldname == 'textarea') {
$out .= generateTextarea($fieldname, $value, $cke);
} elseif ($fieldname == 'img') {
$out .= generateImgField($fieldname, $value);
}
else{ $out = $out;}
}
}
With alot of help from stackers...
/**
* Create Form With Array
*
* Creates a form based on an array. If $do == update, we match fieldnames with values
*
* #param string $table name of database table
* #param string $do whether the form is an insert or update
* #param string $formDesc form description to be echoed
* #param array $array associative array of type (keys), and fieldnames (values)
* #param bool $markFields whether or not to add headers for inputs, textareas .etc during insert
* #param bool $formBrackets whether or not to prepend and append form brackets
* #return $out html form
*
*/
public function createArrayForm($table, $do, $formDesc = '', $id, $array, $markFields = false, $formBrackets = true) {
if (!isset($table) && !isset($do)) {
self::show_error('One or more parameters are missing in ' . __FUNCTION__);
} elseif ($table == 'update' && !isset($id)) {
self::show_error('For this form to be built, and ID must be set. Missing parameter `ID` in ' . __FUNCTION__);
}
if (!is_array($array)) {
self::show_error('For this form to be built, an array must be given. Missing parameter `array` in ' . __FUNCTION__);
}
$result = array();
// create two dimensional array to preserve keys that
// otherwise would be lost with array_flip
foreach($array as $k => $v) {
if (array_key_exists($v, $result)) {
$result[$v][] = $k;
} else {
$result[$v] = array($k);
}
}
// make sure we do not have any duplicates
$result = super_unique($result);
// we just need the array_values for matching with in_array
// however we do not want to run array_values on null
// so we check to see if the $result is a valid array first
// if not, we just output a blank array so in_array doesn't complain
$arrayInput = is_array($result['input']) ? array_values($result['input']) : array();
$arrayTextarea = is_array($result['textarea']) ? array_values($result['textarea']) : array();
$arrayImages = is_array($result['images']) ? array_values($result['images']) : array();
$out = $formBrackets == true ? '<form action="' . $_SERVER['PHP_SELF'] . '?id=' . $id . '&table=' . $table . '" method="post" class="form-horizontal" ' . $formAppend . '>' : NULL;
if($do == 'insert') {
$out .= isset($formDesc) ? '<div class="form-desc">' . $formDesc . '</div>' : NULL;
$out .= $markFields && in_array('input', $array) ? '<h3>Input Fields</h3>' : NULL;
foreach ($arrayInput as $fieldname) {
$out .= generateInputField($fieldname);
}
$out .= $markFields && in_array('textarea', $array) ? '<h3>Content Fields</h3>' : NULL;
foreach ($arrayTextarea as $fieldname) {
$out .= generateTextarea($fieldname, $cke);
}
$out .= $markFields && in_array('image', $array) ? '<h3>Images Fields</h3>' : NULL;
foreach ($arrayImages as $fieldname) {
$out .= generateImgField($fieldname);
}
} elseif ($do == 'update') {
$resultUpdate = Nemesis::select("*", $table, "id = '{$id}'");
if (!$resultUpdate) {
self::show_error(QUERY_ERROR);
} elseif ($resultUpdate->num_rows > 0) {
$out .= isset($formDesc) ? '<div class="form-desc">' . $formDesc . '</div>' : NULL;
} else {
self::show_error(QUERY_EMPTY);
}
while ($row = $resultUpdate->fetch_assoc()) {
foreach ($row as $fieldname => $value) {
if (in_array($fieldname, $arrayInput)) {
$out .= generateInputField($fieldname, $value);
}
}
foreach ($row as $fieldname => $value) {
if (in_array($fieldname, $arrayTextarea)) {
$out .= generateTextarea($fieldname, $value, $cke);
}
}
foreach ($row as $fieldname => $value) {
if (in_array($fieldname, $arrayImages)) {
$out .= generateImgField($fieldname, $value);
}
}
}
} else {
self::show_error('Missing array or `do` argument in function ' . __FUNCTION__);
}
$out .= form_hidden('user_data', '1');
$out .= form_hidden('id', $do == 'update' ? $id : self::generateID());
$out .= $formBrackets == true ? form_close() : NULL;
return $out;
}
Usage:
$arr = array("last_modified"=>"input", "published"=>"input", "project_content"=>"textarea", "project_content"=>"textarea");
echo $automate->createArrayForm('projects', 'insert', 'Some form desc', '123', $arr, true);
echo $automate->createArrayForm('projects', 'update', 'Some form desc', '178514825', $arr, true);
I have a function which performs a foreach loop on an array from a database.
see foreach ($teamarray AS $key => $value){$teamgo .= $value[1]." ".$value[2]."<br/>";
Problem is, sometimes there may be no data set, which throws an error when the loop hits that field.
How can i catch/suppress this error?
function GetUnsubmitted($coach){
$push .= "<div id=unsubmitted><h2>Check which event/teams you want to process and click submit</h2>";
$push .= "<form action=\"submit.php\" method=POST>";
$result = mysql_query("SELECT * FROM `ptable` WHERE coach = '$_SESSION[username]' AND status = '1' ORDER BY status ASC") or trigger_error(mysql_error());
while($row = mysql_fetch_array($result)){
foreach($row AS $key => $value) { $row[$key] = stripslashes($value); }
$id = $row['id'];
$teampre = $row['team'];
$eventpre = $row['event'];
$statuspre = $row['status'];
$eventarray = DecodeEvent($eventpre);
$event = $eventarray[0];
$cat = $eventarray[1];
$subcat = $eventarray[2];
$division = $eventarray[3];
$type = $eventarray[4];
$teamarray = DecodeTeam($teampre);
$price = GetPrice($type, "nat");
$teamcount = count($teamarray);
$total = $price * $teamcount;
$teamgo = "";
foreach ($teamarray AS $key => $value){
$teamgo .= $value[1]." ".$value[2]."<br/>";
if($statuspre == "1"){
$statuscolor = "#FFCC99";
$statusmsg = "unsubmitted <a href=delsub.php?id=$id onClick=\"return confirm('Are you sure you want to delete this submission?');\"><img src=images/del.png border=0 />";
} elseif($statuspre == "2"){
$statuscolor = "#FFCC66";
$statusmsg = "awaiting confirmation";
} elseif($statuspre == "3"){
$statuscolor = "#66CC66";
$statusmsg = "confirmed";
}
}
$push .= "<div id=submission><div id=event style=\"background-color:$statuscolor;\"><h1>$event</h1><span id=status>$statusmsg</span></div><div id=subinfo><span id=dropdown><img src=images/expand.png border=0></span><h2>$cat >> $subcat >> $division >> $type</h2> <div id=team style=\"display:none;\">$teamgo<br />$price - $total<div id=controls></div></div></div></div>";
$pid .= $id;
$rtotal .= "$total,";
}
$stotal = explode(",", $rtotal);
$gtotal = array_sum($stotal);
$push .= "<div style=\"text-align:right;\"><div id=total>Total - <em>$gtotal</em></div><br><input type=image src=images/paynow.png alt=\"Pay Now\"></form> <a href=submit2.php?$pid&$pidarray><img src=images/mailfax.png width=138px height=41px border=0></a></div></div>";
return $push;
}
If possible id like it to say "no team selected" and stop.
You can write so:
foreach ((array)$teamarray as $key => $value) {
$teamgo .= $value[1] . " " . $value[2] . "<br/>";
//...
}
foreach expects array. So the really correct way is to ensure that you deal with array before try to iterate, like this:
if (is_array($teamarray) && count($teamarray)) {
foreach ((array)$teamarray as $key => $value) {
$teamgo .= $value[1] . " " . $value[2] . "<br/>";
//...
}
}
You also can check is_iterable since PHP 7.1.
if ($array) {
foreach ($array as $k => $v) {
...
}
} else {
echo 'No team selected';
// exit from loop
}
Your exit from loop will be a "return", or a "break n" (n is the levels to break for) or continue... it depends on your logic.
if ($value !== null && count($value) >= 3) {
$teamgo .= $value[1] . $value[2]
}
<insert puzzled smiley here>
foreach($row AS $key => $value) {
if ($value) {
$row[$key] = stripslashes($value);
}
}
And:
foreach ($teamarray AS $key => $value){
if ($value && sizeof($value) > 2) {
$teamgo .= $value[1] . $value[2]
}
}
Is this it?
Just do a test if $teamarray actually is an array:
if (is_array($teamarray)) {
foreach ($teamarray as $key => $value) {
// …
}
}
Or you could do:
$teamarray = isset($teamarray) ? $teamarray : array();
Just prior to the loop in a nice tidy line, and it would ensure that you have the variable set to an empty array which would cause it to skip the foreach().