Concatenate two HTML inputs and insert them into a MySQL database - php

I'm creating this web page for this class that I'm in and for it I need to concatenate two separate HTML form inputs with a space in between and insert them into a MySQL database. Specifically I ask the user for their first name and their last name in separate HTML form inputs and I have to concatenate those two input into a full name with a space in between (or else "Bob" and "Ross" concatenated would be "BobRoss" instead of "Bob Ross"). I don't know where to start when doing that. Also I need to check that the full name isn't already in the database before inserting it into the database, but I'm already doing that with the first name and last name so that shouldn't be too hard.
Here is the HTML page with the form inputs:
<html>
<head>
<link rel="stylesheet" href="Site.css">
<?php include("Header.php"); ?>
</div>
</head>
<body>
<div id="main">
<h1>About</h1>
<form action="Insert.php" method="post">
<p>First name:</p><input type="text" name="firstname"><br>
<p>Last name:</p><input type="text" name="lastname"><br>
<p>Age:</p><input type="text" name="age"><br>
<input type="submit">
</form>
<?php include("Footer.php");?>
</div>
</body>
</html>
And here is the PHP page where it inputs the data into the database. Currently I'm inputing the user's first name, last name, and age, but I need to concatenate the first and last name and make sure it isn't in the database and then insert it into the database and I haven't done that. Currently I make sure that the first name is unique, I make sure that the last name is unique, but I don't care whether the age is unique or not.
<?php
$con = mysql_connect("localhost","a7068104_user2","wiseguy1345");
if(!$con) {
die("could not connect to localhost:" .mysql_error());
}
header("refresh:1.5; url=NamesAction.php");
mysql_select_db("a7068104_world") or die("Cannot connect to database");
$name = mysql_real_escape_string($_POST['firstname']);
$query = "SELECT * FROM names_1 WHERE firstname='$name'";
$result = mysql_query($query);
if(mysql_num_rows($result) > 0 ){
echo "Your name is already in the database and will not be added again!";
}
else {
$query = "INSERT INTO names_1 (firstname) VALUES('$name')";
$result = mysql_query($query);
if($result) {
echo "Your first name was successfully added to the database!";
}
else{
echo "Your first name couldn't be added to the database!";
}
}
$name = mysql_real_escape_string($_POST['lastname']);
$query = "SELECT * FROM names_1 WHERE lastname='$name'";
$result = mysql_query($query);
if(mysql_num_rows($result) > 0 ){
echo "Your name is already in the database and will not be added again!";
}
else {
$query = "INSERT INTO names_1 (lastname) VALUES('$name')";
$result = mysql_query($query);
if($result) {
echo "Your first name was successfully added to the database!";
}
else{
echo "Your first name couldn't be added to the database!";
}
}
$name = mysql_real_escape_string($_POST['age']);
$query = "INSERT INTO names_1 (age) VALUES('$name')";
$result = mysql_query($query);
if($result) {
echo "Your name was successfully added to the database!";
}
else {
echo "Your name couldn't be added to the database!";
}
mysql_close($con);
?>
<html>
<head>
<link rel="stylesheet" href="Site.css">
<?php include("Header.php"); ?>
</div>
</head>
<body>
<div id="main">
<h1>Names</h1>
<p>You will be redirected back to the <b>Names</b> page in a moment.</p>
<?php include("Footer.php");?>
</div>
</body>
</html>

For a start you shouldn't be using mysql functions as this extension
is deprecated as of PHP 5.5.0, and will be removed in the future.
I suggest using the new improved PDO library and PDO Prepared Statements, see here.
As for the concatenation, you could simply do it like this:
$concatenated_name = $_POST['firstname'] . " " . $_POST['lastname'];
This would concatenate the names with a space in between.
You can then use $concatenated_name in your queries.
However I still strongly recommend you use PDO for all your functions.

$fullname = trim($_REQUEST['firstname']).trim($_REQUEST['lastname']);

Related

PHP/HTML forms and database inserting

I am going to start this off by saying -- yes I know there are other links similar to this and topics similar to this and I have read all of them and incorporated them into my code. However, I cannot figure it out and have tried everything I can.
Basically my goal is to take a users input from an html form called socialmedia.html:
<html>
<body>
<h1> Pulse submission page </h1><br>
<form action="action.php" method="post">
Title: <input type="text" name="posttitle"><br><br>
Content: <input type="text" name="content"><br><br>
<input type="submit">
</form>
</body>
</html>
and then send it to a php file called action.php:
<?php
$mysqli = new mysqli("DB HOST IP", "USER", "PASS", "DB NAME");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
echo $mysqli->host_info . "\n";
$posttitle = $_POST["posttitle"];
$content = $_POST["content"];
if(isset($_POST['submit'])){
$sql = "INSERT INTO `posts` (posttitle, content) VALUES ('$posttitle', '$content')";
echo 'post added to database';
}
if($sql){
echo 'success';
}
else{
echo 'failure';
}
$sql = "SELECT * FROM `posts`";
$res = $mysqli->query($sql);
if($res->num_rows > 0){
while($row = $res->fetch_assoc()){
echo "ID". $row["id"]. "<br/>";
echo "Title". $row["posttitle"]. "<br/>";
echo "Content". $row["content"]. "<br/>";
}
}
else
{
echo "No Record Found!";
}
?>
This file is SUPPOSED to insert the user's form values into the table posts:
this is the table posts
and then print the whole table to a webpage-- action.php this is what it prints (with the error checks and all):
this is the page, I blurred out the IP
NOTE: I manually inserted the first title and content to see if the code could read from the database (which it can)
honestly, I do not know where I went wrong and I have die extensive research at this point. It's probably going to end up being a syntax error and I'm gonna be kicking myself. It could have something to do with me using a Godaddy server and the phpMyAdmin and database being through there. I am using mysqli instead of PDO because PLESK and Godaddy do not support PDO yet.
<input type="submit" name="submit" /> try with this
if(isset($_POST['submit'])){
$sql = "INSERT INTO `posts` (posttitle, content) VALUES ('$posttitle', '$content')";
$save = $mysqli->query($sql);
if($save)
echo 'success';
else
echo 'failure';
}
several things to get you started
1) missing quote after PASS
mysqli("DB HOST IP", "USER", "PASS, "DB NAME");
2) you are not executing your INSERT query, missing $mysqli->query($sql);
if(isset($_POST['submit'])){
$sql = "INSERT INTO `posts` (posttitle, content) VALUES ('$posttitle',
'$content')";
echo 'post added to database';
}
You have to give name of the submit butto as
input type="submit" name="submit"
"INSERT INTO posts (posttitle, content) VALUES ('$posttitle', '$content')"

Insert echo into textfield using Get Method

This is a continuation from my previous question "Display ID Number in URL & fetch database results from ID Number into textfields", but dubbed as another one.
Thanks for helping me out #Robbie. If only I can upvote more :')
Now for the topic. I can't seem to get to insert the value displayed as an href link into the textfield supposedly I know I'm doing this wrong obviously since I can't get it to work I would like some further assistance.
Here are the codes used: index.html
<html>
<head>
<title>Search Engine</title>
</head>
<body>
<form method='get' action="results.php">
<label> What do you like to search for?</label>
<input type='text' name='search'>
<button type='submit'>Search</button>
</form>
</body>
</html>
And this is for the actual php process:
<?php
mysql_connect("localhost","root","") or die (mysql_error());
mysql_select_db("ntmadb") or die (mysql_error());
$var = "hello";
$clean = mysql_real_escape_string($_GET['search']);
$hello = mysql_query("SELECT * FROM members WHERE id = '$clean'") or die (mysql_error());
if(mysql_num_rows($hello) >=1) {
//getdata
while($i = mysql_fetch_array($hello)){
echo ''.$i['firstname'].'';
}
}
else{
echo "No results found, sorry:(";
}
?>
<html>
<input type='text' name="firstname" value="<?php echo $firstname;?>" ></input></br>
<input type='text' name="lastname" value="<?php echo $lastname;?>" ></input></br>
</html>
Thanks alot again
Azuren, you actually gone backwards from your first question (Display ID Number in URL & fetch database results from ID Number into textfields) as you've reverted to mysql_ functions and not mysqli_ The former (mysql_) have been removed from PHP.
I've rewritten using mysqli (roughly - you may need to debug) and answered the question at the same time.
If a tutorial includes any function that begins mysql_ then find another one!
You need to define $firstname and $lastname; I'd suggest doing so as follows:
<?php
mysql_connect("localhost","root","") or die (mysql_error());
mysql_select_db("ntmadb") or die (mysql_error());
$firstname = '';
$lastname = '';
if (isset($_GET['search'])) {
if ($stmt = $mysqli->prepare("SELECT firstname, lastname FROM members WHERE id = ?")) {
/* bind parameters for markers */
$stmt->bind_param("s", $_GET['search']);
/* bind result variables */
$stmt->bind_result($firstname, $lastname );
/* execute query */
$stmt->execute();
/* fetch values */
while ($stmt->fetch()) {
echo ''.htmlspecialchars($firstname).'';
}
}
}
}
?>

PHP PSQL Insert Error

I'm trying to create a web interface for a baseball database but when I enter information into the forms and press submit it always gets to 'an error occurred'.
Here's the webpage with the form.
<html>
<?php
$dbconn = pg_connect("dbname=mine user=mine password=mine");
if ($dbconn) {
echo "Connection established <br/>";
}
echo "Here are the current NL West Teams <br/>";
$result = pg_query($dbconn, "SELECT Name, Record FROM Teams");
if (!$result) {
echo "An error occurred.\n";
exit;
}
while ($row = pg_fetch_row($result)) {
echo "Team: $row[0] Record: $row[1]";
echo "<br />\n";
}
?>
<form action="InsertPP.php" method="post">
Name: <input type="text" name="name"><br>
Team: <input type="text" name="team"><br>
Number: <input type="text" name="number"><br>
Handed: <input type="text" name="Handed"><br>
Position: <input type="text" name="Position"><br>
<input type="submit">
</form>
</html>
And here is the Insert PHP script.
<html>
<body>
<?php
$dbconn = pg_connect("dbname=mine user=mine password=mine");
if ($dbconn) {
echo "Connection established <br/>";
}
$_first = $_POST["Handed"];
$_second = $_POST["Position"];
$_third = $_POST["name"];
$_fourth = $_POST["number"];
$_fifth = $_POST["team"];
$Query = pg_query(dbconn, "INSERT INTO PosPlayer VALUES('$_first', '$_second', '$_third', $_fourth, '$_fifth)'");
if (!$Query) {
echo "An error occurred.\n";
exit;
}
echo "Your Player has been added!";
?>
</body>
</html>
I input the same values into postgres and the forms, and the player was created directly in postgres, but some error occurred when input into the form. Any ideas?
EDIT: I fixed the missing $ in front of the dbconn. Still getting the 'An error occurred'.
Check the end of the INSERT statement. You have
'$_fifth)'"
where you should have
'$_fifth')"
i.e. the closing quote for the value should be inside the closing parenthesis, not outside it.
You really should be using a prepared statement for this instead of a dynamic query. The syntax would be something like this (using the PostgreSQL driver):
$sql = "INSERT INTO PosPlayer VALUES($1, $2, $3, $4, $5)";
$result = pg_prepare($dbconn, "", $sql);
$result = pg_execute($dbconn, "", array($_first, $_second, $_third, $_fourth, $_fifth));
This will automagically handle proper quoting, escaping and type-matching of the variables' values to prevent (among other things) possible SQL injection attacks. Note that $1, $2, &c. is the pg driver's syntax for bind variables.
Replace
$Query = pg_query(dbconn, "INSERT INTO PosPlayer VALUES('$_first', '$_second', '$_third', $_fourth, '$_fifth)'");
By
$Query = pg_query($dbconn, "INSERT INTO PosPlayer VALUES('$_first', '$_second', '$_third', $_fourth, '$_fifth)'");
$ sign was missing from dbconn. Other than that, there seems to be nothing wrong with the code.

WAMP server not allowing a php search engine?

I'm trying to create a search engine that will pull out information from a mySQL database. My code is as follows:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Search Engine Test</title>
</head>
<body>
<script language="php">
// Create a database connection
$connection = mysql_connect("localhost", "root", "", "test");
if (!connection) {
die("Please reload page. Database connection failed: " . mysql_error());
}
// Select a databse to use
$db_select = mysql_select_db("test", $connection);
if (!$db_select) {
die("Please reload page. Database selection failed: " . mysql_error());
}
// Search Engine
// Only execute when button is pressed
if (isset($_POST['keyword'])) {
// Filter
$keyword = trim($_POST['keyword']);
// Select statement
$search = "SELECT Price FROM 'table_1' WHERE * LIKE '%$keyword%'";
// Display
$result = mysql_query($search) or die('query did not work');
while ($result_arr = mysql_fetch_array($result)) {
echo $result_arr['*'];
echo " ";
echo "<br>";
echo "<br>";
}
$anymatches = mysql_num_rows($result);
if ($anymatches == 0) {
echo "Nothing was found that matched your query.<br><br>";
}
}
</script>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
<input type="text" name="keyword">
<input type="submit" name="search" value="Search">
However, when I run it, I receive a notification saying that I've been forbidden to access the server. Any help would be appreciated.
$search = "SELECT Price FROM table_1 WHERE fieldname LIKE '%$keyword%'";
You can't use single quotes around a field name, as that's how strings are defined. You can use the grave key (`) if your table name is a reserved word. You also can't do WHERE *, you need to specify a field to compare the keyword to.
I would also recommend not using the mysql commands in PHP as they are deprecated. Use the more recent mysqli commands

Using PHP/MYSQL book but get no output from PHP when trying to access the database

I'm currently working my way through "PHP and MySQL Web Development." I've successfully created databases and been able to make tables and use the database. I've also successfully completed all the chapters on PHP and have had no problems with PHP not working up to this point. The goal of this page is return search results from a database. It's a pretty simple thing to do but for some reason nothing is being output from the script to the page. I'm getting no errors or anything. It's just blank with the title at the top. Can anyone please help me out with this? Thank you.
Here is the PHP code:
<html>
<head>
<title>Book-O-Rama Search Results</title>
</head>
<body>
<h1>Book-O-Rama Search Results</h1>
<?php
// create short variable names
$searchtype=$_POST['searchtype'];
$searchterm=trim($_POST['searchterm']);
if (!$searchtype || !$searchterm) {
echo 'You have not entered search details. Please go back and try again.';
exit;
}
if (!get_magic_quotes_gpc()){
$searchtype = addslashes($searchtype);
$searchterm = addslashes($searchterm);
}
# $db = new mysqli('localhost', 'bookorama', 'bookorama123', 'books');
if (mysqli_connect_errno()) {
echo 'Error: Could not connect to database. Please try again later.';
exit;
}
$query = "select * from books where ".$searchtype." like '%".$searchterm."%'";
$result = $db->query($query);
$num_results = $result->num_rows;
echo "<p>Number of books found: ".$num_results."</p>";
for ($i=0; $i <$num_results; $i++) {
$row = $result->fetch_assoc();
echo "<p><strong>".($i+1).". Title: ";
echo htmlspecialchars(stripslashes($row['title']));
echo "</strong><br />Author: ";
echo stripslashes($row['author']);
echo "<br />ISBN: ";
echo stripslashes($row['isbn']);
echo "<br />Price: ";
echo stripslashes($row['price']);
echo "</p>";
}
$result->free();
$db->close();
?>
</body>
</html>
You're supressing the errors from the line:
# $db = new mysqli('localhost', 'bookorama', 'bookorama123', 'books');
Thats what the # sign does, remove the # sign and verify that the connection works properly, it might be that your script fails there.
You shouldn't use that, it's not considered good practice as far as I know.
It worked for me! no white page! If you work with a editor including ftp sometimes saving the file failes. than you get a blank file. in that case safe your code and reopen the file.
as for the sql injection try this:
$searchtypes = array('type1','type2');
if (!in_array($searchtype,$searchtypes) || $searchterm=='') {
echo 'You have not entered search details. Please go back and try again.';
exit;
}
You need to create another php page that sends a post request. Here is a sample one:
Take a look at the fiddle:
<html>
<head>
<title>Book-O-Rama Search </title>
</head>
<body>
<h1>Book-O-Rama Search</h1>
<form id='uploadform' method='post' enctype='multipart/form-data' action='link to your search action php page'>
<legend>Submit form</legend><br/>
<div class='form-inputs'>
SearchType <input name='searchtype' id='searchtype'/><br>
SearchTerm <input name='searchterm' id='searchterm'/><br>
<input type="submit" value= "Search" />
</div>
</form>
</body>
</html>

Categories