Php keep checkboxes checked after form error - checkbox

How can i keep the selected checkboxes checked, after the form submit on error? Now, i get this error message: Warning: in_array() expects parameter 2 to be array, string given in
Thanks!
function runsql_array($sql)
{
global $kapcs;
$res = mysqli_query($kapcs , $sql) or die(mysqli_error( $kapcs));
if (mysqli_num_rows($res) == 0)
{
return array();
}
else
{
$out = array();
while ($a = mysqli_fetch_assoc($res))
{
$out[] = $a;
}
return $out;
}
}
<td>
<?php
$ertek = isset($_POST["termek_tul_tipusok"]) ? $_POST["termek_tul_tipusok"] : '' ;
$values = runsql_array("SELECT termek_tipus_id, termek_tipus_nev FROM termek_tipusok WHERE termek_tipus_status = 1
ORDER BY termek_tipus_nev ASC");
foreach($values as $val=>$szoveg)
{
$checked = in_array($val, $ertek) ? ' checked ' : '' ;
echo '<div style="margin:4px 0;"><label style="cursor:pointer;" for="tulajdonsag-'.$val.'">';
echo '<input id="tulajdonsag-'.$val.'" type="checkbox" name="termek_tul_tipusok[]" '.$checked.' value="'.$val.'" />';
echo $szoveg['termek_tipus_nev'];
echo '</label></div>';
}
?>
</td>

the line
$ertek = isset($_POST["termek_tul_tipusok"]) ? $_POST["termek_tul_tipusok"] : '' ;
defines $ertek. And in the case that the post dosnt exist its defined as an empty string. You should use an empty Array.
$ertek = isset($_POST["termek_tul_tipusok"]) ? $_POST["termek_tul_tipusok"] : array() ;

Related

How to put a database into an array

I finally succeeded in making an image carousel by using php.
The code below works, but there are no images in it.
Now I am trying to make this array to get data from a Mysql database.
Could you show me an example of how do I do it?
<?php
//MySQL database connection
$mysqli = new mysqli('localhost', 'root', '', 'webshop');
$SQL = "SELECT image FROM productlist LIMIT 5";
$result = $mysqli->query($SQL);
$array = array(
0 => "picture1.jpg",
1 => "picture2.jpg",
2 => "picture3.jpg",
3 => "picture4.jpg",
4 => "picture5.jpg",
5 => "kalle6.jpg",
);
//Goes to previous page when clicking on prev
$index = $_GET['start'];
if ($index > 0) {
echo ' prev ';
} else {
echo ' prev ';
}
//Display 3 images
$show_img = 3;
$num_img = 0;
for($i = $_GET['start']; $i<count($array) && $num_img < $show_img; $i++) {
$num_img++;
echo "<img src=".$array[$i]."/>\n";
}
for($i=$num_img; $i<$show_img;$i++) {
echo "<img src=".(count($array) - 1)."/>\n";
}
//Goes to next page when clicking on next
if ($index < count($array) - 1) {
echo ' next ';
} else {
echo ' next ';
}
?>
You should have a look at this: http://php.net/manual/en/mysqli-result.fetch-array.php
/* numeric array */
/* $row is your $array */
$row = $result->fetch_array(MYSQLI_NUM);
echo "<pre>";
print_r($row);
echo "<pre>";
This should help you get the result you want

Undefined offset: 1 twitch channel grab

I get this on my website:
Notice: Undefined offset: 1 in ...
Here is the full code, bolded is the part it refers to i think, basically this scripts should grab list of my channels from ther DB and then display info from the twitch:
<?php
defined('_JEXEC') or die('Direct access to this location is not allowed.');
$userList = $params->get('userlist');
$usersArray = explode(',', $userList);
$userGrab = "http://api.justin.tv/api/stream/list.json?channel=";
$checkedOnline = array ();
foreach($usersArray as $i =>$value){
$userGrab .= ",";
$userGrab .= $value;
}
unset($value);
$json_file = file_get_contents($userGrab, 0, null, null);
$json_array = json_decode($json_file, true);
//used to be $viewer = $json_array[$i]['stream_count'];
**foreach($usersArray as $i =>$value){
$title = $json_array[$i]['channel']['channel_url'];
$array = explode('/', $title);
$member = end($array);
$name = $json_array[$i]['name'];
$game = $json_array[$i]['meta_game'];
$viewer = $json_array[$i]['channel_count'];
$topic = $json_array[$i]['title'];
onlinecheck($member, $viewer, $topic, $game);
$checkedOnline[] = signin($member);
}**
unset($value);
unset($i);
function onlinecheck($online, $viewers, $topic, $game)
{
if ($game == "Counter-Strike: Global Offensive")
{
$igra = "csgo12.jpg";
}
else{
$igra = "online.png";
}
if ($online != null)
{
echo ' <img src="./modules/mod_twitchlist/tmpl/'.$igra.'">';
echo ' <strong>'.$online.'</strong>';
echo ' (' .$viewers.') - ';
echo '<strong>'.$topic.'</strong> </br>';
}
}
function signin($person){
if($person != null){
return $person;
}
else{
return null;
}
}
?>
<!-- <hr> -->
<?php
foreach ($usersArray as $i => $value1) {
foreach($checkedOnline as $ii => $value2){
if($value1 == $value2){
unset($usersArray[$i]);
}
}
}
$broj1 = count($usersArray); //neaktivni korisnici
$broj2 = count($checkedOnline); //ukupno streamova
if ($broj1 == $broj2){
echo '<strong><center>Nijedan stream nije aktivan trenutno!</center></strong>';
}
?>
Any hints?

JRequest::getVar is keeping previous values even after refreshing

I am writing a mail function as a module in joomla 3. e mail works fine, but when i reload the page and insert a different email and send, but it seemed to return the previous email by JRequest::getVar function. Is there a way to solve this issue? thanks in advance..
this is the code i used:
<?php
defined('_JEXEC') or die('Direct Access to this location is not allowed.');
require_once(dirname(__FILE__) . DS . 'helper.php');
//declaration
$input = JFactory::getApplication()->input;
$form_send = $input->get('form_send', 'notsend');
$fanme = $input->get('firstName');
$lname = $input->get('lastinput');
$email = $input->get('email', 0 , 'STRING');
$mail=false;
$emailexist=false;
echo '<script>
var php_var = "chk is first:'.$email.'";
alert(php_var);
</script>';
switch ($form_send) {
case 'send':
if ((is_null($fanme) || is_null($lname) || is_null($email)) || (!filter_var($email, FILTER_VALIDATE_EMAIL))) {
echo '<div> Fields are empty or not valid. <br></div>';
} else {
$mail = ModLittleContactHelper::SendMail($email, $fanme, $lname);
echo '<script>
var php_var = "chk when mail sending:'.$email.'";
alert(php_var);
</script>';
$input = JFactory::getApplication();//i have tried $app also
$input ->setUserState('mod_mycontact.email', null);
}
//echo $respond
if (!$mail) {
echo 'Error sending email:';
require(JModuleHelper::getLayoutPath('mod_myecontact', 'default_tmpl'));
}else{
require(JModuleHelper::getLayoutPath('mod_mycontact', 'sendok_tmpl'));
break;
}
default:
require(JModuleHelper::getLayoutPath('mod_littlecontact', 'default_tmpl'));
unset($var);
}
?>
#Mario this is the helper code:
class ModLittleContactHelper{
public function SendMail($email, $fname, $lname) {
$body = "<p style='font-family:arial;font-size:20px;'>Hi " . $fname . " " . $lname . ",</p>";
$body.="<p style='font-family:arial;font-size:20px;'>Welcome to Crowd Logistics! Please verify your email address below.</p><br/><br/>";
$body.= "<hr><br/>";
$body.= "<p style='align:center;background-color:#40B3DF;font-family:arial;color:#FFFFFF;font-size:20px;'><a href='http://suriyaarachchi.com/crowdlogistics/index.php?option=com_content&view=article&id=192' target='_blank'>Verify " . $email . "</a></p>";
$body.= "<br/><hr><br/>";
$body.="<p style='text-align:right;font-family:arial;font-size:20px;'>Or, paste this link into your browser:<br/>";
$body.= "http://crowdlogistics/index.php?option=com_content&view=article&id=192<br/><br/>";
$body.= "Thanks.<br/>";
$body.= "CrowdLogistics</p><br/>";
$mailer = & JFactory::getMailer();
$mailer->setSender('info#crowdlogistics.com');
$mailer->addRecipient($email);
$mailer->setSubject('Mail from CrowdLogistics - Confirm your email');
$mailer->setBody($body);
$mailer->IsHTML(true);
$send = & $mailer->Send();
return $send;
}
Since you're trying to run your code on Joomla 3, there are a few things that are wrong. Below os your code, corrected where I was able to correct it. Now you have to test it in your module environment with the class being instantiated (in other words, test the below code in your module).
<?php
defined('_JEXEC') or die('Direct Access to this location is not allowed.');
require_once(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'helper.php');
//declaration
$doc = JFactory::getDocument();
$app = JFactory::getApplication();
$input = $app->input;
$form_send = $input->get('form_send', 'notsend');
$fanme = $input->get('firstName');
$lname = $input->get('lastinput');
$email = $input->get('email', 0 , 'STRING');
$mail=false;
$emailexist=false;
$doc->addScriptDeclaration('
var php_var = "chk is first:'.$email.'";
alert(php_var);
');
switch ($form_send) {
case 'send':
if ((is_null($fanme) || is_null($lname) || is_null($email)) || (!filter_var($email, FILTER_VALIDATE_EMAIL))) {
echo '<div> Fields are empty or not valid. <br></div>';
} else {
$mail = ModLittleContactHelper::SendMail($email, $fanme, $lname);
$doc->addScriptDeclaration('
var php_var = "chk when mail sending:'.$email.'";
alert(php_var);');
$app->setUserState('mod_littlecontact.email', null);
}
//echo $respond
if (!$mail) {
echo 'Error sending email:';
require(JModuleHelper::getLayoutPath('mod_littlecontact', 'default_tmpl'));
break;
}else{
require(JModuleHelper::getLayoutPath('mod_littlecontact', 'sendok_tmpl'));
break;
}
default:
require(JModuleHelper::getLayoutPath('mod_littlecontact', 'default_tmpl'));
unset($var);
}
?>
First, JRequest class is deprecated in J3. You should use JInput:
$input = JFactory::getApplication()->input;
$your_var = $input->get('your_var');
Then, regarding the email, you probably need to unset the session variables when the success is achieved (mail sent), or in other words, when you don't need them any longer.
$app = JFactory::getApplication();
// your_var is the variable you want to unset
$app->setUserState('mod_your_module.your_var', null);
Hope it helps
you can use this code
$email = $input->get('email', 0 , 'STRING','');
4th argument for the default value,

Expanding Rows for Unique Checkboxes

I was just recently given a project for my job to write a script that compares two mysql databases and print out information into an html table. Currently, I am trying to insert a checkbox by each individual's name and when selected, rows pertaining to that individual will expand underneath the person's name. I am combining javascript into my script to do this, although I really have no experience is it. The problem I am having is that when any checkbox is selected, all the rows for each individual is expanding instead of the rows pertaining only to the one individual selected.
Here is my code so far:
PHP Code:
<?php
$link = mysql_connect ($server = "harris.lib.fit.edu", $username = "", $password = "") or die(mysql_error());
$db = mysql_select_db ("library-test") or die(mysql_error());
$ids = mysql_query("SELECT * FROM `ifc_studylog`") or die(mysql_error()); //not single quotes (tilda apostrophy)
$x=0;
$n=0;
while($row = mysql_fetch_array( $ids ))
{
$tracksid1[$x] = $row['fitID'];
$checkin[$x] = $row['checkin'];
$checkout[$x] = $row['checkout'];
$n++;
$x++;
}
$names = mysql_query("SELECT * FROM `ifc_users`") or die(mysql_error()); //not single quotes (tilda apostrophy)
$x=0;
while($row = mysql_fetch_array( $names ))
{
$tracksnamefirst[$x] = $row['firstName'];
$tracksnamesecond[$x] = $row['lastname'];
$tracksid2[$x] = $row['fitID'];
$tracksuser[$x] = $row['tracks'];
$x++;
}
$x=0;
foreach($tracksid2 as $comparename)
{
$chk = strval($x);
?>
JS Code:
$(window).load(function() {
$('.varx').click(function() {
$('.text').toggle(this.checked);
});
});​
PHP Code:
<?php
echo '<td><input id = "<?=$chk?>" type="checkbox" class="varx" /></td>';
echo '<td align="center">'.$comparename.'</td>';
echo'<td align="center">'.$tracksnamefirst[$x].'</td>';
echo'<td align="center">'.$tracksnamesecond[$x].'</td>';
$z=0;
foreach($tracksid1 as $compareid)
{
$HH=0;
$MM =0;
$SS =0;
if($compareid == $comparename)// && $tracks==$tracksuser[$x])
{
$SS = sprintf("%02s",(($checkout[$z]-$checkin[$z])%60));
$MM = sprintf("%02s",(($checkout[$z]-$checkin[$z])/60 %60));
$HH = sprintf("%02s",(($checkout[$z]-$checkin[$z])/3600 %24));
// echo'<td align="center">'.$HH.':'.$MM.':'.$SS.'</td>';
echo '</tr>';
echo '<tr>';
echo "<td id='txt' class='text' align='center' colspan='2' style='display:none'></td>";
echo "<td id='txt' class='text' align='center' style='display:none'>".$checkin[$z]."</td>";
echo '</tr>';
}
echo '<tr>';
$z++;
echo '</tr>';
}
$x++;
}
}
?>
Any help is appreciated and apologies if I am too vague on the subject. The username and password have been left out for security reasons.

Drupal 7.14: Preprocess search block form gives me a blank form to render in $search_form

I've started working on a theme from scratch, I've tried to replace the title of the textfield but when imploding the search variable into search_form, the result is blank. Any error that I could be missing?
`function mytheme_preprocess_search_block_form(&$form) {
$form['search'] = array();
$hidden = array();
// Provide variables named after form keys so themers can print each element independently.
foreach (element_children($form['form']) as $key) {
echo $key;
$type = $form['form'][$key]['#type'];
echo '__'.$type.'<br />';
if ($type == 'hidden' || $type == 'token') {
$hidden[] = drupal_render($form['form'][$key]);
}
else {
if($key == 'search_block_form')
{
$form['form'][$key]['#title'] = t('');
//$form['search'][$key] = drupal_render($form['form'][$key]);
}
else
{
$form['search'][$key] = drupal_render($form['form'][$key]);
}
}
}
// Hidden form elements have no value to themers. No need for separation.
$form['search']['hidden'] = implode($hidden);
// Collect all form elements to make it easier to print the whole form.
$form['search_form'] = implode($form['search']);
var_dump($form);
exit;
}`
Refer to http://drupal.org/node/1092122:
<?php
/**
* Implements hook_theme().
*/
function MYMODULE_theme($existing, $type, $theme, $path) {
return array(
'article_node_form' => array(
'render element' => 'form',
'template' => 'article-node-form',
// this will set to module/theme path by default:
'path' => drupal_get_path('module', 'MYMODULE'),
),
);
}
?>
<?php
/**
* Preprocessor for theme('article_node_form').
*/
function template_preprocess_article_node_form(&$variables) {
// nodeformcols is an alternative for this solution.
if (!module_exists('nodeformcols')) {
$variables['sidebar'] = array(); // Put taxonomy fields in sidebar.
$variables['sidebar'][] = $variables['form']['field_tags'];
hide($variables['form']['field_tags']);
// Extract the form buttons, and put them in independent variable.
$variables['buttons'] = $variables['form']['actions'];
hide($variables['form']['actions']);
}
}
?>
article-node-form.tpl.php
<?php echo drupal_render_children($form)?>

Resources