I have two fields
<form action="insert.php" method="post">
Firstname: <input type="text" name="firstname" />
Lastname: <input type="text" name="lastname" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
how to post name and lastname in one variable meaning in one field of database
is it
<?php
$name=$_post['firstname']['lastname'];
?>
Actually you have three fields. Use string concatenation (or implode):
$name = $_POST['firstname'] . ' ' . $_POST['lastname'];
And don't forget to use mysql_real_escape_string (or what #ThiefMaster says) if you store the values in a database. Never trust user input.
Just concatenate the two values e.g.
<?php
$name = $_POST['firstname'] . $_POST['lastname'];
?>
keep an array, and serialize it to store it.
$name['firstname']=$_post['firstname'];
$name['lastname']=$_post['lastname'];
//storage and retrieval methods
$stored_name = serialize($name);
$name = unserialize($stored_name);
This way you don't lose the functionality of having the variables separate in an array, and you can always concatenate them later for display if you need to.
You can give the text inputs the same name with []
Firstname: <input type="text" name="name[]" />
Lastname: <input type="text" name="name[]" />
then you can
$name = $_POST['name'][0].$_POST['name'][1];
but i would prefer
$name=$_post['firstname'] . ' ' . $_post['lastname'];
This One will help You...! I also implemented this and it works...!
Firstname: <input type="text" name="firstName" />
Lastname: <input type="text" name="lastName" />
$fullname = $_post['firstName']. ' ' .$_post['lastName'];
$name = $firstname . " " . $lastname;
Then post $name in whatever field you want.
I had this same problem, i have a form with the name of the person reporting the issue and it takes the first name and the last name from my database of users and adds them together, but then when it came time to post both names to the database it would only post the first name.
my solution was to first of all call the first name and last name from the database of users, then i called just the first name and last name and concat them together to produce reportername.
so this is the first part of the code calling for the user details i require for the form:
// Select the member from the users table
$sql = "SELECT * FROM users WHERE username='$log_username' AND activated='1' LIMIT 1";
$user_query = mysqli_query($db_conx, $sql);
// Now make sure that user exists in the table
$numrows = mysqli_num_rows($user_query);
if($numrows < 1){
echo "That user does not exist or is not yet activated, press back";
// exit();
}
// Fetch the user row from the query above
while ($row = mysqli_fetch_array($user_query, MYSQLI_ASSOC)) {
$profile_id = $row["id"];
$first_name = $row["First_Name"];
$last_name = $row["Last_Name"];
$userlevel = $row["userlevel"];
}
Next i Concat the first name and last name:
$reporter_sql = "SELECT CONCAT (First_name,' ', Last_name) AS reportername FROM users WHERE username='$log_username' AND activated='1' LIMIT 1";
$reporter_results = mysqli_query($db_conx, $reporter_sql);
while ($row = mysqli_fetch_array($reporter_results, MYSQLI_ASSOC)){
$reportername = $row['reportername'];
}
then you can post it to your database:
$reportername = mysqli_real_escape_string($db_conx, $reportername);
$sql = "INSERT INTO yourform (`reportedby`) Value ('$reportername')";
I have striped my code down so it gives you an idea and I'm sure coders with more experience could tell you a simpler way to do this i just know it worked for me.
A shortcut way to concatenate variables is this:
$name = "$_POST[first_name] $_POST[last_name]"
General comment. A good proportion of the world don't have first and last names.
Better practice is just to ask for "Name", and stick it in one field.
If you must split 'em, then "given name" and "family name" are better labels.
Related
So i am trying to create a HTML front end that can use a text field to search an SQL Database. But there are multiple columns that can be searched, and many columns that contain numbers or letters. The User can search one or many of the columns at a time.
In my own test server, I've tried breaking down the possible queries into dropdown lists; and have switch cases to handle the selections. But this hasn't worked. My ultimate goal would be to have the textbox host all the query data, and have it passed to a prepared statement
So my question; is there a way to make a prepared statement adaptable, to handle single search cases or multiple search case. eg. WHERE column1 LIKE query1 (AND column2 LIKE query2).
Here's a basic concept, obviously you need to do your own validation and sanitizing etc. In your html use an array to hold all the form values:
<form action="#" method="post">
Col1:<br>
<input type="text" name="database[column1]"><br>
Col2:<br>
<input type="text" name="database[column2]"><br>
Col3:<br>
<input type="text" name="database[column3]"><br>
Then process that array to prepare a query
$input = $_POST['database']; // Assign all form variables to $input
$input = array_filter($input, 'strlen'); // Remove any form fields which were submitted with empty values
$where = implode(' AND ', (array_map(function($a){return "'$a' LIKE ?";}, array_keys($input)))); // Assemble your list of WHERE clauses
$statement = $dbo->prepare("SELECT * FROM table WHERE $where");
$statement->execute(array_values($input)); // Execute statement with corresponding variables
You can use this database query to get a list of columns for your table. Then using array_intersect_key you could filter out and column names which were submitted but did not exist in the table
SELECT column_name FROM information_schema.columns WHERE table_name='table';
This maybe long-winded and I am sure there are better approaches where you could loop it out or array. *Col1 text box must have data for this to work due to the "AND", I hope this helps.
<form action="#" method="post">
Col1:<br>
<input type="text" name="Col1"><br>
Col2:<br>
<input type="text" name="Col2"><br>
Col3:<br>
<input type="text" name="Col3"><br>
Col4:<br>
<input type="text" name="Col4"><br>
<input type="submit" name="search" value="Search"><br>
</form>
<br />
<br />
<?php
$SQL_Claus = "";
if (!empty($_POST['Col1'])){
$Col1 = $_POST['Col1'];
$SQL_Claus = $SQL_Claus . " Col1 LIKE " . $Col1;
}
if (!empty($_POST['Col2'])){
$Col2 = $_POST['Col2'];
$SQL_Claus = $SQL_Claus . " AND Col2 LIKE " . $Col2;
}
if (!empty($_POST['Col3'])){
$Col3 = $_POST['Col3'];
$SQL_Claus = $SQL_Claus . " AND Col3 LIKE " . $Col3;
}
if (!empty($_POST['Col4'])){
$Col4 = $_POST['Col4'];
$SQL_Claus = $SQL_Claus . " AND Col4 LIKE " . $Col4;
}
$SQL_Statement = "SELECT * FROM TABLE WHERE ".$SQL_Claus;
echo $SQL_Statement;
?>
I currently have a form that creates an item in a database then in the next step it allows the user to upload multiple images for that listing both sections work on their own but i need to be able to insert the $id from the first page into the query for the image upload to identify which listing it corresponds to
Here is the page to allow the user to upload multiple images
<input name="name" type="text" id="name" size="40" placeholder="Homestay's Name"/>
<input name="type" type="text" id="type" size="40" placeholder="Homestay's Type"/>
<input name="category" type="text" id="category" size="40" placeholder="Homestay's Category"/>
<input class='file' multiple="multiple" type="file" class="form-control" name="userfile[]" placeholder="Please choose your image">
here is the function
$path = pathinfo($_SERVER['PHP_SELF']);
for ($i = 0; $i < count ($_FILES['userfile']['name']); $i++)
{
$tmp_file = $_FILES['userfile']['tmp_name'][$i];
$filetype = $_FILES['userfile']['type'][$i];
$filesize = $_FILES['userfile']['size'][$i];
$filename = $_FILES['userfile']['name'][$i];
$destination = $path['dirname'] . '../data/' . $filename;
if (move_uploaded_file($tmp_file, $_SERVER['DOCUMENT_ROOT'] . $destination))
{
$name = $_POST['name'];
$type = $_POST['type'];
$category = $_POST['category'];
$sql="INSERT INTO homestay (name, type,category,)
VALUES
('$name', '$type','$category')";
$result = mysql_query ("insert into img_homestay (id, location,filetype, filename, filesize)
values ('".$id."', '" . $destination . "','" . $filetype ."','" . $filename . "'," . $filesize . ") ");
}
}
If I understood your question:
In the previous page you have the id from the list.
At the second page, put it into a hidden field like:
<input type="hidde" name="theId" value="<?php echo $_POST["idFromPrevPage"]; ?>" />
And then you can access it from $_POST["theId"]
EDIT:
Based on your comment, I think, you want to do something like this:
$sql = "INSERT INTO homestay (name, type,category) VALUES ('".mysql_real_escape_string($name) ."', "
. "'".mysql_real_escape_string($type)."','".mysql_real_escape_string($category)."')";
$res = mysql_query($sql);
$id = mysql_insert_id(); //This where you can get the last insert id.
NOTES
Anyway, you have several problems in your original code:
In your first insert query have an unwanted , character at the field list.
Do not use mysql_* functions, they are deprecated. Use mysqli_* functions or PDO!
Escape your data to avoid sql vulnerables or use prepared statements.
I think your best bet would be :
create the form to insert the db item
get the ID of the inserted item, and add it as a hidden element on the second step
once the second form gets back, you can easily see the ID you need.
Do note that this approach will send DB id's client side, but is the simplest option.
A second approach is to utilize session variables - simply store the item ID to the user session, and retrieve it on the second step. This is safer, but not a good approach if multiple forms can be submitted at the same time by the same account/person.
$_SESSION['the_id'] = $result->id;
and then
$id = $_SESSION['the_id'];
The best approach (in my opinion always) is to use a non-sensical token to the client side, and map it to the proper ID using some logic. A simple example is to generate a complex hash for the ID, and send that as a hidden field to the user when sending the form for step 2. Store the ID and hash in a database table.
When the user POSTs that back, use the hash to map it back to a normal ID, and destroy the entry.
I have a registration form that allows a user to register as many people as they want. For example I don't know ahead of time if 1 person is registering or if 500 are. So on the server side if I have 3 people registering at once I need to access all the first names of a person by $_POST['first0'] $_POST['first1'] and $_POST['first2']. So here is my database query.
for ($i=0; $i < runners; $i++) {
$query = "INSERT INTO ".$usertable." VALUES (".$_POST['first'.$i].", ".$_POST['last'.$i].", ".$_POST['age'.$i].",
".$_POST['gender'.$i].", ".$_POST['email'.$i]." , ".$_POST['phone'.$i]." , ".$_POST['address'.$i]." ,
".$_POST['city'.$i]." , ".$_POST['state'.$i]." , ".$_POST['zip'.$i]." , ".$_POST['type'.$i]." , ".$_POST['tshirt'.$i].")";
My query is not working so I know my quotes and apostrophes are incorrect would anyone be able to show me the correct way to accomplish this. Any help is appreciated!
First of all, posted data is a lot easier to work with if your form entries use the array syntax, i.e.:
<label>First: <input name="first[]" value="" /></label>
<label>Last: <input name="last[]" value="" /></label>
<label>Age: <input name="age[]" value="" /></label>
<label>Gender:
<input type="radio" name="gender[]" value="m" />Male
<input type="radio" name="gender[]" value="f" />Female
</label>
Then, in your code, values like $_POST['first'] are an array of values.
Secondly, you should look at prepared statements. Observe:
$stmt = $db->prepare('INSERT INTO mytable (first, last, age, gender) VALUES (?, ?, ?, ?)');
foreach ($_POST['first'] as $index => $value) {
$stmt->execute(array(
$value,
$_POST['last'][$index],
$_POST['age'][$index],
$_POST['gender'][$index],
));
}
First of all, you should prevent SQL injection while interacting with database.
Use mysqli_real_escape_string. Here is the updated query.
for ($i=0; $i < runners; $i++) {
$firstname = mysqli_real_escape_string($_POST['first'.$i]);
$lastname = mysqli_real_escape_string($_POST['last'.$i]);
$age = mysqli_real_escape_string($_POST['age'.$i]);
$gender = mysqli_real_escape_string($_POST['gender'.$i]);
$email = mysqli_real_escape_string($_POST['email'.$i]);
$phone = mysqli_real_escape_string($_POST['phone'.$i]);
$address = mysqli_real_escape_string($_POST['address'.$i]);
$city = mysqli_real_escape_string($_POST['city'.$i]);
$state = mysqli_real_escape_string($_POST['state'.$i]);
$zip= mysqli_real_escape_string($_POST['zip'.$i]);
$type= mysqli_real_escape_string($_POST['type'.$i]);
$tshirt= mysqli_real_escape_string($_POST['tshirt'.$i]);
$query = "INSERT INTO ".$usertable." VALUES ('".$firstname."', '".$lastname ."', ".$age .",
'".$gender ."', '".$email ."', ".$phone." , '".$address ."' ,
'".$city."' , '".$state."' , ".$zip." , '".$type."' , '".$tshirt."')";
The better way to do this is instead of using user0, user1, user2, ...
You can actually past the html input text as an array.
e.g:
<!-- first user field -->
<input type="text" name="users[]" />
<!-- second user field -->
<input type="text" name="users[]" />
<!-- third user field -->
<input type="text" name="users[]" />
So your php will look something like this:
$users = $_POST['users'];
foreach ($users as $user) {
insertQuery = "INSERT INTO $userTable VALUES ('".mysqli_escape_string($user)."');
}
Of course the code above is only an example with 1 variable you can apply them to all other variables.
Cheers.
As suggested by #plain jane you are missing a lot of single quotes.
You can use PHP's variable replacement capability like the following. This is much more readable code.
$query = "INSERT INTO $usertable VALUES ('{$_POST['first'.$i]}', '{$_POST['last'.$i]}', '{$_POST['age'.$i]}',
'{$_POST['gender'.$i]}', '{$_POST['email'.$i]}', '{$_POST['phone'.$i]}', '{$_POST['address'.$i]}' ,
'{$_POST['city'.$i]}' , '{$_POST['state'.$i]}' , '{$_POST['zip'.$i]}' , '{$_POST['type'.$i]}' , '{$_POST['tshirt'.$i]}')";
Warning: Your code is vulnerable to SQL injection and can be easily broken with just a single quote in any posted field. even St'Mary as first name will break your code. To prevent this
Please validate/sanitize your posted values
Use Prepared statements instead of direct query string.
I'm having some problems trying to post $_GET variables into a table.
Here is my script:
include 'connect.php';
if(isset($_POST['client_name'])) {
$_GET['list']; //these are variables passed through from another page and I want these to post in the same table this page is suppose to post in.
$_GET['list_id'];
$Cname = $_POST['client_name'];
$Cnumber = $_POST['client_number'];
$listid = $_POST['list_id'];
$listname = $_POST['list'];
if(!empty($Cname) && !empty($Cnumber)){
$query = "INSERT INTO clients (id, client_name, client_number, list_name, date_registered, list_id) VALUES ('$userid','$Cname', '$Cnumber', '$listname', now(), '$listid')";
mysql_query($query);
echo '<br />
<br />
You successfully added a new clients to your list View Update';
mysql_close();
}
else {
echo '<script type="text/javascript">alert("Both fields are required");</script>';
}
Whenever I run the script everything else but the listname and list_id is posted in the database table.
I tried assigning the get variables to new variable such as
$listNAME = $_GET['id'];
but even with that I still end up with empty fields in my table
I even tried to use the $_GET variable in the mysql INSERT query and still no luck
Can anyone help me out and give me some advice as to what I can do to solve the empty fields when the script runs.
<form action="addclient.php" method="POST">
Name of Client: <input type="text" name="client_name">
Client's Number: <input type="text" name="client_number" placeholder="1-876-xxx-xxx">
<input type="submit" >
</form>
You say you have $_GET variables, but you are trying to retrieve them as $_POST variables:
$listid = $_POST['list_id'];
$listname = $_POST['list'];
Isn't it the issue? You could also try this to see what's comming in both arrays:
print_r($_GET);
print_r($_POST);
Alternatively, you could use $_REQUEST as it receives either $_GET or $_POST variables.
I say it only to notice .
Please use PDO or mysqli
if you are calling your addclient.php like
http://localhost/addclient.php?list_id=100&list=mylistname
than you must catch both variables in addclient.php
if (isset($_GET['list_id'])) {
$listid = $_GET['list_id'];
$listname = $_GET['list'];
}
and your form
<form action="addclient.php" method="POST">
<input type="hidden" name="list_id" value="$listid">
<input type="hidden" name="list" value="$listname">
Name of Client: <input type="text" name="client_name">
Client's Number: <input type="text" name="client_number" placeholder="1-876-xxx-xxx">
<input type="submit" >
</form>
and after submit
if(isset($_POST['client_name'])) {
$Cname = $_POST['client_name'];
$Cnumber = $_POST['client_number'];
$listid = $_POST['list_id'];
$listname = $_POST['list'];
....
}
and in your insert
VALUES ('$userid','$Cname', '$Cnumber', '$listname', now(), '$listid')
$listid without quotes it's a int(11) .
VALUES ('$userid','$Cname', '$Cnumber', '$listname', now(), $listid)
I have a table that has the user ID already in it, but some of the information is missing and that is where I need the user to input it themselves. With the URL of the form I have their ID in it... winnerpage.php?ID=123
I am having troubles getting the code to work. Any help would be great!
This is the code on that winnerpage.php
<form enctype="multipart/form-data" action="winnerpage.php" method="POST">
ID: <input name="ID" type="text" value="<?=$ID?>" /><br/>
First Name: <input type="text" name="FN"><br />
Last Name: <input type="text" name="LN"><br />
Email: <input type="text" name="EM"><br />
Phone: <input type="text" name="PH"><br />
<input type="submit" name="edit" value="edit"></form> <br>
<?
require_once('mysql_serv_inc.php');
$conn = mysql_connect("$mysql_server","$mysql_user","$mysql_pass");
if (!$conn) die ("ERROR");
mysql_select_db($mysql_database,$conn) or die ("ERROR");
if(isset($_POST['edit']))
{
$sID = addslashes($_POST['ID']);
$sFN = addslashes($_POST['FN']);
$sLN = addslashes($_POST['LN']);
$sEM = addslashes($_POST['EM']);
$sPH = addslashes($_POST['PH']);
mysql_query('UPDATE winner SET FN=$sFN, LN=$sLN, EM=$sEM, PH=$sPH
WHERE ID=$sID') or die (mysql_error());
echo 'Updated!';
}
$query = "select * from winner order by ID";
$result = mysql_query($query);
?>
<?
while ($link=mysql_fetch_array($result))
{
echo 'Unique ID - Completion Time - First Name - Last Name - Email - Phone<br/>'.$link[ID].' -' .$link[FN].' - '.$link[LN].' - '.$link[EM].' - '.$link[PH].'<br>';
}
?>
1)
ID: <input name="ID" type="text" value="<?=$ID?>" /><br/>
Where do you get that $ID? Are you doing something like $_GET['ID'] or are you relying on safe_mode being ON? (it's not clear from the code you provided)
(better yet, if(isset($_GET['ID'])) { $ID = (int)$_GET['ID'] }
2) Please don't to that. Don't use addslashes(). Use mysql_real_escape_string() or, even better, prepared statements. Addslashes is not utterly reliable in escaping datas for queries.
sID = (int)$_POST['ID'];
$sFN = mysql_real_escape_string($_POST['FN']);
$sLN = mysql_real_escape_string($_POST['LN']);
$sEM = mysql_real_escape_string($_POST['EM']);
$sPH = mysql_real_escape_string($_POST['PH']);
Also, add 'value=""' to each input field (not mandatory)
3) encapsulate values in query:
mysql_query("UPDATE winner SET FN='".$sFN."', LN='".$sLN."', EM='".$sEM."', PH='".$sPH."' WHERE ID='".$sID."'") or die (mysql_error());
Maybe try:
mysql_query("UPDATE winner SET FN='$sFN', LN='$sLN', EM='$sEM', PH='$sPH' WHERE ID=$sID") or die (mysql_error());
mysql_query('UPDATE winner SET FN=$sFN, LN=$sLN, EM=$sEM, PH=$sPH WHERE ID=$sID')
the query is encapsulated by single-quotes, so the variables inside will not be parsed.
At first glance I would say that you need:
1) Quote marks around some of the values you are inserting into the table (any strings for example)
2) Quote marks around the names of the fields when you try to echo them out at the end ($link['ID'] for example)