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.
Related
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')"
When I save a form from html to php and finally store it in MySQL somewhere in that line it save the var= including what comes after the =
Here is my html:
<form action="searchResultsSave.php" method="POST">
What are we looking for? <input type="text" name="searchVar" />
<input type="submit" value="Submit">
</form>
Php:
$searchVar = file_get_contents('php://input');
$sql = "INSERT INTO g_information(searchVar) VALUES ('$searchVar')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
Finally my output in mysql is: "searchVar=cars" when it should just be "cars".
Where do you think I went wrong?
$searchVar = file_get_contents('php://input');
should be
$searchVar = $_POST['searchVar'];
This way you get the value of the search term.
You should read input variable from the form
<?php
$_POST["searchVar"];
?>
Then do some validation on the input, making sure no illegal characters are entered and data is safe to store in MySQL database
<?php
$_POST['searchVar'] = filter_var($_POST['searchVar'], FILTER_SANITIZE_STRING);
$sql = "INSERT INTO g_information(searchVar) VALUES ("'.$_POST['searchVar'].'")";
?>
So, I'm pretty new to web. I'm always fiddling with HTML and SQL, but recently I started working on a project. This project is basically creating a database with all employees contact data (name, email, phone number, etc) and show it on web. Database is set, web page is connecting normally to DB (I can call PHP and send a query, results are shown perfectly). BUT I don't know how to use a <form> content (text written by user) as a Query Parameter. I want to send the parameter when Enter or the 'busca' button are pressed.
Here is the form
<form id="searchbox" >
<label for="sectname">
</label>
<input id="sectname" name="sectname" type="search" placeholder="Busca" list="setor" class="searchbox"/>
<div style="text-align:center">
<input id="submit" type="button" class="button" value="BUSCA"/>
</div>
</form>
And here is the PHP with query
$host = "host=localhost";
$port = "port=5432";
$dbname = "dbname=Cards";
$creds = "user=postgres password=12345678";
$db = pg_connect( "$host $port $dbname $creds" );
if(!$db){
echo nl2br ("Unable to open database\n");
}
$sql =<<<EOF
SELECT * from Cards where nome='Diego Teste';
EOF;
$ret = pg_query($db, $sql);
if(!$ret){
echo pg_last_error($db);
exit;
}
while($row = pg_fetch_assoc($ret)){
echo "<div>";
echo "<img src='".$row['pic']."'class='cardcontent2'/>";
echo "<div class='carddata'>";
echo nl2br ("\nNome: ".$row['nome'] . "\n");
echo nl2br ("Email: ".$row['email'] . "\n");
echo nl2br ("Ramal: ".$row['ramal'] . "\n");
echo nl2br ("NĂºmero: ".$row['numero'] . "\n");
echo nl2br ("Setor: ".$row['setor'] . "\n\n");
echo "</div>";
echo "</div>";
}
pg_close($db);
I want 'nome="Diego Teste"' to be 'nome= %var%' and the %var% value should be text written by user.
The trick is to use prepared statements: (ref)
$basequery =<<<EOF
SELECT * from Cards where nome = $1;
EOF;
pg_prepare($db, "my_query", $basequery);
$results = pg_execute($db, "my_query", array($_GET["nome"]));
...
Prepared statements take care of escaping any values you will pass to SQL, so you do not have to do it yourself. It protects you from SQL injection; some people will fill form fields with malicious content that can trip up your SQL statement if you just put the field's text in-place.
My PHP might be a bit rusty, so please forgive me if I made minor mistakes.
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']);
I'm learning PHP from reading the php manual and studying different tutorials. I hit a snag with the mysql_query. I'm trying to insert user data into a database from a form using PHP. The mysql_query should return false because the username doesn't exist in the database yet but according to the result I am getting it is returning true and nothing is being entered into the database. Am I using mysql_query wrong or is using !result incorrect?
$sql = "SELECT * FROM users WHERE username='".$_POST["name"]."'";
$result = mysql_query($sql)
if (!$result) {
$sql = "INSERT INTO USERS (username, email, password) VALUES
('".$_POST["name"]."', '".$_POST["email"]."', '".$passwords[0]."')";
$result = mysql_query($sql);
if ($result) {
echo "It's entered!";
} else {
echo "There's been a problem: " . mysql_error();
}
} else {
echo "There's already a user with that name: <br />";
$sqlAll = "SELECT * FROM users";
$resultsAll = mysql_query($sqlAll);
$row = mysql_fetch_array($resultsAll);
while ($row) {
echo $row["username"]." -- ".$row["email"]."<br />";
$row = mysql_fetch_array($result);
}
}
Jason, you're checking to see if the query has failed or not - not whether it has returned the value 'false' or 'true'. You need to call mysql_fetch_row or similar, then compare the result.
Alternatively you could use the following:
if (mysql_num_rows($result) == 0) {
/* User doesn't exist */
} else {
/* User exists */
}
This will detect if any users have been chosen by your query and - if they have - your user exists already.
Also, you should learn about input sanitisation and SQL Injection. It's a very critical security issue and your script is vulnerable to it. More info here.
A select query which has no result rows STILL returns a result handle. msyql_query() will ONLY return a 'false' value if the query fails due to a syntax error, constraint violation, etc...
Your code should be
$sql = "...";
$result = mysql_query($sql);
if ($result === false) {
die("QUery failed: " . mysql_error());
}
if (mysql_num_rows($result) == 0) {
... user does not exist ...
}
And please please please read up about SQL injection vulnerabilities. Your code has holes wide enough for a truck to drive through.
In this case, $result will be a resource. You should check the number of results with mysql_num_rows().
Never, really, NEVER, use $_POST or any direct user input in a query. Always escape the input, BEFORE using it in a query, with mysql_real_escape_string(), or you'll have opened a serious security issue with SQL Injection.
Ex:
$safe_name = mysql_real_escape_string($_POST["name"]);
$sql = "SELECT * FROM users WHERE username='$safe_name'";
It's not exact.
mysql_query() will also fail and return FALSE if the user does not
have permission to access the table(s) referenced by the query.
In your case you have the permission but the user doesn't exist. So it will return true but the result set returned is empty.
mysql_query will return an empty set if the query returns no data. The query will however not fail.
i solve my problem :
like this
<?php
$username = $_POST['username'];
include('config.php');
$result = mysqli_query($con,"SELECT * FROM persons WHERE username='$username'");
while($row = mysqli_fetch_array($result)){
echo $row['username'];
echo "</br>";
echo "</br>";
echo "<p><b>Secret Question</b></p>";
echo $row['secret'];
}
?>
</br>
</br>
<form action="forgetaction.php" method="POST">
<p><b>Answer is :</b><p>
<input type="hidden" name="username" value="<?php echo $username; ?>">
<input type="text" name="answer">
</br>
</br>
<input type="Submit" value="Submit">
</form>
and forget action.php like this :
<?php
include('config.php');
$username = $_POST['username'];
echo $username;
$result = mysqli_query($con,"SELECT * FROM persons WHERE username='$username'");
$row = mysqli_fetch_array($result);
if($row['answer'] == $_POST['answer']) {
echo $row['password'];
} else {
echo 'wrong!';
}
?>
thank you all for help .