User creation in php, mysql using for loop and insert query - php

I need to create n number of users with n username and password.
If I give the input 5, abc. 5 Users should be created with the username and password such as abc1, abc2, abc3, abc4 and abc5.
How can I do this in for loop by giving the mysql insert query?
Here are my forms
create.php
Create User :
<br><br>
<form action="add_res.php" method="post">
Count : <input type = "text" name="count"><br>
Name : <input type = "text" name="val">
<input type = "submit">
</form>
and the add_res.php
<?php
$count=$_POST['count'];
$val=$_POST['val'];
include ('config.php');
echo "<b>".$count." Users Created"."</b>"."<br>";
echo "<u>"."The Users' List is given below"."</u>";
for ($i=1; $i <=$count; $i++)
{
$select=mysql_query("insert into student (username, password) VALUES
('$con', '$con')");
}
?>
I don't have idea about implementing the proper for loop and the proper insert query. How can i achieve it?

Use the for loop and the insert query by the below format,
<?php
$count=$_POST['count'];
$val=$_POST['val'];
include ('config.php');
echo "<b>".$count." Users Created"."</b>"."<br>";
echo "<u>"."The Users' List is given below"."</u>";
for ($i=1; $i <=$count; $i++)
{
echo "<br>";
echo $val.$i;
$con=$val.$i;
$select=mysql_query("insert into student (username, password) VALUES
('$con', '$con')");
}
?>

Several of the other answers here have indicated how to properly set up the variables to send with your MySQL query, but every single one of them, as well as your original code, contains a classic SQL injection vulnerability! Especially since you are getting your input directly from $_POST, this will allow an attacker complete control over your database -- reading data, resetting passwords, anything.
One way to solve the problem is to escape the input to mysql_query. A version which both solves your original question and the security issue might look like this:
<?php
include ('config.php');
$count = $_POST['count'];
$val = $_POST['val'];
echo "<b>".$count." Users Created</b><br>";
echo "<u>The Users' List is given below</u>";
echo "<ul>";
for ($i = 1; $i <= $count; $i++)
{
echo "<li>";
$name = $val . $i;
$name = mysql_real_escape_string($name);
mysql_query("insert into student (username, password) VALUES ('$name', '$name')");
}
echo "</ul>";
However, this still uses mysql_query, and while mysql_real_escape_string solves the aforementioned security problem, is not the preferred way to write MySQL queries. I believe PDO is the recommended way to do so now.

Just create a variable with the $val variable then put the $i variable at the end. Then insert that.
for ($i=1; $i <=$count; $i++)
{
$con = $val.$i;
$select=mysql_query("insert into student (username, password) VALUES ('$con', '$con')");
}

Replace this instead of your loop
for ($i=1; $i <=$count; $i++)
{
echo "<br>";
echo $val.$i;
$con=$val.$i;
$select=mysql_query("insert into student (username, password) VALUES ('".$con."', '".$con."')");
}

Related

PHP- is unable to read the other checked checkbox

I stored the data in a supposed to be an array but what happens is that only the last checked checkbox is the only one that is registered in the idSkills. This is the part of the code wherein the skills are displayed through a query in the database
<?php
$i=0;
while ($row = mysqli_fetch_assoc($result)) {
$id=$row['id'];
$skillName=$row['skillName'];
?>
<input type="checkbox" name="skills[]" value="<?php echo $id; ?>"><?php echo $skillName; ?><br>
<?php
$i++;
}
?>
Here is the part where the loop unveil all of the selected checkbox
//QUERY TO INSERT
$conn = new mysqli($config['servername'], $config['username'], $config['password'], $config['database']);
$idSkills = $_GET['skills'];
if(empty($idSkills))
{
echo("You didn't select any buildings.");
}
else
{
$N = count($idSkills);
echo("You selected $N door(s): ");
echo("$idSkills[1] ");
for($i=0; $i < $N; $i++) {
echo "Skill ID: "
$sql = "INSERT INTO volunteer_skills (idskill,idVolunteer)
VALUES ('$idSkills[$i]','$idVolunteer')";
$result = $conn->query($sql);
}
}
$conn->close();
It would be best to use a prepared statement instead of substituting a variable into the SQL. But if you're going to do it this way, you need to use the correct syntax:
$sql = "INSERT INTO volunteer_skills (idskill,idVolunteer)
VALUES ('{$idSkills[$i]}','$idVolunteer')";
You need to put {} around an array reference in order to get the variable inside the brackets to be evaluated. See the section on Complex (curly) Syntax in the PHP Strings documentation.

How to add multiple selection checkboxes to mysql db?

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

How to retrieve imploded array from a cell in an MySQL database through PHP

Thanks for taking the time to look at this question.
Currently, I have a piece of code that creates four checkboxes labeled as "Luxury, Brand, Retailer," and "B2B." I have looked into a number of PHP methods to create checkboxes, and I felt the implode() function was the most simple and suitable for my job. I have looked into a number of tutorials to create the implosions, however, they did not fit my criteria, as I would like the database values be reflected in the front-end. Currently in my database, the implode() works, therefore (for example), if I check "Luxury", "Brand", "Retailer", and press the "Submit" button, the three items "Luxury, Brand, Retailer" will be in that specified cell. It looks like my code works in the back-end, but these are my issues:
I am not exactly sure (despite multiple Googles) how to retrieve those values stored in the single-cell array, and have it selected as "selected" (this would "check" the box in the front-end)
Could someone kindly take a look at my code below and let me know what seems to be missing/wrong/erroneous so I could attempt the revisions? Anything would be appreciated, thank you!
<?
if (isset($_POST['formSubmit2'])){
$category = mysql_real_escape_string(implode(',',$_POST['category']));
$accountID = $_POST['accountID'];
mysql_query("UPDATE Spreadsheet SET category='$category' WHERE accountID='$accountID'");
}
$query = mysql_query("SELECT * FROM Spreadsheet LIMIT $firstRow,$rpp");
while($row = mysql_fetch_array($query)){
// Begin Checkboxes
$values = array('Luxury','Brand','Retailer','B2B');
?>
<form name ="category" method ="POST" action ="" >
<?
echo "<input type = 'hidden' name = 'accountID' value = '" . $row['accountID'] . "' >";
for($i = 0; $i < count($values); $i++){
?>
<input type="checkbox" name="category[]" value="<?php echo $values[$i]; ?>" id="rbl_<? echo $i; ?>" <? if($row['category'] == $i) echo "checked=\"checked\""; ?>/>
<? echo $values[$i] ?><br>
<? } ?>
<input type ="Submit" name ="formSubmit2" value ="Submit" />
</form>
<? } ?>
The best approach i can recommend given what you have is to, explode the values out of the db giving you a new array of all the select fields. Then use in_array to compare the list you have with this new list in the loop. then flag the checkboxs as needed.

Foreach $_POST results from form, returning the word "Array"

Language: PHP / MySQL
I have a form on a page, with hidden inputs. I forward the data from these inputs on to another page, then I insert them into my database.
The inputs inside the form are:
copied_filename[]
copied_url[]
copied_userid[]
These are set-up to be arrays because there are times that a user will have more than one file attached.
<input type="hidden" id="copied_filename" name="copied_filename[]" value="<?php echo $img->filename; ?>" />
<input type="hidden" id="copied_url" name="copied_url[]" value="<?php echo $img->url; ?>" />
<input type="hidden" id="copied_userid" name="copied_userid[]" value="<?php echo $current_user->id; ?>" />
Now on the 2nd page where the data is received, this is how I handle it:
if (empty($_POST["copied_filename"])) {
WHAT IT DOES WHEN THERE ARE NO ATTACHED FILES
}
else {
$copied_filename = $_POST["copied_filename"];
$copied_url = $_POST["copied_url"];
$new_sessionid = $_POST['session_id'];
foreach ($_POST["copied_filename"] as $copied_file) {
$sql = "INSERT INTO ".$wpdb->prefix."estimate_images (code, url, filename, session_id, user_id) VALUES ('".$code."', '".$copied_url."', '".$copied_file."','".$new_sessionid."', '".$current_user->id."')";
$wpdb->query($sql);
}
It works fine for the filename, but the URL being inserted in my database is the word "Array"...
I am sure it is the foreach format, but I am stumped & don't know how to fix it.
Thank you so much for your time, any assistance would be greatly appreciated!
if (empty($_POST["copied_filename"])) {
//WHAT IT DOES WHEN THERE ARE NO ATTACHED FILES
}
else {
$new_sessionid = $_POST['session_id'];
foreach ($_POST["copied_filename"] as $k => $copied_file) {
$copied_url = $_POST["copied_url"][$k];
$sql = "INSERT INTO ".$wpdb->prefix."estimate_images (code, url, filename, session_id, user_id) VALUES ('".$code."', '".$copied_url."', '".$copied_file."','".$new_sessionid."', '".$current_user->id."')";
$wpdb->query($sql);
}
}
Because they are arrays. echo cannot correctly display an array. Use print_r or var_dump to see the correct structure.
If you want to access the first element, you need to echo $_POST["copied_filename"][0].
If you want to access all of the elements, iterate it with a foreach loop.
Your foreach is working on copied_filename only. For your situation try in this way:
foreach ($_POST["copied_filename"] as $key => $val)
{
$sql = "INSERT INTO ".$wpdb->prefix."estimate_images (code, url, filename,
session_id, user_id) VALUES ('".$code."', '".$copied_url[$key]."',
'".$val."','".$new_sessionid."', '".$current_user->id."')";
$wpdb->query($sql);
}
$copied_url is an array.
To get the URL you have to do something like e.g. $copied_url[0].
In your case maybe simething like this could work:
for($i=0; $i< count($_POST["copied_filename"]); $i++) {
$sql = "INSERT INTO ".$wpdb->prefix."estimate_images (code, url, filename, session_id, user_id) VALUES ('".$code."', '".$copied_url[$i]."', '".$copied_filename[$i]."','".$new_sessionid."', '".$current_user->id."')";
$wpdb->query($sql);
}

Looping through dynamic input boxes and inserting into mysql database

I need your help with my form. I'm trying to build a dynamic forms, whereby a specific integer entered in a previous form sp1.php is used to display the number of input boxes.
The variables from the first forms are $state and $number. Then on the handling page sp2.php, the value of $number is put into a for loop to display the input boxes.
What I'm trying to do now is that the values entered into the tinput boxes are inserted into a mysql table.
The error I'm getting are
1) Undefined Index : DISTRICT
2) Invalid Argument supplied for foreach()
Please how can I make this work. Thank you.
My Code is below.. I'll be more than happy to show other parts of the code, if required.
Thank you.
<?php
$state=htmlspecialchars(($_POST['state'])) ;
$number = intval(($_POST['number']));
for ($i = 0; $i < $number ; $i++ ) {
echo "
<form action='sd2.php' method='post'>
<label for='name'>Districts</label>
<input type='text' name='district[]'>
<br/><br/>
</form>";
}
?>
<?php
foreach($_POST['district'] as $senatorial) {
$query = "INSERT INTO state ( `state_id`, `state`, `senatorial`)
VALUES (NULL, '".$state."', '".$senatorial."') ";
mysql_query($query) or die (mysql_error());
}
?>
This must work:
$count = count($_POST['district']);
for ($i=0; $i<$count; $i++){
$district = $_POST['district'][$i];
//do this
//do that
}

Categories