0% found this document useful (0 votes)
49 views13 pages

'Connections/Ballot - PHP' "Getsqlvaluestring" "" ""

The issue is that $_POST['region'] is an array, not a string, since you are submitting multiple checkboxes with the same name. To insert the values properly, you need to implode the array into a comma separated string before inserting: ```php $region = implode(',', $_POST['region']); $query = "UPDATE table SET region='$region' WHERE id='$id'"; ``` This takes the array of checked values, joins them with commas, and inserts the result as a single string into the database. So the key points are: - Name checkboxes the same to group them as an array - On submit, the

Uploaded by

Aneel Lalwani
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
49 views13 pages

'Connections/Ballot - PHP' "Getsqlvaluestring" "" ""

The issue is that $_POST['region'] is an array, not a string, since you are submitting multiple checkboxes with the same name. To insert the values properly, you need to implode the array into a comma separated string before inserting: ```php $region = implode(',', $_POST['region']); $query = "UPDATE table SET region='$region' WHERE id='$id'"; ``` This takes the array of checked values, joins them with commas, and inserts the result as a single string into the database. So the key points are: - Name checkboxes the same to group them as an array - On submit, the

Uploaded by

Aneel Lalwani
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 13

1.

<?php require_once('Connections/ballot.php'); ?>
<?php
if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") 
{
  if (PHP_VERSION < 6) {
    $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
  }

  $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mys
ql_escape_string($theValue);

  switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;    
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case "double":
      $theValue = ($theValue != "") ? doubleval($theValue) : "NULL";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "defined":
      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
      break;
  }
  return $theValue;
}
}

$editFormAction = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
  $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
}
if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "Ballot")) {
  $insertSQL = sprintf("INSERT INTO votes (`first`, `last`, gender, grade, involvement, schedule, party, `tim
e`) VALUES (%s, %s, %s, %s, %s, %s, %s, %s)",
                       GetSQLValueString($_POST['first'], "text"),
                       GetSQLValueString($_POST['last'], "text"),
                       GetSQLValueString($_POST['gender'], "text"),
                       GetSQLValueString($_POST['grade'], "text"),
                       GetSQLValueString($_POST['involvement'], "text"),
                       GetSQLValueString($_POST['schedule'], "text"),
                       GetSQLValueString($_POST['party'], "text"),
                       GetSQLValueString($_POST['time'], "text"));

  mysql_select_db($database_ballot, $ballot);
  $Result1 = mysql_query($insertSQL, $ballot) or die(mysql_error());

  $insertGoTo = "thanks.php";
  if (isset($_SERVER['QUERY_STRING'])) {
    $insertGoTo .= (strpos($insertGoTo, '?')) ? "&" : "?";
    $insertGoTo .= $_SERVER['QUERY_STRING'];
  }
  header(sprintf("Location: %s", $insertGoTo));
}

mysql_select_db($database_ballot, $ballot);
$query_Recordset1 = "SELECT * FROM votes";
$Recordset1 = mysql_query($query_Recordset1, $ballot) or die(mysql_error());
$row_Recordset1 = mysql_fetch_assoc($Recordset1);
$totalRows_Recordset1 = mysql_num_rows($Recordset1);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/D
TD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Please Place your Vote Below</title>
</head>

<body style="background-image:url(images/bg.jpg); background-repeat:repeat-x; background-
color:#000000;">
<table align="center" bgcolor="#FFFFFF" cellpadding="0" cellspacing="0" border="0">
<tr><td>
<div style="border:thin; border-color:000000; border-style:groove; width:700px; background-
color:ffffff;">
<div align="center"><a href="index.php"><img src="images/header.jpg" alt="Mock Elections 2010" /></
a></div>
<div style="margin:10px; margin-top:30px;">
Before continuing to vote, in order to count your vote, we ask that you please ensure you are adhereing 
to the following guidelines:
</div>
<div style="margin:30px">
  <p>- When putting your name, remember to put your full legal name. NO nicknames.<br />
    - Be sure that all your information is valid otherwise your vote will not be counted.
    <br />
  </p>
</div>
<div style="margin-left:150px; margin-right:150px; margin-top:50px;">
<form action="<?php echo $editFormAction; ?>" method="POST" name="Ballot">
First Name:&nbsp; <input type="text" name="first" /><br />
Last Name:&nbsp; <input type="text" name="last" /><br />
<div>Gender:&nbsp;
<label>
Male <input type="radio" value="Male" name="gender" /></label>
<label>Female <input type="radio" value="Female" name="gender" /></label>
</div>
Grade:&nbsp;
<select name="grade">
  <option selected="selected">&nbsp;</option>
  <option value="7">7</option>
  <option value="8">8</option>
  <option value="9">9</option>
  <option value="10">10</option>
  <option value="11">11</option>
  <option value="12">12</option>
  <option value="Teacher">Teacher</option>
  <option value="Staff">Staff</option>
</select><br />
<div>Involvement:&nbsp;
  <label>
    <input type="checkbox" name="involvement[]" value="Athletics" id="involvement_0" />
    Athletics</label>
  <label>
    <input type="checkbox" name="involvement[]" value="Co-Curricular" id="involvement_1" />
    Co-Curricular</label>
  <label>
    <input type="checkbox" name="involvement[]" value="Clubs" id="involvement_2" />
    Clubs</label>
</div>
<div>Schedule:&nbsp;
<label><input type="radio" value="C4" name="schedule" />C4</label>
<label><input type="radio" value="All Day" name="schedule" />All Day Hauser Student</label>
</div>
<div>Party:&nbsp;
<label><input type="radio" value="PokePartay" name="party" />PokePartay</label>
<label><input type="radio" value="Equilibrium" name="party" />Equilibrium Party</label>
</div>
<br />
<input type="Submit" value="Submit" />
<input type="hidden" value="<?php 
$tz =  new DateTimeZone('America/Indianapolis');
$date = new DateTime('now', $tz);
echo $date->format('m-d-Y h:i:s') . "\n";
?>" name="time" />
<?php
if (isset($_POST['submit'])) { 
   $involvements = $_POST['involvement'];

   foreach($involvements as $involvement) {
      $query2 = "INSERT INTO votes (involvement) VALUES ('$involvement')";
      $result2 = mysql_query($ballot, $query2) or die(mysql_error());
   }
}
?>
<input type="hidden" name="MM_insert" value="Ballot" />
</form>
</div>
<br />
<br />
<br />
<br />
</div>

</td>
</tr>
</table>

</body>
</html>
<?php
mysql_free_result($Recordset1);
?>

2. was trying to insert data from a form but it is not inserting the entry to the database.

Here’s the code

$Tours = $_POST['Tours'];

if (is_array($Tours)) {

foreach ($Tours as $key=> $val);

$content = $content . count($Tours);

for ($i=0;$i $val);

// remove this line $content = $content . …

in Php Checkbox | 0 comments

Question by RickyG: How to insert multiple checkbox entry into mysql using php?
I was trying to insert data from a form but it is not inserting the entry to the database.

Here’s the code

$Tours = $_POST['Tours'];
if (is_array($Tours)) {
foreach ($Tours as $key=>$val);
$content = $content . count($Tours);
for ($i=0;$i
$content = $content . "$Tours[$i]\n";
}

I made Tours a set with 4 selections but the entry is just blank. When i changed the type of Tours into a varchar, the
word array is in the database not the selections made from the form.

I use the code above to display the selection and there's a number which appears before the selections like below.
How do i get rid of the number?

4FirstChoice SecondChoice ThirdChoice FourthChoice

Best answer:
Answer by George Garchagudashvili
You have mistakes in your code

$Tours = $_POST['Tours'];
if (is_array($Tours)) {
foreach ($Tours as $key=>$val);
// remove this line $content = $content . count($Tours);
for ($i=0;$i
$content = $content . "$Tours[$i]\n";
}

3. <?php
<body>
<form action="checkbox.php" method="post">
<input type="checkbox" name="checkbox[]" value="a">
<input type="checkbox" name="checkbox[]" value="b">
<input type="checkbox" name="checkbox[]" value="c">
<input type="checkbox" name="checkbox[]" value="d">
<br>
<br>
<input type="submit" name="Submit" value="Submit">
</form>
<?

/* and in your checkbox.php you do this: */

if(isset($_POST['Submit']))
{
for ($i=0; $i<count($_POST['checkbox']);$i++) {
 $check_val .= $_POST['checkbox'][$i];
 $check_val .=",";
}
}
?>

4.

Inserting multiple checkbox values into db (yet again!)


The script only inserts "Array" into the database.

 8:38 am on Jan 16, 2004 (gmt 0)


pablone
t Hello, I have followed along other threads regarding this topic. I have
followed the examples pretty closely (I think) but still fail to get the
desired effect. Instead of inserting the values of the checked checkboxes,
the script inserts Array into the database. Here are the relevant code:
#:1252903

//update.php
<input type="checkbox" value="East Bay" name="region[]" <?php
if (preg_match("/East Bay/", "$region")) { echo "checked"; }
else { echo ""; }?>>East Bay
<input type="checkbox" value="North Bay" name="region[]" <?php
if (preg_match("/North Bay/", "$region")) { echo "checked"; }
else { echo ""; }?>>North Bay <br>
<input type="checkbox" value="South Bay" name="region[]" <?php
if (preg_match("/South Bay/", "$region")) { echo "checked"; }
else { echo ""; }?>>South Bay
<input type="checkbox" value="Peninsula" name="region[]" <?php
if (preg_match("/Peninsula/", "$region")) { echo "checked"; }
else { echo ""; }?>>Peninsula <br>
<input type="checkbox" value="Bay Area" name="region[]" <?php
if (preg_match("/Bay Area/", "$region")) { echo "checked"; }
else { echo ""; }?>>Bay Area
<input type="checkbox" value="San Francisco" name="region[]" <?
php if (preg_match("/San Francisco/", "$region")) { echo
"checked"; } else { echo ""; }?>>San Francisco <br>

Handled by:

//updated.php
include("dbinfo.inc.php");
mysql_connect('localhost',$username,$password);

$id=$_POST["id"];
$sregion = $_POST['region'];

$query="UPDATE intern_db SET region='$sregion' WHERE id='$id'";


@mysql_select_db($database) or die( "Unable to select database");
mysql_query($query);
echo "Record Updated";
mysql_close();

Any ideas? Thank you in advance.

BTW, is there a more efficient way to search for a string in a field than
using preg_match?

 10:07 am on Jan 16, 2004 (gmt 0)


warumauchnich
t Heloo pablonet,

you'll have to set up a while-loop to get each of the selected


checkboxes:
#:1252904
while (list($k, $v) = each($region)) :
// put into mySQL
endwhile;

dcrombie  11:19 am on Jan 16, 2004 (gmt 0)

#:1252905
Try the PHP functions strstr [php.net] and implode [php.net].

;)

pablonet  5:05 am on Jan 17, 2004 (gmt 0)

Thank you for replying. I tried the while suggestion but the script
#:1252906 added only one value to the database. I finally got it to work by
lifting an example script from PHP and MySQL for Dynamic Web
Sites:

//updated.php

include("dbinfo.inc.php");
mysql_connect('localhost',$username,$password);

$id=$_POST["id"];

if (isset($_POST['region'])) {
foreach ($_POST['region'] as $key => $value) {
$ints .= "$value, ";
}
$ints = substr($ints, 0, -2); //removes leading comma and space
}else {
echo 'You forgot to enter a region.';
}

$sregion = $ints;

$query="UPDATE intern_db SET region='$sregion' WHERE


id='$id'";
@mysql_select_db($database) or die( "Unable to select
database");
mysql_query($query);
echo "Record Updated";
mysql_close();

Thank you again... :o)

broniusm  3:52 am on Feb 8, 2004 (gmt 0)

So you were trying to insert a comma-delim array of values as a


#:1252907 string, not to insert multiple records, one per checkbox?

I'm trying to solve the latter, and I'm leaning toward a foreach or
while.

-bronius

pablonet  3:08 am on Feb 9, 2004 (gmt 0)

Yeah, I know that it is not the best way but I did not want to
#:1252908 complicate myself any more than I had to. The database is small
and simple. On a display page I use the preg_match function to
find one item in the string, like this:

<input value="Bay Area" name="region[]" type="checkbox"


<?php if (preg_match("/Bay Area/", "$region")) { echo
"checked"; } else { echo ""; }?> >Bay Area

broniusm  3:22 pm on Feb 9, 2004 (gmt 0)

claro.. In case someone is looking to insert multiple records based


#:1252909 on checkboxes in Dreamweaver MX 2004 using PHP, here's what I
added to the insert Server Behavior:

$valuesSets = "";
for ($i=0; $i < count($asstcoachid); $i++) {
$valuesSets.="(".GetSQLValueString($teamid[$i],
"int").",".GetSQLValueString($asstcoachid[$i],
"string").",".GetSQLValueString($eventid[$i], "int")."),";
}
$valuesSets=substr($valuesSets,0,-1); // to remove last comma

$insertSQL = sprintf("INSERT INTO TeamAsstCoaches (teamid,


asstcoachid, eventid) VALUES %s",
$valuesSets);

mysql_select_db($database_usatss, $usatss);
if ($valuesSets <> "") {
// echo $insertSQL;
$Result1 = mysql_query($insertSQL, $usatss) or die(mysql_error());
}
The main concepts here:
- name your input fields so PHP knows they're arrays:
"team[]", not "team"
- loop thru params based on checkbox:
asscoachid[] or $asscoachid in my case
- use MySQL multiple insert functionality:
INSERT INTO table (fld1, fld2, fld3) VALUES (val1_1, val2_1,
val3_1), (val1_2, val2_2, val3_2) .. etc

Hope this helps someone down the road.

5.

$entry_type = serialize($_POST["entry_type"]);

6. <?
if(isset($_POST['submit'])) {
include('include/db.php');
$arrays = implode(",",$_POST['all_food']);
$query="insert into checkbox values('".$arrays."')";
//echo $query;
mysql_query($query) or die ('Error inserting values into database, please go back and try again');
mysql_close();
}
?>

<html>
<body>
<form method="post">
<table width="50%">
<th>What is your favorite food?</th>
<tr>
<?
$array_food=array('fish','meat','vegetable','fastfood','soup');
foreach($array_food as $food){
echo "<td>";
echo "<input type=\"checkbox\" name=\"all_food[]\" id=\"all_food\" value=$food>$food</input>";
echo "</td>";
}
?>

</tr>
<tr>

<td colspan="6" style="padding-left:30em">


<input type="submit" name="submit" value="save">
</td>
</table>
</form>
</body>
</html>

7. Way 02: Inserting data using serialize function

<?
if(isset($_POST['submit'])) {
include('include/db.php');
$arrays = serialize($_POST['all_food']);
$query="insert into checkbox values('".$arrays."')";
//echo $query;
mysql_query($query) or die (mysql_error());
mysql_close();
}
?>

<html>
<body>
<form method="post">
<table width="50%">
<th>What is your favorite food?</th>
<tr>
<?
$array_food=array('fish','meat','vegetable','fastfood','soup');
foreach($array_food as $food){
echo "<td>";
echo "<input type=\"checkbox\" name=\"all_food[]\" value=$food>$food</input>";
echo "</td>";
}
?>

</tr>
<tr>

<td colspan="6" style="padding-left:30em">


<input type="submit" name="submit" value="save">
</td>
</table>
</form>
</body>
</html>

8. <? ob_start(); ?>


<html>
<form method="POST" action="search.php">
<body bgproperties="fixed" background="c4.bmp">
<?php
$user=$_POST[user];
$conn=mysql_connect("localhost","username","passwo rd");
mysql_select_db("database",$conn);
$result = mysql_query("SELECT * FROM posting where job_keywords='$keyword'", $conn) or die("error
querying database");\\posting is the table where the list of jobs are stored.
?>
<table border="2" cellspacing="1" width="100%">
<tr>
<th>Position</th>
<th>Job Responsibility</th>
<th>Job Level</th>
<th>Job location</th>
<th>Functional area</th>
<th>Salary</th>
<th>Apply</th>
<th>Review</th>
<th>Not Interested</th>
</tr>
<?
$i = 0;

while($result_ar = mysql_fetch_assoc($result)){
?>
<input="text" name="post_id[<? echo $i?>]" value="<?php echo $result_ar['post_id'];?>">
<tr>
<td><?php echo $result_ar['position']; ?></td> \\columns of table 'posting'
<td><?php echo $result_ar['job_responsibility'];?></td>
<td><?php echo $result_ar['job_level'];?></td>
<td><?php echo $result_ar['location_of_job'];?></td>
<td><?php echo $result_ar['job_functional_area'];?></td>
<td><?php echo $result_ar['job_salary'];?><br></td>
<td><input type="radio" value="apply" name="choice[<?echo $i?>]"></td>
<td><input type="radio" value="review" name="choice[<?echo $i?>]"></td>
<td><input type="radio" value="not_interested" name="choice[<?echo $i?>]"></td>
</tr>
<?php
$i+=1;
}
?>
</table>
</br></br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&n bsp;&nbsp;&nbsp;&nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&n bsp;&nbsp;&nbsp;&nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&n bsp;&nbsp;&nbsp;&nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&n bsp;&nbsp;&nbsp;&nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&n bsp;&nbsp;&nbsp;&nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&n bsp;&nbsp;&nbsp;&nbsp;&nbsp;

<input type="hidden" value="<?echo $user?>" name="user">


<input type="hidden" value="<?echo $i?>" name="i">
<input type="Submit" value="Submit" name="Submit">
</form>
</html>
</body>
<? ob_end_flush(); ?>

You might also like