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
Related
Attempting to insert a Score based on the User's Session ID and POST , I've set up the database to use the UserID as a foreign key constraint but dont know how to do an insert query.
enter image description here
Database Values ^^
My attempt below
<?php
include("php/functions.php");
include('connections/conn.php');
$userID = $_SESSION["userID"];
//echo "all good here";
$newsoanxscore = mysqli_real_escape_string($conn, $_POST['socanxscore']);
$insertquery = "INSERT INTO socanxscore(socialanxietyscore)" . "VALUES('$newsoanxscore')";
$result = mysqli_query($conn, $insertquery) or die(mysqli_error($conn));
mysqli_close($conn);
?>
My insert form
<form action="insertsoanxietyscore.php" method="post">
Insert your score <input type="number" name="socanxscore" /><br><br>
<input type="submit" />
</form>
There are a few things here that may be helpful.
Firstly, you are not passing the user ID into your insert query. which can be written in this case as.
$insertquery = "INSERT INTO socanxscore(socialanxietyscore, UserId) VALUES('$newsoanxscore', '$userID')";
Secondly, please take the time to explore prepared queries to prevent SQL injection when passing end-user input to a database table. You may find the following resource useful.
http://php.net/manual/en/mysqli.prepare.php
go for this:
<?php
session_start();
include("php/functions.php");
include('connections/conn.php');
$userID = $_SESSION["userID"];
if(isset($_POST["socanxscore"]))
{
$query=INSERT INTO socanxscore(socialanxietyscore) VALUES('$newsoanxscore') WHERE userID=$userID";
$result = mysqli_query($conn, $insertquery) or die(mysqli_error($conn));
}
else
{
ehco "error";
}
mysqli_close($conn);
?>
This question already has answers here:
mysqli_real_escape_string not working properly
(2 answers)
Closed 5 years ago.
Good Day
I am new to html, php I am trying to set up a page to run a sql query to move data from one table into another one. The trouble I am having is that I require a user to input a date that needs to pass to the query.
I have checked on the net and viewed the question that this is marked as a duplicate of. And am still unable to get this working.
My Html is as follows for the submit part.
<div class = "boxed">
<p> First Date to be used for comparasion</p>
<form method="post">
Date1: <input type="text" name="date1"/>
<input type="Submit" value="submit"/>
</form>
</div>
My Php is
<?php
session_start();
include_once 'include/dbconf.php';
if(isset($_POST['date1']))
$d1 = mysqli_real_escape_string($_POST['date1']);
$sql1 = "insert ignore into compare2 SELECT * FROM Compare where Date =
'$d1'";
$sqldata = mysqli_query($sql1,$conn) or die ('error updaing Table');
echo "Table updated";
mysql_close($con)
?>
My include/dbconfig.php works as I use it on another page and connect succesfully to the DB.
It looks like my query doesn't get the user defined input passed to it.
I don't get any errors either in the httpd error.log.
You advise and help would be most appreciated.
Updated PHP
<?php
session_start();
include_once 'include/dbconf.php';
if(isset($_POST['date1']))
{
$d1 = mysqli_real_escape_string($conn, $_POST['date1']);
$sql1 = "insert ignore into compare2 SELECT * FROM Compare where Date =
'$d1'";
$sqldata = mysqli_query($conn, $sql1) or die ('error updaing Table');
echo "Table updated";
}
mysqli_close($conn)
?>
Still not running the sql to update the table.
Change your code to:
session_start();
include_once 'include/dbconf.php';
if(isset($_POST['date1'])) {
$d1 = mysqli_real_escape_string($conn, $_POST['date1']);
$sql1 = "insert ignore into compare2 SELECT * FROM Compare where Date = '$d1'";
$sqldata = mysqli_query($conn, $sql1) or die ('error updaing Table');
echo "Table updated";
}
mysql_close($con);
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.'"');
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.
Trying to follow a tutorial, but i get a database error on line six of the executable php file (second code below)
<?php
mysql_connect("localhost","root","") or die("Error: ".mysql_error()); //add your DB username and password
mysql_select_db("beyondmotors");//add your dbname
$sql = "select * from `TestTable` where ID = 1";
$query = mysql_query($sql);
while ($row = mysql_fetch_array($query)){
$id = $row['ID'];
$fname = $row['FName'];
$lname = $row['LName'];
$phone = $row['PHON'];
//we will echo these into the proper fields
}
mysql_free_result($query);
?>
<html>
<head>
<title>Edit User Info</title>
</head>
<body>
<form action="updateinfo.php" method="post">
userid:<br/>
<input type="text" value="<?php echo $id;?>" name="id" disabled/>
<br/>
Last Name:<br/>
<input type="text" value="<?php echo $fname;?>" name="fname"/>
<br/>
Last Name:<br/>
<input type="text" value="<?php echo $lname;?>" name="lname"/>
<br/>
Phone Number:<br/>
<input type="text" value="<?php echo $phone;?>" name="phon"/>
</br>
<input type="submit" value="submit changes"/>
</form>
</body>
</html>
and here is the executable
<?php
mysql_connect("localhost","root","") or die("Error: ".mysql_error()); //add your DB username and password
mysql_se lect_db("beyondmotors");//add your dbname
//get the variables we transmitted from the form
$id = $_POST[''];
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$phon = $_POST['phon'];
//replace TestTable with the name of your table
$sql = "UPDATE `TestTable` SET `FName` = '$fname',`LName` = '$lname',
`PHON` = '$phon' WHERE `TestTable`.`ID` = '$id' LIMIT 1";
mysql_query($sql) or die ("Error: ".mysql_error());
echo "Database updated. <a href='editinfo.php'>Return to edit info</a>";
?>
everything is good until i hit submit changes; than i get error on line 6. I'm new to database so please be specific if possible. Thank you! also if anyone could point me to a similar, "working" tutorial that would help ALOT!
trying to follow this tutorial: http://teamtutorials.com/web-development-tutorials/editing-mysql-data-using-php
i'm using wamp server, so the database log in is correct. I mean it displays the data, just doesn't edit it..
The error i'm getting is :
Notice: Undefined index: ID in C:\wamp\www\test\updateinfo.php on line 6
i get that even if i change post to $id = $_POST['ID'];
Ok I changed the $_POST['']; to $_POST['id']; , still had the same error.
Than I read online to add a # to the front so now it looks like this: #$_POST['id'];
That too off all the errors. but not my data base is not been updated. Everything goes through with no errors but no data is been changed??
Also when i tried to remove backticks I get this error:
Parse error: syntax error, unexpected T_STRING in C:\wamp\www\test\updateinfo.php on line 12
So i left them the way they were...
Could it be because i'm using a local server? This should be all simple not sure what i'm doing wrong here.. I mean i literary copied everything over from the tutorial.
First and foremost, you should be warned that your code is completely vulnerable against sql injections. Escaping your POST data before inserting it into the database is a good start in protecting your database.
Also, learning the mysql extension is useless for new systems because it is deprecated. You might think about looking into the PDO interface or the mysqli extension. There are many beginner tutorials for both and you will gain much more.
Now, as for your error
Make sure you are defining which ID you want to update in your database. In your second block of code you have:
//get the variables we transmitted from the form
$id = $_POST[''];
needs to change to:
$id = $_POST['id'];
You said you get the error even if you change post to $id = $_POST['ID'], but if you look at your form, the id input has name = 'id' and PHP is case sensitive.
Now, in your sql query, all of those back ticks are unnecessary. Also, there is no point in specifying which table ID because this is all being done in ONE table, TestTable.
//replace TestTable with the name of your table
$sql = "UPDATE TestTable SET FName = '$fname',LName = '$lname',
PHON = '$phon' WHERE ID = '$id' LIMIT 1";
EDIT:
Although the query above is syntactically correct, you should consider using mysqli or PDO due to reasons mentioned above. Below are examples using mysqli and PDO.
Mysqli
mysqli Manual
/* connect to the database */
$mysqli = new mysqli("localhost", "user", "password", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
/* build prepared statement */
$stmt = $mysqli->prepare("UPDATE TestTable SET FName=?, LName=?, PHON=? WHERE ID=?)");
/* bind your parameters */
$stmt->bind_param('sssi', $fname, $lname, $phon, $id);
/* execute prepared statement */
$stmt->execute();
/* close connection */
$stmt->close();
PDO
PDO Manual
/* connect to the database */
$dbh = new PDO('mysql:host=localhost;dbname=database', $user, $pass);
/* build prepared statement */
$stmt = $dbh->prepare("UPDATE TestTable SET FName = :fname, LName = :lname, PHON = :phon WHERE ID = :id");
/* bind your parameters */
$stmt->bindParam(':fname', $fname);
$stmt->bindParam(':lname', $lname);
$stmt->bindParam(':phon', $phon);
$stmt->bindParam(':id', $id);
/* update one row */
$fname = 'John'; # or use your $_POST data
$lname = 'Doe';
$phon = '123-456-7890';
$id = 1;
/* execute prepared statement */
$stmt->execute();
/* use it again!1! */
$fname = 'Jane';
$lname = 'Doe';
$phon = '123-456-7890';
$id = 2;
/* execute prepared statement */
$stmt->execute();
/* close connection */
$dbh = null;
Remove backticks:
UPDATE TestTable SET FName = '$fname',LName = '$lname',PHON ='$phon'
WHERE TestTable.ID = '$id' LIMIT 1";