I'm trying to insert multiple rows into a MySQL table depending on the number of options selected from a multiple select box. currently it is inserting one row (regardless of how many options are selected) but the 'strategyname' column is empty each time.
Any ideas on how to insert multiple rows and why the values of the options aren't being sent to the table?
Here is the form:
<form method="POST" action="update4.php">
<input type="hidden" name="id" value="1">
<p class="subheadsmall">Strategies</p>
<p class="sidebargrey">
<?php
$result = mysql_query("SELECT strategyname FROM sslink WHERE study_id = '{$_GET['id']}'");
if (!$result) {
die("Database query failed: " . mysql_error());
}
while($row = mysql_fetch_array($result)) {
$strategyname = $row['strategyname'];
echo $strategyname.'<br />';
}
?>
<p class="subheadsmall">Add a strategy... (hold down command key to select more than one)</p>
<select name="strategylist" multiple="multiple">
<?php
$result = mysql_query("SELECT * FROM strategies");
if (!$result) {
die("Database query failed: " . mysql_error());
}
while($row = mysql_fetch_array($result)) {
$strategylist = $row['name'];
$strategyname = htmlspecialchars($row['name']);
echo '<option value="' . $strategylist . '" >' . $strategyname . '</option>' . '\n';
}
?>
</select>
</p>
<input type="submit" class="box" id="editbutton" value="Update Article">
</form>
And this is what sends it to the database:
<?php
$id=$_POST['id'];
$test=$_POST['strategylist'];
$db="database";
$link = mysql_connect("localhost", "root", "root");
//$link = mysql_connect("localhost",$_POST['username'],$_POST['password']);
if (! $link)
die("Couldn't connect to MySQL");
mysql_select_db($db , $link) or die("Select Error: ".mysql_error());
//for($i=0;$i<sizeof($_POST["test"]);$i++)
//{
//$sql = "insert into tbl_name values ($_POST["test"][$i])"; }
//sql = "INSERT INTO table_name VALUES ('" . join(",",$_POST["test"]) . "')";
$result=mysql_query("INSERT INTO sslink (study_id, strategyname) VALUES ('$id','" . join(",",$_POST["strategylist"]) . "')")or die("Insert Error: ".mysql_error());
mysql_close($link);
print "Record added\n";
?>
Couple of points:
your select needs to be named strategylist[] in order to tell PHP that it will contain an array rather than a single value
Your insert code then needs to iterate over that array, creating a new insert for each element it contains, unless (as it seems) you want all those options to be concatenated into a single row's field.
At the moment, your form only returns a single option (from PHP's perspective), so it's only going to insert a single row.
To iterate over the array, use something like this:
foreach($_POST["strategylist[]"] as $s) {
# do the insert here, but use $s instead of $_POST["strategylist[]"]
$result=mysql_query("INSERT INTO sslink (study_id, strategyname) " .
"VALUES ('$id','" . join(",",$s) . "')")
or die("Insert Error: ".mysql_error());
}
Two things:
If you view the source of page with the multiple select in it, can you see the <option value="something"> lines there? Are the values empty? It seems strange to me that at the top of your file you are using $row['strategyname'] and later you are using $row['name']. I suspect this may be the cause of the empty StrategyName column.
To handle multiple selections, you should specify the select tag as
<select name="strategylist[]" multiple="multiple">
The extra [] tells PHP to form an array with all of the selections in it. You can then loop over the array like:
$strategylist = $_POST['strategylist'];
for ($i = 0; $i < count($strategylist); $i++) {
$strategyname = $strategylist[$i];
// Insert a record...
}
// first you need to define your output as one variable if you don't like the loop
if($_POST){
$sum = implode(", ", $_POST[select2]);
echo $sum.".";
}
// the variable sum is the one you are seeking for you can insert it to the database
// if you want to enter every peiece of the array in a new field you should use
// different select names
Related
Hello i am creating a form where i can update multiple rows in my database
first of all i have a form with a field name "pol", this should carry multiple values as declared below using "[]"
<form action="snooze.php" name="frm" method="post">
<input type="checkbox" name="pol[]" value="<?php echo $row_cert['Policy_Number']; ?>">
</form>
This multiple values, i have been able to display using a for each loop
<?php
if (isset($_POST['pol']))
{
$hobby = $_POST['pol'];
foreach ($hobby as $hobys=>$value) {
echo "".$value."<br /><br />";
}
}
?>
but now i am trying to use this multiple values passed in the for each loop in a where clause to update multiple rows in my database, but it only passes 1 value instead of multiple values as the above code does when echo.
this is what i have tried
<?php
if (isset($_POST['pol']))
{
$db = new mysqli('localhost', '---', '----', '----');
if ($db->connect_error) {
die("Connect Error: " .$db->connect_error); //TODO: better error handling
}
$hobby = $_POST['pol'];
foreach ($hobby as $hobys=>$value) {
$sql = "UPDATE check_niid
SET niid_status = 'Successful'
WHERE Policy_Number = '$hobby[$hobys]'";
}
if (!$db->query($sql)) {
die("Update failed. Error: " .$db->error); //TODO: better error handling
}
}
?>
please what could i be doing wrong here, my aim is to be able to update multiple rows using the where clause
your query execution is in out side the foreach so . $sql variable overwrite by multiple times and final array value only set in $sql . that only executed once in your query so .it should be inside the foreach loop
foreach ($hobby as $hobys=>$value) {
$sql = "UPDATE check_niid
SET niid_status = 'Successful'
WHERE Policy_Number = '$hobby[$hobys]'";
if (!$db->query($sql)) {
die("Update failed. Error: " .$db->error); //TODO: better error handling
}
}
I am missing something from my code and I don't know how to make it work. I may have programed it wrong and that could be giving me my troubles. I am new at php and things have been going slowly. please understand that the code my not be organized as it should be. After creating about 12 pages of code I found out that I should be using mysqli or pod. Once I get everything working that will be the next project. Enough said here is my issue. I was able to populate my drop down box and there shows no errors on the page. Also all the data does get inserted into the database except for the section made on the drop down box. Here is my code. I will leave out all of the input fields except the drop down.
<?php
{$userid = $getuser[0]['username'];}
// this is processed when the form is submitted
// back on to this page (POST METHOD)
if ($_SERVER['REQUEST_METHOD'] == "POST")
{
# escape data and set variables
$tank = addslashes($_POST["tank"]);
$date = addslashes($_POST["date"]);
$temperature = addslashes($_POST["temperature"]);
$ph = addslashes($_POST["ph"]);
$ammonia = addslashes($_POST["ammonia"]);
$nitrite = addslashes($_POST["nitrite"]);
$nitrate = addslashes($_POST["nitrate"]);
$phosphate = addslashes($_POST["phosphate"]);
$gh = addslashes($_POST["gh"]);
$kh = addslashes($_POST["kh"]);
$iron = addslashes($_POST["iron"]);
$potassium = addslashes($_POST["potassium"]);
$notes = addslashes($_POST["notes"]);
// build query
// # setup SQL statement
$sql = " INSERT INTO water_parameters ";
$sql .= " (id, userid, tank, date, temperature, ph, ammonia, nitrite, nitrate, phosphate, gh, kh, iron, potassium, notes) VALUES ";
$sql .= " ('', '$userid', '$tank', '$date', '$temperature', '$ph', '$ammonia', '$nitrite', '$nitrate', '$phosphate', '$gh', '$kh', '$iron', '$potassium', '$notes') ";
// #execute SQL statement
$result = mysql_query($sql);
// # check for error
if (mysql_error()) { print "Database ERROR: " . mysql_error(); }
print "<h3><font color=red>New Water Parameters Were Added</font></h3>";
}
?>'
Here is the drop down
<tr><td><div align="left"><b>Tank Name: </b> </div></td><td><div align="left">
<?php
echo "<select>";
$result = mysql_query("SELECT tank FROM tank WHERE userid = '$userid'");
while($row = mysql_fetch_array($result))
{
echo "". $row["tank"] . "";
}
echo "";
?>
</div></td></tr>
You missed some code in while loop.
while($row = mysql_fetch_array($result))
{
echo "<option>".$row['tank']."</option>";
}
echo "</select>";
are you able to build drop down menu or box. if not try this query
$sql="SELECT `tank` FROM `tank` WHERE user_name='$user'";
$result=mysqli_query($dbc,$sql)
//here $dbc is a variable which you use to connect with the database.
Otherwise leave that only read from here why you need to change your code. in the while loop
one one more thing you have to give your select attribute a name, because it will return the value through name so give a name to your select attributes as you are using tank while building your drop down menu so i will give a same name tank. Than you dont have to change anything.
and you have to give value to your option as well, thanks
echo "<select name='age'>";
while($row = mysql_fetch_array($result))
{
echo "<option value='" . $row['tank'] . "' >" . $row['tank'] . "</option>";
}
echo "</select>";
In this project, I am making an attendance user interface for the teacher. Here teacher can update student's marks which will directly update into the MYSQL database. Below shows the code that I used to echo out the list of students from the database. Here, I have used array i.e. name="gradeEdit[]" in input section.
teacherGrades.php
<?php
$con=mysqli_connect("#", "#", "", "#");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query ($con,"SELECT ");
echo ' <form method="POST" action="teacherGrades.php">
<table class="tableEchoPupil" border="1">
<tr>
<th>Name</th>
<th>Edit</th>
</tr>';
while($row = mysqli_fetch_array($result))
{
echo "<tr>
<td>" . $row['name'] . "</td>
<td> <input type='text' name='gradeEdit[]' /> </td>
</tr>"; }
echo "<input class='gradeSubmit' type='submit' name='btnSubmit' value='Submit'>";
echo "</table>";
echo "</form> <br/>";
?>
Below shows the code that is stored in the beginning of this page [teacherGrades.php
]. When the teacher inputs new grades and click the submit button from the previous code, the grades has to updated in the database. However the problem is that, I am not able to update it properly. I think there is a few problem behind my code, can you please check and help me. If there are further questions, I am ready to answer.
Thank you in advance.
<?php
$con=mysqli_connect("#","#","","#");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if ($_POST['btnSubmit']){
$gradeEdit = $_POST['gradeEdit'];
foreach ($gradeEdit as $key => $value) {
$grades = implode(',', $gradeEdit);
$query = "UPDATE classroom_student_teacher SET marks = '$grades'
WHERE teacher_id = $userid AND classroom_id = $id";
$close = mysqli_query($con, $query);
}
}
?>
You should pass student name or id in your input box. Which means row-1_key => row-1_value.
<input type='text' name='gradeEdit[".$row['student_id']."]' />
the above line is for form input. Let me know Are you updating data for teacher or for all students. State me table structure.
If you want to save array value. use the below line
foreach ($gradeEdit as $key => $value) {
//use $key as row id and marks will be your $value. So change your query like this below.
$row_id=$key+1;
$query = "UPDATE classroom_student_teacher SET marks = '$value'
WHERE student_id=$row_id AND teacher_id = $userid AND classroom_id = $id";
AND teacher_id = $userid AND classroom_id = $id why you using this condition
$close = mysqli_query($con, $query);
}
2 methods,
the json_encode is a possibility, but it might decode differently.
one option which sounds better to me would be to use serialize and unserialize, this will return the objects just as you put them.
e.g.
serialize($var);
unserialize($var);
It wil just make a serialized string of your array or objects.
In your case JSON could be fine too.
http://php.net/manual/en/function.serialize.php
To store data in you database you can use php own functions.
$conn=mysqli_connect("example.com","testuser","passwort","your_db");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "INSERT INTO Your_Table (First, Second, Array)";
$sql .= VALUES ('First', 'Second',Your_Array)";
mysqli_query($conn, $sql);
mysqli_close($con);
To put your array in the database you can user the php function implode.
$array = array('First', 'Second', 'Last');
$comma_separated = implode(",", $array);
Wich will return you a string like this - First, Second, Last
As a new programmer I'm having trouble figuring out how to exactly code this situation. I've taken some of the solutions via stackoverflow but this one doesn't seem to work as I thought it would. I have a tag that correctly puts in one selected item but if I put in two or three it gives me the numbers. I.e. if I selected 3 options with id's 3, 5 and 8 it turns into 358 instead of creating a many-to-many catalog relationship of 3-3, 3-5, 3-8.
The purpose is that the form is creating a new character that can gain several disadvantages. These disadvantages are then linked to the new characters unique id.
$query2 = implode ( "",$_POST['did']);
$sql="INSERT INTO player_disadvantage
(disadvantageid,characterid)
VALUES ('".$query2."',LAST_INSERT_ID())"
;
<tr>
<td>Disadvantages</td>
<td>
<?php
$result = $mysqli->query("SELECT * FROM disadvantages");
echo '<SELECT multiple="multiple" id="did" name="did[]">';
while($row1 = $result->fetch_assoc()) {
$disadvantages = $row1['name'];
$disadvantagesid = $row1['did'];
$disadvantagescost = $row1['cost'];
echo "<option value='".$disadvantagesid."'>". '+' . ' ' . $disadvantagescost . ' ' . $disadvantages . "</option>";
}
echo '</select>';
?>
</td>
My only guess is to find a way to move the code so that it puts the LAST_INSERT_ID() with every disadvantage id. I'm not sure how to code it.
Try this:
$values = implode(',', array_map(function($x) {
return "('" . mysql_real_escape_string($x) . "', LAST_INSERT_ID())"; },
$_POST['did']));
$sql = "INSERT INTO player_disadvantage (disadvantageid, characterid) VALUES $values";
This creates a query that looks like:
INSERT INTO player_disadvantage (disadvantageid, characterid)
VALUES ('3', LAST_INSERT_ID()),
('5', LAST_INSERT_ID()),
('8', LAST_INSERT_ID())
to add multiple rows.
I am looking to take a PHP page to retrieve data based on the selection from a drop down list, then show the results based on that selection. I am not even sure where to begin except my connection to the database. I do also know that I have to have a query statement, like I would in SQL, which here is a little bit of that:
$sql = "SELECT ForteID, Disposition, appNumber, Finance_Num, Num_Payments, ACH_CC, Notes, Date
FROM cslogs.dbo.Logs
WHERE ForteID = 'bs1441'";
The bs1441 is just an example of one option that would be in the drop down list. I am not sure what I would put there for it to put in there automatically from the list.
Thanks for the help in advance. Sorry if there is not enough information to go on, but not sure what even would be needed at this point.
EDIT:
This is what I have so far:
<form method="get" action="getlog.php">
<table width="300" border="0">
<tr>
<td> Forte ID:</td>
<td><select id="ForteID" name="ForteID">
<option value="nc4682">nc4682</option>
<option value="bs1441">bs1441</option>
<option value="sp3212">sp3212</option>
</select></td>
</tr>
</table>
<input type="submit" name="getLog" value="Get Log">
</form>
</head>
<body>
</body>
</html>
<?php
$serverName = 'SRB-Nick_Desktop\SQLEXPRESS';
$connectionInfo = array('Database'=>'cslogs', 'UID'=>'cslogslogin', 'PWD'=>'123456');
$connection = sqlsrv_connect($serverName, $connectionInfo);
$result = sqlsrv_query( $connection,
'SELECT ForteID, Disposition, appNumber, Finance_Num, Num_Payments, ACH_CC, Notes, Date
FROM Logs
WHERE (ForteID = $ForteID)',
array($ForteID));
while($row = sqlsrv_fetch_array($result))
{
echo($row['ForteID'] . ', '.
$row['Disposition'] . ', '.
$row['appNumber'] . ', '.
$row['Finance_Num'] . ', '.
$row['Num_Payments'] . ', '.
$row['ACH_CC'] . ', '.
$row['Notes'] . ', '.
$row['Date']);
}
sqlsrv_close( $connection);
?>
Then when I look at the page it throws this error:
Parse error: syntax error, unexpected T_STRING in C:\wamp\www\cslogs\getlog.php on line 46
Line 46 is this line:
echo($row['ForteID'] . ', '.
Let me know if that helps!
A couple steps here:
First you need to submit your form with the selection in. I'm not going to go over form submission here but look into it.
once you submit the form you will need to get the value of the drop down and assign it to a variable.
$value= $_POST['value'];
Note: This is a basic example so I didnt add in regex or anything like that.
Once you have your variable ($value) you can then put it in your SQL
$sql = mssql_query($dbc,"SELECT ForteID, Disposition, appNumber, Finance_Num, Num_Payments, ACH_CC, Notes, Date
FROM cslogs.dbo.Logs
WHERE ForteID = '$value'") or die("Query Error " . mssql_get_last_message());
So here we are processing the query. $dbc is the variable that I chose to represent my database connection and the "or die" part will let me know if the query is valid or not.
Once you have a working query you can then summon the data pulled into an array:
while ($row = mssql_fetch_array($sql)) {
And then you need to assign the results of your query to a variable.
$result1 = $row["RESULT1"];
$result2 = $row["RESULT2"];
The capital words are the titles of the columns in your sql table. After you have them assigned to variables you can do whatever you want to them provided they are inside the while loop.
$value= $_POST['value'];
$sql = mssql_query($dbc,"SELECT ForteID, Disposition, appNumber, Finance_Num, Num_Payments, ACH_CC, Notes, Date
FROM cslogs.dbo.Logs
WHERE ForteID = '$value'") or die("Query Error " . mssql_get_last_message());
while ($row = mssql_fetch_array($sql)) {
$result1 = $row["RESULT1"];
$result2 = $row["RESULT2"];
echo $result1;
echo $result2;
}