I'm trying to take an array and insert it into seperate rows in a MYSQL database.
Basically, there's an HTML form for a top 5 list that I want to input in one field, but with each value seperated by commas. So, for example (Artist 1, Artist 2, Artist 3, etc.)
These 5 values then have to be seperated into 5 values that are then inserted into 5 rows in a MYSQL database.
So the HTML form looks like this:
<tr>
<td>Loud Rock</td>
<td><label for="lr_topfive"><input type="text" placeholder="" name="lr_topfive" size="75"
maxlength="100" autofucus required /></label></td>
</tr>
and the form value is sent to another php file with this code in it:
$val = $_POST['lr_topfive'];
$data = str_getcsv($val);
??????
$lr_one = mysql_prep($_POST['lr_one']);
$lr_two = mysql_prep($_POST['lr_two']);
$lr_three = mysql_prep($_POST['lr_three']);
$lr_four = mysql_prep($_POST['lr_four']);
$lr_five = mysql_prep($_POST['lr_five']);
$query = "INSERT INTO xyz_wb (lr_one, lr_two, lr_three, lr_four, lr_five) VALUES ('{$lr_one}','{$lr_two}', '{$lr_three}', '{$lr_four}', '{$lr_five}')";
$result = mysql_query($query, $connection);
if ($result) {
redirect_to("email-ready.php");
} else {
//display error message
echo "<p>Yikes!</p>";
echo "<p>" . mysql_error() . "</p>";
}
I get that the 'lr_topfive' value is parsed and seperated into distinct values by the first two lines, but I dont know what to do before inserting these values into the MYSQL DB.
I think you are just looking for:
$top_five_array = explode(',', $_POST['lr_topfive']);
and then:
$lr_one = mysql_prep($top_five_array[0]);
$lr_two = mysql_prep($top_five_array[1]);
....
However, this will break if there are not exactly 4 comma's in your input field.
Apart from that you need to switch to prepared statements using PDO or mysqli, see the comments below your question.
Related
I want the user be able to check multiple checkboxes, after which his/hers selection is printed on the html page and add each selection to my Mysql db. Unfortunately I only see the literal string 'Array' being added to my db instead of the selected names.
My script looks as follows :
<html>
<head>
<title>checkbox help</title>
</head>
<?php
if (isset($_POST['submit'])) {
$bewoner_naam = $_POST["bewoner_naam"];
$how_many = count($bewoner_naam);
echo 'Names chosen: '.$how_many.'<br><br>';
if ($how_many>0) {
echo 'You chose the following names:<br>';
}
for ($i=0; $i<$how_many; $i++) {
echo ($i+1) . '- ' . $bewoner_naam[$i] . '<br>';
}
echo "<br><br>";
}
$bewoner_naam = $_POST['bewoner_naam'];
echo $bewoner_naam[0]; // Output will be the value of the first selected checkbox
echo $bewoner_naam[1]; // Output will be the value of the second selected checkbox
print_r($bewoner_naam); //Output will be an array of values of the selected checkboxes
$con = mysql_connect("localhost","usr","root");
mysql_select_db("db", $con);
$sql="INSERT INTO bewoner_contactgegevens (bewoner_naam) VALUES ('$_POST[bewoner_naam]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con)
?>
<body bgcolor="#ffffff">
<form method="post">
Choose a name:<br><br>
<input type="checkbox" name="bewoner_naam[]" value="kurt">kurt <br>
<input type="checkbox" name="bewoner_naam[]" value="ian">ian <br>
<input type="checkbox" name="bewoner_naam[]" value="robert">robert <br>
<input type="checkbox" name="bewoner_naam[]" value="bruce">bruce<br>
<input type="submit" name = "submit">
</form>
</body>
<html>
Thank you so much with helping me!!!
Kindest regards,
Martin
You can't insert an array into a singular column, it will show up as "array" as you're observing, so you've got two choices:
Insert multiple rows, one for each item, by looping over that array.
Combine them together using implode into a singular value.
The way your database is structured in your example it's not clear which of these two would be best.
Since $_POST['bewoner_naam'] is an array, you have to add each item in that array to the database. You can for example use a for loop for this:
$con = mysql_connect("localhost","usr","root");
mysql_select_db("db", $con);
foreach($_POST['bewoner_naam'] as $naam) {
$sql="INSERT INTO bewoner_contactgegevens (bewoner_naam) VALUES ('". mysql_real_escape_string($naam) ."')";
}
Note that I've used the mysql_real_escape_string function. You will ALWAYS want to include this. For the why and how, see: Sanitizing PHP/SQL $_POST, $_GET, etc...?
First thing is to avoid all mysql_* functions in PHP. They are deprecated, and removed in newer versions, and to top it all of, insecure. I advise you switch to PDO and use prepared statements.
This will not solve your issue however. The issue you are having is that in the code where you combine the SQL you are concatenating the array with the string, that's why you only insert "Array". If you wish to insert all array items as a string, then you need to implode the array:
$sql = "INSERT INTO bewoner_contactgegevens (bewoner_naam) VALUES (:checkboxes)";
$statement = $pdo->prepare($sql);
$statement->bindValue(":checkboxes", implode(",", $_POST["bewoner_naam"]);
$statement->execute();
Although, storing multiple values as a comma separated list in a database is not such a good idea, since it can become too un-maintainable through time, and produces more difficulty when obtaining such data, because you need to "re-parse" it after retrieving it from data.
As #Rodin suggested, you will probably want to insert each array item as a separate row, so I propose the following:
$sql = "INSERT INTO bewoner_contactgegevens (bewoner_naam) VALUES "
. rtrim(str_repeat('(?),', count($_POST["bewoner_naam"])), ',');
$statement = $pdo->prepare($sql);
$count = 1;
foreach ($_POST["bewoner_naam"] as $bewoner_naam) {
$statement->bindValue($count++, $bewoner_naam);
}
$statement->execute();
This way you will create a bulk insert statement, with as many placeholders as there are selected checkboxes, and put each of their values on a separate line in the database.
For more on PDO, and parameter binding please refer to http://www.php.net/pdo
I am trying to get cell value which is at the intersection of row and column number entered by user, as like in matrices, like if user enters row 5 and column 4 then my result should show the value present in the cell [5.4].
I am getting row and column number as:
<td>Please enter the temperature:</td>
<td><input type="text" name="temp" /></td>
<td>Please enter the column:</td>
<td><input type="text" name="col" /></td>
<td><input type="submit" name="go" /></td>
i am redirecting these values to find.php page, where i am doing this:
$entry1 = $_POST['temp'];
$entry2 = $_POST['col'];
$result = mysql_query("SELECT * FROM tables WHERE Temperature LIKE '".$entry1."'
AND COLUMN_NAME = '".$entry2."' ");
and showing my result as
<td ><?php echo (don't know what to write here) ; ?></td>
i know i am making lot of mistakes but do not know how to fix them. Please show me way.
If you want to get values at [Temperature ,COLUMN_NAME] then change query to
$result = mysql_query("SELECT * FROM tables WHERE Temperature = '".$entry1."'
AND COLUMN_NAME = '".$entry2."' ");
Because LIKE will look all string containing $entry1.
For example if $entry = 10 the it will select column with values like 10, 110, 100,...
after executing the query fetch data like this
if the no of rows returned is more than one the loop it with while like this
while ($row = mysql_fetch_array($result))
{
echo $row[$entry2];
}
or if it return only one value or you need only first value when it returns more than one value try this
$row = mysql_fetch_array($result);
echo $row[$entry2];
Also try to avoid using mysql_* functions and start using mysqli_* function or PDO
I have some simple PHP code that will generate new text boxes with the naming scheme of 'car_init$i' and 'car_num$i'. Where $i = 1 and I use i++ to increment it up. The problem I'm having is that while a user can have a maximum of 70 text boxes generated, it can be any number between 1 and 70. So I can have 46 text boxes as an example on a page if the user wanted just 46. So I would have car_num1, car_num2, car_init1, car_init2, etc. as my form names.
Car_ID would be my auto-incremented primary key, and I'd have 2 columns car_num and car_init. Is it possible to do something like this: INSERT INTO dbo (car_init, car_num) VALUES (car_init$i, car_num$i) and then use $i = 1 and i++ to increment it while adding all the values to new rows? Car_id = 1 would contain car_num1 and car_init1 information in their respective columns, Car_id = 2 would contain car_num2 and car_init2 information, and so on and so forth.
EDIT:
So this is the code I have now:
$car_num = $_POST["car_num"];
foreach($_POST['car_init'] as $key => $car_init)
{
// your insert query
$sql = "INSERT INTO CustBill_cars (C_ID, car_init, car_num) VALUES ('1', '".$car_init."', '".$car_num[$key]."')";
}
What happens is every time I add to my database, only the last thing I entered gets inputted. So if I have 3 cars needed, that's 6 text boxes, but only the last text boxes on the page are the ones that get inputted.
EDIT 2: This is how my text boxes are generated. All text boxes have it the way you said, using the 'car_init[]' and 'car_num[]'.
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$i = 1;
while ($i <= $_POST['carAmount'] AND $i <= 70) {
// Now print the text box to the screen
echo "<b>$i</b>. Car Initial: <input type=\"text\" class='element text small' name=\"car_init[]\" maxlength='4' id='car_init[]' /> ";
echo "Number: <input type=\"text\" class='element text small' name=\"car_num[]\" maxlength='6' id='car_num[]' /><br>";
$i++;
}
}
Ah, I think I got it.
This is a problem:
foreach($_POST['car_init'] as $key => $car_init)
{
// your insert query
$sql = "INSERT INTO CustBill_cars (C_ID, car_init, car_num) VALUES ('1', '".$car_init."', '".$car_num[$key]."')";
}
I assume you're then running the query $sql? If so, that is running only the last value $sql contained! You need to:
foreach($_POST['car_init'] as $key => $car_init)
{
// your insert query
$sql = "INSERT INTO CustBill_cars (C_ID, car_init, car_num) VALUES ('1', '".$car_init."', '".$car_num[$key]."')";
// actually run the query!
}
Change your html to something like this:
<input name="car_init[]" />
<input name="car_init[]" />
<input name="car_init[]" />
<input name="car_init[]" />
<input name="car_init[]" />
Then in php, your variable will be an array!
$_POST['car_init'] // is an array!
Loop through those and do multiple INSERTs.
foreach ($_POST['car_init'] as $car_num => $car_init) {
// "INSERT INTO dbo (car_init, car_num) VALUES ('$car_init', $car_num)"
}
Edit based on your updates:
INSERT INTO CustBill_cars (C_ID, car_init, car_num) VALUES ('1', '".$car_init."', '".$car_num[$key]."')"
Use PDO with prepared statements instead of using string interpolation. You seem to be susceptible to sql injection attacks.
I have an array of checkboxes.
<input type="checkbox" name="selection[]" value="move" />
<input type="checkbox" name="selection[]" value="move2" />
<input type="checkbox" name="selection[]" value="move3" />
<input type="checkbox" name="selection[]" value="move4" />
Depending on the number of checkboxes selected, a table with corresponding number of rows is generated.
for($x=0; $x<$N; $x++)
{
echo nl2br("<td><textarea name=art[] rows=10 cols=30></textarea> </td><td><textarea name=science[] rows=10 cols=30></textarea></td></textarea></td><td><textarea name=method[] rows=10 cols=30></textarea></td><td><textarea name=criteria[] rows=10 cols=30></textarea></td></tr>");
}
I cannot tell how many table rows with corresponding columns will be generated each time. So how to write the code to insert each set of row array is a problem. I have tried the
$optionsVal = implode(",", $data);
but that only works to store the selected options and not for the generated table rows and columns.Please can anyone help with this. Thanks in advance
Okay so I think I understand a little better, but perhaps you should relay your question in other terms.
Basically my understanding is that you are accepting an uncertain (within the boundaries of the number of checkboxes you have) number of checkboxes, which there in turn generate a row for each selected check box.
If you want to store these generated rows in mySQL you need to post the data back to the database
$result = mysqli_query($query, $conn);
$row = mysqli_fetch_array($result);
You need to set a $result similar to this, and store your check box values in it
In this example if the end-user hits the save button it inserts the values from the check box into a variable
if(isset($_POST["savebtn"]))
{
//inserting the new information
$id = $_POST[""];
$name = $_POST[""];
//iterate through each checkbox selected
foreach($_POST["checkbox"] as $loc_id)
{
$query = "INSERT INTO table(ID, Loc_Code) VALUES('$id', '$loc_id')";
$result = mysqli_query($query, $conn);
}
?>
This was just kinda taken from another example, but you are way off with the implode, you need to save the results of the php selection to variables first, and then assign them rows in mySQL by looping through the selection
UPDATE:
Okay, so you got them in an array, seelction[] - this is good now you would want to check to see if a certain value is selected...
if (in_array("move2", $_POST['selection'])) { /* move2 was selected */}
then you want to put that into a single string - you were right with the implode method
echo implode("\n", $_POST['selection']);
then echo it out with a foreach loop
foreach ($_POST['selection'] as $selection) {
echo "You selected: $selection <br>";
}
I've searched extensively but can't find an answer… Hope someone can help:
I'm a newbie PHP and MySQL user and have a problem with checkboxes.
I have a simple HTML page which contains checkboxes.
The page is linked up to a MySQL db in PHPmyadmin.
The HTML is:
<html><p>User1<input type="checkbox" name="Users[]" id="Users1" value="1"/></p>
<p>User2<input type="checkbox" name="Users[]" id="Users2" value="2"/></p>
<p>User3<input type="checkbox" name="Users[]" id="Users3" value="3"/></p>
<p>User4<input type="checkbox" name="Users[]" id="Users4" value="4"/></p></html>
What I want is for the person filling in the form to check 1 or more of the values and then for the checked values to be displayed in PHPmyadmin, so that I can export them.
However, when using this PHP:
$values = implode(',', $_POST['Users']);
All I get in PHPmyadmin is "Array", and I can't figure out how to get the actual values to be displayed.
Thanks in advance,
You can get all value checked by looping :
$userChecked = $_POST['Users'];
for ($i=0; $i<count($userChecked ); $i++) {
echo( ($i+1) . ") " . $userChecked [$i] . "<br/>");
}
This will display all id. Instead of echo the value you can insert them in your database or do what you want. The values will be loop inside : $userChecked [$i]
#Daok: Yes, that displays the values
on the results page, but in
PHPmyadmin, it still indicates
"Array". How do I get it to display
the values?
PhpMyAdmin is just a tool to administrate php/mysql. I guess you mean that you have "array" written in your database? If you do want all value inside a field (varchar) than you just have to implode:
$comma_separated = implode(",", $_POST['Users']);
//Code here to Insert to you database with ...value($comma_separated)...
If you want 1 row for each entry :
$userChecked = $_POST['Users'];
for ($i=0; $i<count($userChecked ); $i++) {
//Insert Sql statement here with value($userChecked [$i])
}
try
$values = implode(',', (array)$_POST['Users']);
or
Users=array();
$values = implode(',', $_POST['Users']);