PHP - Explode or Implode Values into an Array? - php

I'm creating a simple survey and I want the values in the column to be just (1) one row and separated with "|". But the only problem is, how do I save those values that I've got from the $_POST into an array on my database? For example:
Male|Employed|Married| instead of this...
<?php
$cnt = 1; // VARIABLE FOR QUESTIONS //
$query = "SELECT * FROM questions";
$result = mysqli_query($connection, $query);
while ($row = mysqli_fetch_object($result))
{
$choices = explode ("|", $row->choices);
if(isset($_POST['submit_post']))
{ // eq - radio button name (choices) for $cnt - question # //
$choice = $_POST["eq$cnt"]; // What to do in this $_POST part? //
$query = "INSERT INTO users(answers)";
$query .= "VALUES ('{$choice}')";
$create_post_query = mysqli_query($connection, $query);
}
?>
<form action="" method="post">
<?php
if($row->num ==0)
{
$num=" ";
} else
{
$num=$row->num.". ";
}
?>
<p id="eqIdentify_<?php echo $cnt ?>"><strong><?php echo $num; echo $row->questions; ?></strong> <?php ?> <?php echo $cnt; ?>
<?php
// VARIABLE FOR CHOICES //
for($a=0;$a<count($choices);$a++)
{
?>
<br/><label><input type="radio" name="eq<?php echo $cnt;?>" value="<?php echo $choices[$a] ?>" /><?php echo $choices[$a]?></label>
<?php
}
?>
<?php
$cnt = $cnt + 1;
}
?>
<input type="submit" name="submit_post">
</form>

change your table structure so you have a field for each of the questions.
like
ID Question1 Question2
and then change your insert query such
INSERT INTO `answers`( `question1`, `question2`, `question3`, `question4`) VALUES ([value-2],[value-3],[value-4],[value-5])
But please please look in to PDO and prepared query's

Related

Explode Checkbox looping php

I want explode data from table "school_minat"
into checklist in checbox looping table from "dayaminat".
I already try, but my checklist show only one. whereas my data minat_id in table school_minat 4 data = smk2,smk3,smk1,smk4
<center>
<?php $sql = "select * from dayaminat";
$rs = mysql_query($sql);
$i = 0;
while($row = mysql_fetch_array($rs)){ // Looping data from Table "dayaminat"
?>
<input name='minat[]'
<?php
$values = $result['minat_id']; // Data "minat_id" already Selected in Database table "school_minat"
$array_of_values = explode(",", $values); //Explode Data "Minat" already Selected in Database table "school_minat"
if (in_array($row['minat_id'],$array_of_values)) {
echo 'checked="checked"';
}
?>
value='<?php echo $row['minat_id']?>' type='checkbox'> <?php echo $row['minat'] ?>
<?php
$i ++;
}?>
</center>
Help me. Thank's :)
You must loop in your $array_of_values
<center>
<?php $sql = "select * from dayaminat";
$rs = mysql_query($sql);
while($row = mysql_fetch_array($rs)){ // Looping data from Table "dayaminat"
$values = $result['minat_id']; // Data "minat_id" already Selected in Database table "school_minat"
$array_of_values = explode(",", $values); //Explode Data "Minat" already Selected in Database table "school_minat"
for($i = 0; $i < count($array_of_values); $i++) {
echo "<input name='minat[]' ";
if (in_array($row['minat_id'], $array_of_values)) {
echo 'checked="checked"';
}
?>
value='<?php echo $array_of_values[$i]; ?>' type='checkbox'> <?php echo $array_of_values[$i]; ?>
<?php
}
}?>
</center>
You are looping only through the database row. As there is just 1 row you get only 1 result.
So try looping through the array! Probably using foreach loop..
<center>
<?php $sql = "select * from dayaminat";
$rs = mysql_query($sql);
$i = 0;
while($row = mysql_fetch_array($rs)){ // Looping data from Table "dayaminat"
$values = $result['minat_id']; // Data "Minat" already Selected in Database table "school_minat"
$array_of_values = explode(",", $values); //Explode Data "Minat" already Selected in Database table "school_minat"?>
foreach ($array_of_values as $arrayItem){
<input name='minat<?php echo $i;?>'
<?php
if (in_array($row['minat_id'],$arrayItem)) {
echo 'checked="checked"';
}
?>
value='<?php echo $arrayItem ?>' type='checkbox'> <?php echo $arrayItem ?>
<?php
$i ++;
}
}?>
</center>

how to access values in jquery muiltiselect through php

I'm using jquery multiselect and in options i'm fetching data from database these are basically available seats in a buss.. when user selected some seats and press the button i'm putting values on $_POST and using update query updating selected seats as reserved please help here is the code
** HTML SELECT tag with jquery and php for fetching data this is working fine **
<form action="" method="post">
<label for="required">Required</label>
<select id="required" multiple="multiple" data-placeholder="Select attendees..." name="required">
<?php
$con = mysql_connect("localhost","root","") or die(mysql_error());
$link = mysql_select_db("bus") or die(mysql_error());
$query = " select seats.seatNo from seats where seats.isactive = 0 and seats.busID = 1";
$result = mysql_query($query);
while($row = mysql_fetch_array($result))
{
$seatNo = $row['seatNo'];
?>
<option> <?php echo $seatNo ?> </option>
<?php } ?>
</select>
And then I'm getting selected seats here and updating the db
<?php
$con;
$link;
if(isset($_POST['submit']))
{
for($i = 0; $i<5; $i++)
{
$selected = $_POST['required'];
}
$insert = " update seats set seats.isactive = 1 where seats.seatNo = $selected and seats.busID = 1";
$q = mysql_query($insert) or die(mysql_error());
if($q)
{
echo " record updated ";
}
else
{
echo " couldn't update ";
}
}
?>

Inserting mysql values from 'submit' button in PHP doesn't work as expect

I have two tables:
'courses' with these fields:COURSE_ID(auto
increment),start_date,end_date,title
'courses_students' with these fields:ID(auto
increment),COURSE_ID,STUDENT_ID.
I want to insert some values in my mysql table called "courses_students" from my other table called "courses".
Users can see in a page the data from 'courses'(courses names,starting dates,ending dates) and they must select which course they want to attend,by clicking the button 'attent course'.
Everytime someone clicks the submit button,the values are inserted in courses_students table,but not correctly.The problem is that everytime,the COURSE_ID from 'courses_students' has the value of the last COURSE_ID from 'courses'.And,other strange problem is that the values are inserted twice,everytime.
This is the code:
<?php
$link = mysql_connect('localhost','root','');
if(!$link){
die('Could not connect: '.mysql_error());
}
mysql_selectdb("db");
?>
<ul>
<?php
$sql = "SELECT * FROM courses";
$result = mysql_query($sql);
while($file = mysql_fetch_array($result)){
echo '<ul>';
echo '<li>';
$STUDENT_ID = $_SESSION['ID'];
$COURSE_ID = $file['COURSE_ID']; //**It dislays the CORRECT ID for each course!**
echo 'the course id: ' .$COURSE_ID;
echo 'course name: ' .$file['title'];
echo 'Starting: ' .$file['start_date'];
echo ' ending: '.$file['end_date'];
echo '<form action="lista_cursuri.php" method="post"> <input type="submit" name="submit" value="attent course!"> </form>';
echo '</li>';
}
?>
</ul>
<?php
if(isset($_POST['submit'])){
$sql1 = "INSERT INTO `courses_students` (COURSE_ID,STUDENT_ID) VALUES ($COURSE_ID,$STUDENT_ID)";
$result = mysql_query($sql1);
}
?>
I can't manage to see where the problem is.Maybe this is not the correct procedure.
Salut
Change mysql_fetch_array which is a multidimensional array once numerically indexed and once by field name which gives you double results to mysql_fetch_assoc
and $COURSE_ID is always last because for each loop it is overwritten
Try this:
Part 1:
while($file = mysql_fetch_assoc($result)){
echo '<ul>';
echo '<li>';
$STUDENT_ID = $_SESSION['ID'];
$COURSE_ID = $file['COURSE_ID'];
echo 'the course id: ' .$COURSE_ID;
echo 'course name: ' .$file['title'];
echo 'Starting: ' .$file['start_date'];
echo ' ending: '.$file['end_date'];
echo "<form action='lista_cursuri.php' method='post'>
<input type='hidden' name='courseid' value='".$COURSE_ID."' >
<input type='submit' name='submit' value='attent course!''> </form>";
echo '</li>';
}
Part 2:
if(isset($_POST['submit'])){
$course = $_POST['courseid'];
$sql1 = "INSERT INTO `courses_students` (COURSE_ID,STUDENT_ID) VALUES ($course,$STUDENT_ID)";
$result = mysql_query($sql1);
}
Try this:
$sql1 = "INSERT INTO `courses_students` (COURSE_ID,STUDENT_ID)
VALUES ('".$COURSE_ID."','".$STUDENT_ID."')"; $result = mysql_query($sql1);

php how can I make sure the page is reloaded and the echo is updated to the new value

The users of my website can subscribe some of their animals for a competition.
My code works perfectly but there is a big issue. When a user presses subscribe the page reloads but because the isset is after the echo of the button itself the page needs to be refreshed before the buttontext changes into "subscribed".
Change the order gives issues as you probably can see.
Who can help me out? I'm out of options myself. (I translated the variables etc.)
<form action="" method="post" name="frmSubscribe">
<?php
$Counter = 0;
$sql = "Select * from Animals where username='".$_SESSION['User']."' ";
$result = mysql_query($sql);
while($row=mysql_fetch_array($result)){
echo $row['Animalname'];
$Duiven[] = $row['AnimalID'];
$Username[] = $row['username'];
?>
<input type='submit' <?php echo "name= ".$Buttons[$Counter].""; ?> value='<?php
$sqlSubscribed = "SELECT * FROM Competitionresults WHERE AnimalID='".$Animals[$Counter]."'";
$resultSubscribed = mysql_query($sqlSubscribed);
if(mysql_num_rows($resultSubscribed) == 0){ echo "Subscribe";}
else {echo "deregister";}
?>'><br/><?php
$Teller++;
}
if (isset($_POST['btnSubscribe1'])){
$sqlCheck = "SELECT * FROM Competitionresults WHERE AnimalID='".$Animals[0]."'";
$resultCheck = mysql_query($sqlCheck);
if (mysql_num_rows($resultCheck) == 0){
$sql1 = "INSERT INTO Competitionresuls (AnimalID, username) VALUES ('".$Animals[0]."','".$Username[0]."')";
$result1 = mysql_query($sql1);
$row=mysql_fetch_array($result1);
?><?php
}
}
... and so on for the next animals.
You have to use output buffering I think. Put ob_start() at the beginning of your page, now output any placeholder instead of real input code:
[SUMBIT]
instead of:
<input type='submit' ....
At the end of page you get your buffered content:
$content = ob_get_clean()
And replace submit button with correct code:
$content = str_replace('[SUBMIT]', 'Your actual submit button code here...', $content);
And now output content:
echo $content;
quick fix can be javascript
echo '<span id="someid" >Subscribe</span>';
and when changing
echo "<script>document.getElementById('someid').innerHTML = 'Subscribed';</script>";
in future I STRONGLY suggest you to use PHP MVC Framework
You can use your post code above the page then loaded your page....
Please use like below code:
<?php
if (isset($_POST['btnSubscribe1'])){
$sqlCheck = "SELECT * FROM Competitionresults WHERE AnimalID='".$Animals[0]."'";
$resultCheck = mysql_query($sqlCheck);
if (mysql_num_rows($resultCheck) == 0){
$sql1 = "INSERT INTO Competitionresuls (AnimalID, username) VALUES ('".$Animals[0]."','".$Username[0]."')";
mysql_query($sql1);
header('Location: samefilename.php');
die;
}
}
?>
<form action="" method="post" name="frmSubscribe">
<?php
$Counter = 0;
$sql = "Select * from Animals where username='".$_SESSION['User']."' ";
$result = mysql_query($sql);
while($row=mysql_fetch_array($result)){
echo $row['Animalname'];
$Duiven[] = $row['AnimalID'];
$Username[] = $row['username'];
?>
<input type='submit' <?php echo "name= ".$Buttons[$Counter].""; ?> value='<?php
$sqlSubscribed = "SELECT * FROM Competitionresults WHERE AnimalID='".$Animals[$Counter]."'";
$resultSubscribed = mysql_query($sqlSubscribed);
if(mysql_num_rows($resultSubscribed) == 0){ echo "Subscribe";}
else {echo "deregister";}
?>'><br/><?php
$Teller++;
}
}
most easy solution move the isset up to the top. just so you know actions should always be the first things you handle after that you are gonna work on the view
<form action="" method="post" name="frmSubscribe">
<?php
if (isset($_POST['btnSubscribe1'])){
$sqlCheck = "SELECT * FROM Competitionresults WHERE AnimalID='".key($_GET)."'";
$resultCheck = mysql_query($sqlCheck);
if (mysql_num_rows($resultCheck) == 0){
$sql1 = "INSERT INTO Competitionresuls (AnimalID, username) VALUES ('".key($_GET)."','".$_SESSION['User']."')";
$result1 = mysql_query($sql1);
$row=mysql_fetch_array($result1);
}
}
$Counter = 0;
$sql = "Select * from Animals where username='".$_SESSION['User']."' ";
$result = mysql_query($sql);
while($row=mysql_fetch_array($result)){
echo $row['Animalname'];
$Duiven[] = $row['AnimalID'];
$Username[] = $row['username'];
?>
<input type='submit' <?php echo "name= ".$Buttons[$Counter].""; ?> value='<?php
$sqlSubscribed = "SELECT * FROM Competitionresults WHERE AnimalID='".$Animals[$Counter]."'";
$resultSubscribed = mysql_query($sqlSubscribed);
if(mysql_num_rows($resultSubscribed) == 0){ echo "Subscribe";}
else {echo "deregister";}
?>'><br/><?php
$Teller++;
}

PHP Foreach loop problem with mySQL INSERT INTO

I am having a big issue.
This is the first time I sue a foreach and I do not even know if it's the right thing to use.
I have a textarea where my members can add some text.
They also have all the accounts where to send the posted text.
Accounts are of two types F and T.
They are shown as checkboxes.
So when a member types "submit" the text should be INSERTED in a specific table for EACH of the selected accounts. I thought php foreach was the right thing. But I am not sure anymore.
Please take in mind I do not know anything about foreach and arrays. So please when helping me, consider to provide the modded code =D . Thank you so much!
<?php
require_once('dbconnection.php');
$MembID = (int)$_COOKIE['Loggedin'];
?>
<form action="" method="post">
<p align="center"><textarea id="countable1" name="addit" cols="48" rows="10" style="border-color: #ccc; border-style: solid;"></textarea>
<br>
<?
$DB = new DBConfig();
$DB -> config();
$DB -> conn();
$on="on";
$queryF ="SELECT * FROM `TableF` WHERE `Active`='$on' AND `memberID`='$MembID' ORDER BY ID ASC";
$result=mysql_query($queryF) or die("Errore select from TableF: ".mysql_error());
$count = mysql_num_rows($result);
if ($count > 0)
{
while($row = mysql_fetch_array($result)) {
?><div style="width:400px; height:100px;margin-bottom:50px;"><?
$rowid = $row['ID'];
echo $row['Name'] . '</br>';
$checkit = "checked";
if ($row['Main'] == "")
$checkit = "";
if ($row['Locale'] =="")
$row['Locale'] ="None" . '</br>';
echo $row['Locale'] . '</br>';
if ($row['Link'] =="")
$row['Link'] ="javaScript:void(0);";
?>
<!-- HERE WE HAVE THE "F" CHECKBOXES. $rowid SHOULD BE TAKEN AND INSERTED IN THE FOREACH BELOW FOR ANY SELECTED CHECKBOX IN THE FIELD "Type".SEE BELOW -->
<input type="checkbox" name="f[<?php echo $rowid?>]" <?php echo $checkit;?>>
</div>
<?
}//END WHILE MYSQL
}else{
echo "you do not have any Active account";
}
$DB = new DBConfig();
$DB -> config();
$DB -> conn();
$queryTW ="SELECT * FROM `TableT` WHERE `Active`='$on' AND `memberID`='$MembID' ORDER BY ID ASC";
$result=mysql_query($queryTW) or die("Errore select TableT: ".mysql_error());
$count = mysql_num_rows($result);
if ($count > 0)
{
while($row = mysql_fetch_array($result)) {
?><div style="width:400px; height:100px;margin-bottom:50px;"><?
$rowid = $row['ID'];
echo $row['Name'] . '</br>';
$checkit = "checked";
if ($row['Main'] == "")
$checkit = "";
if ($row['Locale'] =="")
$row['Locale'] ="None" . '</br>';
echo $row['Locale'] . '</br>';
if ($row['Link'] =="")
$row['Link'] ="javaScript:void(0);";
?>
<!-- HERE WE HAVE THE "T" CHECKBOXES. $rowid SHOULD BE TAKEN AND INSERTED IN THE FOREACH BELOW FOR ANY SELECTED CHECKBOX IN THE FIELD "Type".SEE BELOW -->
<input type="checkbox" name="t[<?php echo $rowid?>]" <?php echo $checkit;?> >
</div>
<?
}//END 2° WHILE MYSQL
}else{
echo "you do not have any Active account";
}
?>
<input type="submit" value="submit">
</form>
<?
//WHEN CHECKBOXES "F" ARE FOUND, FOR EACH CHECKBOX IT SHOULD INSERT INTO TableG THE VALUES BELOW, FOR EACH SELECTED "F" CHECKBOX
if(!empty($_POST['addit']) && !empty($_POST['f'])){
$thispostF = $_POST['f'];
$f="F";
foreach ($thispostF as $valF)
//THE MOST IMPORTANT FIELD HERE IS "Type". THE ARRAY INSERT "on", I NEED INSTEAD THE VALUE $rowid AS ABOVE
$queryaddF="INSERT INTO TableG (ID,memberID,Type,IDAccount,Tuitting) VALUES (NULL,".$MembID.",'".$f."','".$valF."', '".$_POST['addit']."')";
$resultaddF=mysql_query($queryaddF) or die("Errore insert G: ".mysql_error());
}
//WHEN CHECKBOXES "T" ARE FOUND, FOR EACH CHECKBOX IT SHOULD INSERT INTO TableG THE VALUES BELOW, FOR EACH SELECTED "T" CHECKBOX
if(!empty($_POST['addit']) && !empty($_POST['t'])){
$thispostT = $_POST['t'];
$t="T";
foreach ($thispostT as $valF)
//THE MOST IMPORTANT VALUE HERE IS "Type". THE ARRAY GIVES "on", I NEED INSTEAD THE VALUE $rowid AS ABOVE
$queryaddT="INSERT INTO TableG (ID,memberID,Type,IDAccount,Tuitting) VALUES (NULL,".$MembID.",'".$t."','".$valF."', '".$_POST['addit']."')";
$resultaddF=mysql_query($queryaddF) or die("Errore insert G: ".mysql_error());
}
?>
foreach ($thispostT as $valF)
{
$queryaddT="INSERT INTO TableG (ID,memberID,Type,IDAccount,Tuitting) VALUES (NULL,".$MembID.",'".$t."','".$valF."', '".$_POST['addit']."')";
$resultaddF=mysql_query($queryaddF) or die("Errore insert G: ".mysql_error());
}
please put start and ending bracket to your foreach loop and try i have not read the whole code but just found you missing the brackets. hope that helps you.
I think I know what you're doing...
You're going to need to do:
foreach($_POST as $key => $value) {
$type = substr($key,0,1);
$id = substr($key,1);
if($type == 't') {
// do insert for t table here
} else if($type == 'f') {
// do insert for f table here
}
}
I didn't test it but it should be something like this.
My suggestion is
create field name as t[] (array)
onchecked value will be passed on the next page
the form checkbox field should be like that
<input type="checkbox" name="t[]" value="< ?php echo $rowid?>" <?php echo $checkit;? > >
and when you Submit the form
GET THE VALUE and insert in to database;
< ?
if($_POST['t'])
{
foreach($_POST['t'] as $v)
{
queryaddT="INSERT INTO TableG (ID,memberID,Type,IDAccount,Tuitting) VALUES (NULL,".$MembID.",'".$t."','".$valF."', '".$_POST['addit']."')";
$resultaddF=mysql_query($queryaddF) or die("Errore insert G: ".mysql_error());
}
}
? >

Categories