Form content as PostGre query parameter - php

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.

Related

How to connect an HTML interface (to submit SQL statements) to a PHP file and then connect the PHP to my database?

I'm not sure how to connect my HTML interface to a PHP file to then connect to my database. I want to be able to enter SQL statements into my interface and have it retrieve and display data from my database?
Connect from client HTML to server with a PHP handler for GET or POST. In this handler method, implement your logic for database interaction for SQL statements.
MySQL is the most popular database system used with PHP.
I will try to explain this to you by storing data into the DB and getting the data from the DB to view in a table in the front end.Very often you will need to use a MySQL table to store data inside it and then output that data by using a PHP script. To display the table data it is best to use HTML, which upon filling in some data on the page invokes a PHP script which will update the MySQL table.
To populate a new database table with data you will first need an HTML page which will collect that data from the user. The following HTML code that and passes the information to a PHP script:
<form action="insert.php" method="post">
Value1: <input type="text" name = "field1" /><br/>
Value2: <input type="text" name = "field2" /><br/>
Value3: <input type="text" name = "field3" /><br/>
Value4: <input type="text" name = "field4" /><br/>
Value5: <input type="text" name = "field5" /><br/>
<input type="submit" />
</form>
The above HTML code will show the user 5 text fields, in which the user can input data and a Submit button. Upon clicking the Submit button the data submitted by the user will be passed to a script named insert.php.
That script can have a syntax similar to the following:
<?php
$username = "your_username";
$password = "your_pass";
$database = "your_db";
$mysqli = new mysqli("localhost", $username, $password, $database);
// Don't forget to properly escape your values before you send them to DB
// to prevent SQL injection attacks.
$field1 = $mysqli->real_escape_string($_POST['field1']);
$field2 = $mysqli->real_escape_string($_POST['field2']);
$field3 = $mysqli->real_escape_string($_POST['field3']);
$field4 = $mysqli->real_escape_string($_POST['field4']);
$field5 = $mysqli->real_escape_string($_POST['field5']);
$query = "INSERT INTO table_name (col1, col2, col3, col4, col5)
VALUES ('{$field1}','{$field2}','{$field3}','{$field4}','{$field5}')";
$mysqli->query($query);
$mysqli->close();
After the user submits the information, the insert.php script will save it in the database table. Then you may want to output that information, so that the user can see it on the page. The first command you will need to use is the SELECT FROM MySQL statement that has the following syntax:
SELECT * FROM table_name;
This is a basic MySQL query which will tell the script to select all the records from the table_name table. After the query is executed, usually you would want the result from it stored inside a variable. This can be done with the following PHP code:
<?php
$query = $mysqli->query("SELECT * FROM table_name");
The whole content of the table is now included in a PHP array with the name $result. Before you can output this data you should change each piece into a separate variable. There are two stages.
Now, we have to set up the loop. It will take each row of the result and print the data stored there. This way we will display all the records in the table:
$query = "SELECT * FROM table_name";
if ($result = $mysqli->query($query)) {
/* fetch associative array */
while ($row = $result->fetch_assoc()) {
$field1name = $row["col1"];
$field2name = $row["col2"];
$field3name = $row["col3"];
$field4name = $row["col4"];
$field5name = $row["col5"];
}
/* free result set */
$result->free();
}
You can now write a full script to output the data. In this script the data is not formatted when it is printed:
<?php
$username = "username";
$password = "password";
$database = "your_database";
$mysqli = new mysqli("localhost", $username, $password, $database);
$query = "SELECT * FROM table_name";
echo "<b> <center>Database Output</center> </b> <br> <br>";
if ($result = $mysqli->query($query)) {
while ($row = $result->fetch_assoc()) {
$field1name = $row["col1"];
$field2name = $row["col2"];
$field3name = $row["col3"];
$field4name = $row["col4"];
$field5name = $row["col5"];
echo '<b>'.$field1name.$field2name.'</b><br />';
echo $field5name.'<br />';
echo $field5name.'<br />';
echo $field5name;
}
/*freeresultset*/
$result->free();
}
This outputs a list of all the values stored in the database. This will give you a very basic output which is not useful for a live website. Instead, it would be better if you could format it into a table and display the information in it. To apply formatting you need to use HTML to print the result by including the variables in the correct spaces. The easiest way to do this is by closing the PHP tag and entering HTML normally. When you reach a variable position, include it as follows:
<?php echo $variablename; ?>
in the correct position in your code.
You can also use the PHP loop to repeat the appropriate code and include it as part of a larger table.
The final output will be:
<html>
<body>
<?php
$username = "username";
$password = "password";
$database = "your_database";
$mysqli = new mysqli("localhost", $username, $password, $database);
$query = "SELECT * FROM table_name";
echo '<table border="0" cellspacing="2" cellpadding="2">
<tr>
<td> <font face="Arial">Value1</font> </td>
<td> <font face="Arial">Value2</font> </td>
<td> <font face="Arial">Value3</font> </td>
<td> <font face="Arial">Value4</font> </td>
<td> <font face="Arial">Value5</font> </td>
</tr>';
if ($result = $mysqli->query($query)) {
while ($row = $result->fetch_assoc()) {
$field1name = $row["col1"];
$field2name = $row["col2"];
$field3name = $row["col3"];
$field4name = $row["col4"];
$field5name = $row["col5"];
echo '<tr>
<td>'.$field1name.'</td>
<td>'.$field2name.'</td>
<td>'.$field3name.'</td>
<td>'.$field4name.'</td>
<td>'.$field5name.'</td>
</tr>';
}
$result->free();
}
?>
</body>
</html>
This code will print out table content and add an extra row for each record in the database, formatting the data as it is printed.
I hope this will help you to solve your issue.

HTML form not populating MySQL DB as expected

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'].'")";
?>

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.

PHP Gallery CMS - Cannot Update Row in PHPMyadmin (LONG)

Project: Create a simple CMS for a photography website. My first project in php. :)
Problem: I am 90% finished with the CMS, but have ran into an issue of not being able to UPDATE row data after being READ from database.
The Goal: What I am trying to achieve seems simple. I have an admin page that reads image data from a database (id, image) and I am using a while loop to display this. It works great, and so does the delete button.
<?php
$query = "SELECT * FROM photos";
$select_all_photos_query = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc($select_all_photos_query)) {
$photos_id = $row['photos_id'];
$photos_image = $row['photos_image'];
$photos_title = $row['photos_title'];
$photos_alt = $row['photos_alt'];
echo "<tr>
<td><input type='checkbox' name='photo' value='photo'></td>
<td><img src='../images/$photos_image' width='70'></td>
<td><a class='edit' href='edit_photo.php?&p_id={$photos_id}'>Edit</a></td>
<td><a onClick=\"javascript: return confirm('Are you sure?') \"class='delete' href='admin.php?delete={$photos_id}'>Delete</a></td>
</tr>";
}
?>
The problem I am having is the Edit Button in my while loop. I am using a get method in my href to get the edit_photo.php page with a parameter named "p_id" that is = to $photos_id.
Once I click the Edit button it sends me to the edit_photo.php page and I see all of the CORRECT information which tells me it is reading it correctly. I do get a error at the bottom ( Notice: Undefined variable: photos_file) See code below.
<?php
if (isset($_GET['p_id'])) {
$photo_id = $_GET['p_id'];
// Send query to photos table in database. //
$query = "SELECT * FROM photos WHERE photos_id = $photo_id";
$result = mysqli_query($connection, $query);
// Grab unique row from photos table in database. //
while($row = mysqli_fetch_assoc($result)) {
$photo_file = $row['photos_image'];
$photos_title = $row['photos_title'];
$photos_desc = $row['photos_alt'];
}
}
?>
Now. Here comes the big problem. When I try to update this information, the program busts. I even checked to see if my sql is correct, and if the queries are connecting to database. See code below.
<?php
if (isset($_POST['image'])) {
// After "Save" is pressed, the values white space is trimmed and assigned to a variable. //
$photos_title = trim($_POST['photos-title']);
$photos_desc = trim($_POST['photos-description']);
$photos_file = $_FILES['image']['name'];
$photos_file_temp = $_FILES['image']['name_tmp'];
// The new variables are sanitized. //
$photos_title = mysqli_real_escape_string($connection, $photos_title);
$photos_desc = mysqli_real_escape_string($connection, $photos_desc);
}
// Send the Update query to the database. //
$update_query = " UPDATE photos SET
photos_image = '$photos_file', photos_title = '$photos_title', photos_alt = '$photos_desc'
WHERE photos_id = '$photo_id' ";
// Test the SQL syntax. //
if(!$update_query) {
echo "Wrong." . " " . mysqli_error($connection);
}
else { echo "The SQL appears right..." . "<br>";
}
// Test the Update query. //
$update_result = mysqli_query($connection, $update_query);
if(!$update_result) {
echo "Didnt Connect." . " " . mysqli_error($connection);
} else {
echo "Sent query to to database.";
}
?>
<form action="edit_photo.php" class="settings-form" method="post" enctype="multipart/form-data">
<div class="form-group edit-preview">
<label for="image">Photo</label>
<img src= <?php echo "../images/$photo_file"?> >
<input type="file" name="file_upload">
</div>
<div class="form-group">
<label for="photos-title">Title</label>
<input type="text" name="photos-title" value= <?php echo "$photos_title" ?> class="form-control">
</div>
<div class="form-group">
<label for="photos-description">Description</label>
<textarea type="text" rows="4" name="photos-description" class="form-control" ><?php echo "$photos_desc" ?> </textarea>
</div>
<div class="form-group">
<input type="submit" name="image" class="btn btn-primary" value="Save Photo">
</div>
</form>
I have spent four days trying to figure this out with no luck.
For one thing, it's failing because of this ['name_tmp'].
The syntax is ['tmp_name'] - you had those inversed
Ref: http://php.net/manual/en/features.file-upload.php so your temp file never gets processed.
Then as per your edit and seeing your HTML form:
You're using name="file_upload" and then using the $_FILES['image'] array; those names need to match.
Error reporting would have helped you here.
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Displaying errors should only be done in staging, and never production.
Additional note.
If you are attempting to set the given (file) column as binary data instead of the path to the given file(s) as text, then you MUST escape it.
Otherwise, MySQL will throw you an error.
If that is the case, you will need to do the same as the others:
$photos_file = $_FILES['file_upload']['name']; // notice I changed it to what it should be
$photos_file = mysqli_real_escape_string($connection, $photos_file);
as per <input type="file" name="file_upload">
Check for errors against all your queries; you're not doing that in your $query = "SELECT * FROM photos WHERE photos_id = $photo_id"; query.
Add or die(mysqli_error($connection)) to all mysqli_query() should there be an error somewhere.
HTML stickler.
<textarea type="text" - <textarea> does not have a "text" type; remove it.
Footnotes.
If you want to check if your UPDATE truly was successful, use mysqli_affected_rows().
http://php.net/manual/en/mysqli.affected-rows.php
Instead of else { echo "The SQL appears right..." . "<br>"; }
As outlined in comments, your code is open an SQL injection.
If $photo_id is an integer, change
$photo_id = $_GET['p_id'];
to
$photo_id = (int)$_GET['p_id'];
However, if that is a string, then you will need to quote it and escape it in your query.

sql php results and search

I have a problem, small to others, but huge to me. I have been working on a project since March 15 of this year. I am not a web designer but this is just a hobby of mine.
My problems are:
When I call this program for data, I receive records but it only works if I search for the full postcode
(EX 1: n = no results EX 2: nn12ab = 5 results displayed )
I have to arrange the results in some order
(my results = abcdabcdabcdabcdnn12ababcdabcdabcdabcdnn12ababcdabcdabcdabcdnn12ab,
the way I am trying to get them its
first name / last name / email / postcode.
I had checked in w3schools and all other mode but still I am asking this. :(
I am fully aware its no hack protected , I just want to make it work.
any idea where I need to place whatever works ?
TXT IN ADVANCE!
HTML search
<form method="post" action="search.php">
<center>
<h1>My Search Engine</h1>
<input type="text" value="Search..." name="query" />
<input type="submit" value="Find" name="list" />
</center>
</form>
PHP SEARCH and display CODE
<?php
$servername = "localhost";
$username = "abcd";
$password = "******";
$dbname = "abcd";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM wfuk";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<table><td><tr><th>ID</th></td></tr>
<th>Name</th></td></tr>
<th>postcode</th</td>></tr>
<th>trade</th></td></tr>
<th>telephone</th></td></tr>
<th>comments</th></td></tr></table>
";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<table><tr><td>"
.$row["id"].
"</td><td>"
.$row["first_name"]
.$row["last_name"].
"</td></tr>".
"<tr><td>"
.$row["post_code"].
"</td></tr>".
"<tr><td>"
.$row["trade"].
"</td></tr>".
"<tr><td>"
.$row["telephone"].
"</td></tr>".
"<tr><td>"
.$row["comments"].
"</td></tr></table>"
;
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
?>
Substitute this line:
$sql = "SELECT * FROM wfuk";
by
$sql = "SELECT * FROM wfuk where name like " . $_POST["query"] . " order by first_name, last_name, email, postcode";
I'm assuming that the columns in table wfuk have the names you said. If not, change them by the column names.
This is not the best way to do a search, because it open the possibility for SQL-injection attacks. But at your current level of knowledge you probably aren't ready for other solution.
Later please educate yourself on better prattices on this kind of operation.
Nothing to worry about, just basic confusions .
Answer of first question:
Dont use = sign in query like this :
Select * from table where postcode='.$variable.'
Use like clause this :
Select * from table where postcode like '%.$variable.%'
Answer for Second question:
Place border for your table :
<table border="1">
a few things here
Use some good tutorials, don't trust on w3school (some people call
it w3fool)
Never User Select * from table, rather specify column names
something like Select firstname, lastname from table
if you want search based on integer, user = sign e.g where rollunme=134
if you want to search some text/ character field , use LIKE operator
eg firstname LIKE %zaffar%
these are basic tips which should help you...
PS
question edited, but these tips should still apply as they are very generic in nature and should help you
yes it work unfortunately not whit this code, but from hear i lear the pice that i was missing THX ALL .
CODE I HAVE USE
<?php
//load database connection
$host = "localhost";
$user = "change my";
$password = "change my";
$database_name = "chage my database name";
$pdo = new PDO("mysql:host=$host;dbname=$database_name", $user, $password, array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
));
// Search from MySQL database table
$search=$_POST['search'];
$query = $pdo->prepare("select * from change_table_name where change_title LIKE '%$search%' OR change_author LIKE '%$search%' LIMIT 0 , 10");
$query->bindValue(1, "%$search%", PDO::PARAM_STR);
$query->execute();
// Display search result
if (!$query->rowCount() == 0) {
echo "Search found :<br/>";
echo "<table style=\"font-family:arial;color:#333333;\">";
// if need to multiply check clousley <tr> and </td> make shure they are on the right order
echo "<tr>
<td style=\"border-style:solid;border-width:1px;border-color:#98bf21;background:#98bf21;\">Change_Title_Books</td>
<td style=\"border-style:solid;border-width:1px;border-color:#98bf21;background:#98bf21;\">Change_Author</td>
<td style=\"border-style:solid;border-width:1px;border-color:#98bf21;background:#98bf21;\">change_Price</td></tr>";
while ($results = $query->fetch()) {
// if need to multiply check clousley <tr> and </td> make shure they are on the right order
echo "<tr><td style=\"border-style:solid;border-width:1px;border-color:#98bf21;\">";
echo $results['Chage_title'];
echo "</td><td style=\"border-style:solid;border-width:1px;border-color:#98bf21;\">";
echo $results['Change_author'];
echo "</td><td style=\"border-style:solid;border-width:1px;border-color:#98bf21;\">";
// if not needit delete "$". from bellow
echo "$".$results['change_price'];
echo "</td></tr>";
}
echo "</table>";
} else {
echo 'Nothing found';
}
?>
<html>
<head>
<title> How To Create A Database Search With MySQL & PHP Script | Tutorial.World.Edu </title>
</head>
<body>
<form action="search-database.php" method="post">
Search: <input type="text" name="search" placeholder=" Search here ... "/>
<input type="submit" value="Submit" />
</form>
<p>PHP MySQL Database Search by Tutorial.World.Edu</p>
</body>
</html>
i found a different code i will post it for future references but you guys let me understand the thinks i could not understand

Categories