dynamic drop down with php from postgresql database - php

EDIT: CODE CHANGED AND QUESTION UPDATED FOR LATEST ERROR.
I need to populate a dropdown list of book titles from my postgreSQL database using a query such as SELECT title FROM books WHERE ownedBy = [users facebook ID] and then use the selection by the user to display the rest of the information on that book. The page is a facebook app, which is how I'm getting the facebook ID.
This is the relavent section of code so far, mostly created from various answers to similar questions I have found.
<form action="updateform.php" method="post">
<input type="hidden" name="userid" id="userid" value="<?php echo htmlspecialchars($user_id); ?>"
<select name="booktitle" id="booktitle">
<option>Select book</option>
<?php
$db = pg_connect("host=ec2-54-243-190-226.compute-1.amazonaws.com port=5432 dbname=d6fh4g6l0l6gvb user=zmqygfamcyvhsb password=1Apld4ivMXSK8JZ_8yL7FwIuuz sslmode=require options='--client_encoding=UTF8'") or die('Could not connect: ' . pg_last_error());
$sql = pg_query("SELECT title FROM books WHERE ownedby='$user_id'";
while ($row = pg_fetch_assoc($sql)) {
echo '<option value="'.htmlspecialchars($row['title']).'"></option>';}
pg_close($db);
?>
</select>
//other form elements here
</form>
Currently, no drop down box is displaying, and the server log says pg_query() expects parameter 1 to be resource, string given in /app/www/update.php on line 275 and the same error for pg_fetch_assoc
If anyone can help me get the drop down box part to work, that would be great for now, I'll work on figuring the rest out myself once this part is working.

Unescaped quotes inside quotes
This
$sql = pg_query("SELECT title FROM books WHERE ownedby=("$user_id")");
Should be
$sql = pg_query("SELECT title FROM books WHERE ownedby='$user_id'");
Or
$sql = pg_query("SELECT title FROM books WHERE ownedby=\"$user_id\"");

try this:
<form action="updateform.php" method="post">
<select name="bookTitle">
<?php
$db = pg_connect("host=ec2-54-243-190-226.compute-1.amazonaws.com port=5432 dbname=d6fh4g6l0l6gvb user=zmqygfamcyvhsb password=[removed] sslmode=require options='--client_encoding=UTF8'") or die('Could not connect: ' . pg_last_error());
$sql = pg_query(sprintf("SELECT title FROM books WHERE ownedby=%d", $user_id));
while ($row = pg_fetch_assoc($sql)) {
echo '<option value="'.htmlspecialchars($row['title']).'"></option>';
}
pg_close($db);
?>
</select>
Note the use of 'echo' instead of closing the PHP tags.
Also, you should probably use an ID, rather than a title for the option value :)
Regards,
Phil

The line
$sql = pg_query("SELECT title FROM books WHERE ownedby=("$user_id")");
contains an error because the double quotes before $user_id closes the string "SELECT ....
A quick fix is to change "$user_id" with '$user_id' and remove the braces ()
In general it is not a good practice to directly put variables in SQL queries because your code becomes vulnerable to SQL Injection. Consider using prepare, bind and execute statements.

You haven't escaped the quotes on Line 275. It should be
$sql = pg_query("SELECT title FROM books WHERE ownedby=\"$user_id\"");
or
$sql = pg_query('SELECT title FROM books WHERE ownedby="'.$user_id.'"');

Related

How to get data from a different database and save it to another database

I don't know if this problem of mine is possible. Is it? I have a library system. I add and edit new books in the Catalog Database. In other words, the Catalog Database is for adding/editing books only. I have another Database (not table) for Borrowing Books. I want to store these books, which are viewed through Catalog DB, to Borrowing DB.
I have a snippet for getting data from Catalog DB
error_reporting(0);
$con = mysql_connect("localhost","root","");
mysql_select_db("catalog", $con);
$acc_number=$_GET["acc_number"];
$query="select * from branch where acc_number = '$acc_number'";
$result=mysql_query($query);
while ($row = mysql_fetch_array($result)) {
//echo $row[1];
}
<textarea name="title" disabled><?php echo $row[1];?></textarea>
And a button for the submission (store to borrowing database). If button is clicked, it's where my problem occurs. I just got a blank page after submitting it. Here is my process.php:
$con = mysql_connect("localhost","root","");
mysql_select_db("catalog", $con);
$acc_number = $_POST['acc_number'];
$title = $_POST['title'];
$sql = mysql_query("select * from books where acc_number='$acc_number'");
while($row=mysql_fetch_array($sql)){
$con = mysql_connect("localhost","root","");
mysql_select_db("borrowing", $con);
$query="INSERT INTO borrowers (title) VALUES ('$title')";
mysql_query($query);
if($query){
header("Location:../librarysystem/books.php");
}
}
You need to create two sql connections, one for each DB. Then simply get the data from one DB (perform operations, if required) and write to the second DB.
First, I suggest that you use MYSQLI or DO since MYSQL is deprecated.
These are suggestions not a fix.
Use only one connect function, you don't need two of them just use the same variable $con.
Add some error checks in there to make sure you are connecting properly
$sql = mysql_query("select * from books where acc_number='$acc_number'") or die ("error message here");
For this
$query="INSERT INTO borrowers (title) VALUES ('$title')";
mysql_query($query);
if($query){
header("Location:../librarysystem/books.php");
}
Try
$query=mysql_query("INSERT INTO borrowers (title) VALUES ('$title')") or die("Could not insert...");
if($query){
header("Location:../librarysystem/books.php");
}
You have two approaches for this:
Create two separate DB connections and manipulate data there. Passing $conn as connection to MySQL queries will work.
Use the same database using different DB prefixes. Say for example, for first DB it should be
mb_ (Manage Books)
and
bb_ (Borrow Books)
If I were at your place, I would have preferred second approach.

Display row in mysql table when a user enter id

I want to display a row when a user enter his id and after submit.
My code is not working correctly. Please rectify this.
search-form.php is looking like this.
</html><body>
<form method="GET" action="search.php">
Keyfield <input type="text" name="search"> <br><br>
<input type="submit" value="submit">
</form></body>
</html>
and
search.php looking like this.
<?php
$connection = mysql_connect('localhost','user','pass') or die ("Couldn't connect to server.");
$db = mysql_select_db('db', $connection) or die ("Couldn't select database.");
$search=$_GET['search'];
$fetch = 'SELECT * FROM `table` WHERE `ID` = "'.$search.'"';
echo "<table margin=auto width=999px border=1>";
echo "<tr><td><b>ID</b></td><td><b>Name</b></td><td><b>Telephone</b></td><td> <b>E-mail</b></td><td><b>Couttry Applying for</b></td><td><b>Visa-Category</b> </td><td><b>Other Category</b></td><td><b>Passport No</b></td><td> <b>Remarks</b></td></tr>";
for($i=0;$i<$num;$i++)
{
$row=mysql_fetch_row($fetch);
echo "<tr>";
echo"<td>$row[0]</td>";
echo"<td>$row[1]</td>";
echo"<td>$row[2]</td>";
echo"<td>$row[3]</td>";
echo"<td>$row[4]</td>";
echo"<td>$row[5]</td>";
echo"<td>$row[6]</td>";
echo"<td>$row[7]</td>";
echo"<td>$row[8]</td>";
echo"</tr>";
}//for
echo"</table>";
?>
Display when a user enter his id and submit. But this code doesn't display row with id.
Rectify this.
Thanks.
you are missing mysql_query statement.You should execute the query before fetching the result
modify like
$sql= 'SELECT * FROM table WHERE ID = "'.$search.'"';
$fetch = mysql_query($sql);
A few points:
mysql_connect is obsolete, do not use it. Use PDO instead for example.
$fetch = 'SELECT * FROMtableWHEREID= "'.$search.'"' leads to the most common and severe security flaw : SQL injection. Please read about this (google)
Where do you "fetch" the result of your query ?
About point 3, assuming the fact that you will use PDO, please read http://www.phpro.org/tutorials/Introduction-to-PHP-PDO.html

Connecting html form to php page according to primary key

Ok so essentially what I'm trying to do is add a q&a component to my website (first website, so my current php knowledge is minimal). I have the html page where the user's input is recorded, and added to the database, but then I'm having trouble pulling that specific info from the database.
My current php page is pulling info where the questiondetail = the question detail (detail='$detail') in the database, but that could potentially present a problem if two users enter the same information as their question details (unlikely, but still possible, especially if the same person accidentally submits the question twice). What I want to do is have the page load according to the database's question_id (primary key) which is the only thing that will always be unique.
HTML CODE:
<form id="question_outline" action="process.php" method="get">
<p><textarea name="title" id="title_layout" type="text" placeholder="Question Title" ></textarea> </p>
<textarea name="detail" id= "detail_layout" type="text" placeholder="Question Details" ></textarea>
<div id="break"> </div>
<input id="submit_form" name="submit_question" value="Submit Question" type="submit" />
</form>
PROCESS.PHP CODE:
$name2 = $_GET['name2'];
$title = $_GET['title'];
$detail = $_GET['detail'];
$query= "INSERT INTO questions (title, detail) VALUES ('$title', '$detail')";
$result = mysql_query("SELECT * FROM questions where detail='$detail' ")
or die(mysql_error());
The info is being stored correctly in the database, and is being pulled out successfully when detail=$detail, but what I'm looking to do is have it pulled out according to the question_id because that is the only value that will always be unique. Any response will be greatly appreciated!
Updated Version
QUESTION_EXAMPLE.PHP CODE
<?php
$server_name = "my_servername";
$db_user_name ="my_username";
$db_password = "my_password";
$database = "my_database";
$submit = $_GET['submit'];
$title = $_GET['title'];
$detail = $_GET['detail'];
$conn = mysql_connect($server_name, $db_user_name, $db_password);
mysql_select_db($database) or die( "Unable to select database");
$result = mysql_query("SELECT title, detail FROM questions WHERE id =" .
mysql_real_escape_string($_GET["id"]), $conn);
$row = mysql_fetch_assoc($result);
mysql_close($conn);
?>
<h1><?php echo htmlspecialchars($row["title"]);?></h1>
<p><?php echo htmlspecialchars($row["detail"]);?></p>
Firstly, if that is code to be used in production, please make sure you are escaping your SQL parameters before plugging them in to your statement. Nobody enjoys a SQL injection attack. I would recommend using PDO instead as it supports prepared statements and parameter binding which is much much safer.
How can I prevent SQL injection in PHP?
So you have a form...
[title]
[details]
[submit]
And that gets inserted into your database...
INSERT INTO questions (title, details) VALUES (?, ?)
You can get the last insert id using mysql_insert_id, http://php.net/manual/en/function.mysql-insert-id.php.
$id = mysql_insert_id();
Then you can get the record...
SELECT title, details FROM questions WHERE id = ?
And output it in a preview page.
I have written an example using PDO instead of the basic mysql functions.
form.php:
<form action="process.php" method="post">
<label for="question_title">Title</label>
<input id="question_title" name="title"/>
<label for="question_detail">Detail</label>
<input id="question_detail" name="detail"/>
<button type="submit">Submit</button>
</form>
process.php:
<?php
// Create a database connection
$pdo = new PDO("mysql:dbname=test");
// Prepare the insert statement and bind parameters
$stmt = $pdo->prepare("INSERT INTO questions (title, detail) VALUES (?, ?)");
$stmt->bindValue(1, $_POST["title"], PDO::PARAM_STR);
$stmt->bindValue(2, $_POST["detail"], PDO::PARAM_STR);
// Execute the insert statement
$stmt->execute();
// Retrieve the id
$id = $stmt->lastInsertId();
// Prepare a select statement and bind the id parameter
$stmt = $pdo->prepare("SELECT title, detail FROM questions WHERE id = ?");
$stmt->bindValue(1, $id, PDO::PARAM_INT);
// Execute the select statement
$stmt->execute();
// Retrieve the record as an associative array
$row = $stmt->fetch(PDO::FETCH_ASSOC);
?>
<h1><?php echo htmlspecialchars($row["title"]);?></h1>
<p><?php echo htmlspecialchars($row["detail"]);?></p>
Without PDO...
form.php:
<form action="process.php" method="post">
<label for="question_title">Title</label>
<input id="question_title" name="title"/>
<label for="question_detail">Detail</label>
<input id="question_detail" name="detail"/>
<button type="submit">Submit</button>
</form>
process.php:
<?php
// Create a database connection
$conn = mysql_connect();
// Execute the insert statement safely
mysql_query("INSERT INTO questions (title, detail) VALUES ('" .
mysql_real_escape_string($_POST["title"]) . "','" .
mysql_real_escape_string($_POST["detail"]) . "')", $conn);
// Retrieve the id
$id = mysql_insert_id($conn);
// Close the connection
mysql_close($conn);
header("Location: question_preview.php?id=$id");
question_preview.php:
<?php
// Create a database connection
$conn = mysql_connect();
// Execute a select statement safely
$result = mysql_query("SELECT title, detail FROM questions WHERE id = " .
mysql_real_escape_string($_GET["id"]), $conn);
// Retrieve the record as an associative array
$row = mysql_fetch_assoc($result);
// Close the connection
mysql_close($conn);
?>
<h1><?php echo htmlspecialchars($row["title"]);?></h1>
<p><?php echo htmlspecialchars($row["detail"]);?></p>
I assume you want to sort the questions according to the question_id. You could try using the ORDER BY command
example -
$result = mysql_query("SELECT * FROM questions where detail='$detail' ORDER BY question_id")
For these type of examples, you need to run Transaction within database
below are the
http://dev.mysql.com/doc/refman/5.0/en/commit.html
Or else
Create an random variable stored in session and also insert into database and you call it from database and you can preview it easily.
id | question_code | q_title
question_code is the random value generated before insertion into database,
and save the question_code in a session and again call it for preview.

PHP update table by form

I'm trying to update a table from a form.
I have 3 pages. The first one queries all of the rows from my table with an "edit" link.
When edit is clicked (page 2) the code pulls the $id and puts it in the url. The $id is pulled from the url and is used in a query to fill a form.
My problem is passing the updated form info to my table. Basically the update isn't happening.
Second page
<?php
include '../db/config.php';
include '../db/opendb.php';
$id = $_GET["id"];
$order = "SELECT * FROM tableName where id='$id'";
$result = mysql_query($order);
$row = mysql_fetch_array($result);
?>
<form method="post" action="edit_data.php">
<input type="hidden" name="id" value="<?php echo "$row[id]"?>">
<tr>
<td>Title</td>
<td>
<input type="text" name="title" size="20" value="<?php echo"$row[title]"?>">
</td>
</tr>
<tr>
<td>Post</td>
<td>
<input type="text" name="post" size="40" value="<?php echo
"$row[post]"?>">
</td></tr>
<tr>
<td align="right">
<input type="submit" name="submit value" value="Edit">
</td>
</tr>
</form>
third page
include '../db/config.php';
include '../db/opendb.php';
$query = "UPDATE tableName SET '$_POST[title]', '$post[post]' WHERE id='$id'";
mysql_query($query);
It should be
UPDATE tableName SET `title` = {$_POST['title']}, `post` = {$_POST['post']}...
Ask yourself, what are you setting?
Your SQL statement for the database update is wrong. It should include a listing of not only the new values but also the corresponding field names. This means it should look more like this:
$query = "UPDATE tableName SET `title` = {$_POST['title']}, `post` = {$_POST['post']} WHERE id = '$id'";
Notice that you also should embrace fields of $_POST inside of strings with curly brackets ({}) or put them outside of the quotes. (like " = " .$_POST['title']. ", "). This is absolutely necessary if you use the standard way to access those with he quotes (e.g. not $_POST[title] but $_POST['title'] or $_POST["title"]).
Additionally you should add the following to your code:
Some error handling, currently you don't even know if something went wrong. The simplest way is to check the return value of the mysql_query() function for null and if it is null, get the mysql error message with mysql_error().
Escaping for passed values. Currently you directly pass the posted data into a mysql query which is very insecure. (See for example SQL-Injection on wikipedia) You should use mysql_real_escape_string() on all form data before inserting them into queries. This escapes all parts that could be malicious.
if (isset($_POST[title])){
$title = mysql_real_escape_string(trim($_POST['title']));
}else{
$title = NULL;
}
if (isset($_POST[post])){
$post = mysql_real_escape_string(trim($_POST['post']));
}else{
$post = NULL;
}
$query = "UPDATE tableName SET title='$title', post='$post' WHERE id='$id'";
mysql_query($query);
I would also recommend mysqli functions instead of mysql and I probably wouldn't call a variable and table column 'post' to avoid confusion.
That is because you are not setting the values. In the statement:
$query = "UPDATE tableName SET '$_POST[title]', '$post[post]' WHERE id='$id'";
you should pass column names to be updated.
If you are not using PDO statements yet to prevent SQL injection attacks then you should use more protection then just mysql_real_escape_string(). On top of escaping the data you should be validating that the submitted data is in fact what you are expecting.
Ie. In your code here:
$id = $_GET["id"];
$order = "SELECT * FROM tableName where id='$id'";
$result = mysql_query($order);
$row = mysql_fetch_array($result);
If you added:
if(is_numeric($_GET['id'])){
$id = mysql_real_escape_string(trim($_GET["id"]));
$order = "SELECT id, title, post FROM tableName where id='$id'";
$result = mysql_query($order);
$row = mysql_fetch_array($result);
}
This would at least validate what you are executing is in fact an ID number (That is, if ID is actually a number ;) . You can apply this logic to all your inputs if you are not yet using PDO statements. If you are expecting letters then validate for letters, numbers validate for numbers, escape special characters. Again, this is bare minimum. I would really suggest reading up on the hundreds of SQL injection techniques and start reading up on PDO's.
Also, in regards to using the SELECT * statement. I would try and avoid it. It adds a layer of vulnerability to your statements, if you change the order of the fields in your table and you are using $row[0] (Numbered requests) it can muck things up and lastly if your table contains additional fields with data that is unrelated to the ones you need then you are using on this page then you are loading information you don't need to.
$order = "SELECT id, title, post FROM tableName where id='$id'";
Would solve that nicely. :) Good luck!

Invalid MySQL Query when passing in value from external select box

I have two files in use. The first is a front end select box with a list of dynamically populated char/text values that uses POST to send the selected value to a back end file. This back end file assigns this value to a variable and that variable is then used in the following query:
$query = "SELECT DoctorName, Speciality FROM hospital WHERE HospitalName =".$hosname;
However, I keep getting the Invalid Query message I have set in my or die(); and I have no idea why. The full section of php code on the backend file is as follows:
$conn = mysqli_connect("localhost", "root", "") or die ("No connection");
mysqli_select_db($conn, "hospitaldb") or die("db will not open");
$hosname=$_POST['valuelist'];
$query = "SELECT DoctorName, Speciality FROM hospital WHERE HospitalName =".$hosname;
$result = mysqli_query($conn, $query) or die("Invalid query");
echo "<table border='1'><tr><th>mDoctorName</th><th>Speciality</th></tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr><td>" . $row[0] . "</td><td>" . $row[1] . "</td></tr>";
}
echo "</table>";
mysqli_close($conn);
Note: I have checked that the value from the select box is being passed in using print and it is. Any help would be greatly appreciated.
*I am only testing this locally but thanks to all who recommended mysql_real_escape_string() to protect against injections.*
It looks like you're not wrapping the value in quotes, so the query is malformed. My PHP is rusty, excuse me if there is a syntax error in my example, below:
$query = "SELECT DoctorName, Speciality FROM hospital WHERE HospitalName ='".$hosname ."';";
However, the string concatenation leaves you open to SQL Injection (http://en.wikipedia.org/wiki/SQL_injection). Consider using prepared statements http://php.net/manual/en/pdo.prepare.php
The resulting SQL query you want would be something like;
SELECT DoctorName, Speciality FROM hospital WHERE HospitalName = 'MyHospital'
In other words, you need to add quotes to your query creation;
$query = "SELECT DoctorName, Speciality FROM hospital WHERE HospitalName = '".$hosname."'";
You should really also escape the hospital name using mysql_real_escape_string() before just inserting it into a query.
Actually, your error is you need to surround your variable in single quotes like:
$query = "SELECT DoctorName, Speciality FROM hospital WHERE HospitalName ='".$hosname."'";
I'm assuming $hosname is a string. Your query is failing because you haven't quoted it.
$query = "SELECT DoctorName, Speciality FROM hospital
WHERE HospitalName = '" . mysql_real_escape_string($hosname) . "'";
Note I added mysql_real_escape_string as well as the quotes to protect from SQL Injection attacks. You should read and learn about SQL Injection attacks because your code is vulnerable to them. Also consider using PDO which helps take care of these things for you.
Use ' (quotes) around your .$hosname variable name.

Categories