I am new to PHP/MYSQLI and I am having trouble creating a simple search to search my database. The columns in my database are: 'ID' , 'Name' , 'Age'. The name of my database is 'users' and the table name is 'employees'.
Here is the code:
<?php require('Connections/Localhost.php'); ?>
<?php
if (isset($_POST['Search'])) {
$search = $_POST['element'];
$sql = mysqli_query("SELECT * FROM employees WHERE Name = '$search' ");
if($sql->num_rows > 0 ) {
while($rows = $sql->fetch_assoc()) {
$id = $rows['ID'];
$name = $rows['Name'];
$age = $rows['Age'];
echo "ID: $id <br> Name: $name <br> Age: $age <br>";
}
}
else {
echo "No Result Found!";
}
}
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<form method="post">
<input type="text" name="element" placeholder="Enter A Name"/>
<input type="button" name="Search" value="Search" />
</form>
</body>
</html>
It just returns a blank page and nothing else. I want the user to enter a name in the text area of the form and on clicking the Search button all the data corresponding to that name from the database should be displayed on the webpage. Please correct me where I made the mistake.
You need to change button type to submit.
Your form is not posting.
Change
<input type="button" name="Search" value="Search" />
To:
<input type="submit" name="Search" value="Search" />
Also, mysqli_query() needs database connection resource.
You have given only sql query.
$sql = mysqli_query($databaseConnection, "SELECT * FROM employees WHERE Name = '$search' ");
mixed mysqli_query ( mysqli $link , string $query [, int $resultmode =
MYSQLI_STORE_RESULT ] )
Reference
As per request of OP here I will explain the general concept of a Prepared statement in mysqli feel free to edit this if you feel I did not elaborated on a topic.
The first thing you need to do is prepare the query(preparing the
query is sending an empty query to the database). But instead of
defining the parameter you will put a question mark.
After that you need to bind the parameters to the question marks In the exact order as in the query! The first thing you'll do is defining the type of the parameter string is s integer is i and blob
is b. After that you'll need to define the variables with the data.
And the third and final thing you'll need to do is executing the query. I always use it in an if statement because it will return a
true or false and like this you can check if the query failed or not and handle the error. In this case you will not need an else because the page will die if the query returns false.
/*1.*/
$stmt = $databaseConnection->prepare("SELECT * FROM `employees` WHERE `name` = ?");
/*2.*/
$stmt->bind_param("s",$search);
/*3.*/
if(!$stmt->execute())
{
die("There went something wrong: " . $stmt->error);
}
Edit: here is the question explaining more about how to prevent SQL-injections.
Related
I'm at a complete loss here. I've written a relatively simple PHP script which updates a database record based on user input from a HTML form. The script contains an 'if' statement which executes based a hidden input. I know that the statement executes because the SQL query executes without a problem. The problem I'm having is that there there is another if statement within which should execute if the query object is set, but apparently it doesn't because the $message variable within is not assigned a value. I know that the query object is set because when I echo it it shows up as '1'. Below is the code block in question:
<?php
if(isset($_POST['submitted']) == 1) {
$name = mysqli_real_escape_string($dbc, $_POST['name']);
$q = "UPDATE ".$_POST['table']." SET name = '".$name."' WHERE id = ".$_POST['id'];
$r = mysqli_query($dbc, $q);
echo $r;
print_r($_POST);
echo mysqli_error($dbc);
if ($r) {
$message = '<p>Operation executed successfuly</p>';
} else {
$message = '<p>Operation did not execute because: '.mysqli_error($dbc);
$message .= '<p>'.$q.'</p>';
}
}
?>
The echoes and print_r() below the query are for debugging purposes. The code that should echo $message is above the aforementioned code block (in my script) and looks like this:
<?php if(isset($message)) {echo $message;} ?>
Also, I tried using isset() for the $r variable and also changed the condition to $r !== false but that did not make a difference. When I just echo out $message without the isset() i get the obvious " Undefined variable: message in C:\xampp\htdocs\IMS\modify.php on line 47" error. My apologies if I'm missing something glaringly obvious. I did search beforehand but all the answers were too different from my situation and my knowledge of PHP is too small for me to be able to connect dots that are that far away, if you know what I mean.
EDIT: alright, I might as well put in the entire script. It's a bit all over the place, my apologies. The $id and $table variables do show as undefined after the submit button is pressed, could that have something to do with it?
<?php
error_reporting(E_ALL);
include('config/setup.php');
$id = $_GET['id'];
$table = $_GET['table'];
if ($table == "users") {
header('Location: index.php');
exit;
}
?>
<html>
<head>
<title>Update</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
<div class="back">
Back
</div>
<div class="panel">
<?php
if(!isset($_POST['submitted'])) {
$q = "SELECT name FROM $table WHERE id = $id";
$r = mysqli_query($dbc, $q);
$row = mysqli_fetch_assoc($r);
if($table == "categories"){
$type = "category";
} else if ($table == "products") {
$type = "product";
}
echo "<p>You are changing the properties of this ".$type.": ".$row['name']."</p>";
}
?>
<?php if(isset($message)) {echo $message;} ?>
<form action="modify.php" method="POST">
<label for="name">New name</label>
<input type="text" class="form-control" id="name" name="name">
<button type="submit">Submit</button>
<input type="hidden" name="submitted" value="1">
<input type="hidden" name="id" value="<?php echo $id; ?>">
<input type="hidden" name="table" value="<?php echo $table; ?>">
</form>
<?php
if(isset($_POST['submitted'])) {
$name = mysqli_real_escape_string($dbc, $_POST['name']);
$q = "UPDATE ".$_POST['table']." SET name = '".$name."' WHERE id = ".$_POST['id'];
$r = mysqli_query($dbc, $q);
echo $r;
print_r($_POST);
echo mysqli_error($dbc);
if ($r !== false) {
$message = '<p>Operation executed successfuly</p>';
} else {
$message = '<p>Operation did not execute because: '.mysqli_error($dbc);
$message .= '<p>'.$q.'</p>';
}
}
?>
</div>
</body>
EDIT2: Alright, I came up with a "fix" that kind of solves the problem, namely, I moved the if condition up before the echo of $message and changed the condition to isset($_POST['submitted']. This will have to do, I suppose. I guess I should read up more about the order of operations when processing submitted data and parsing PHP files in general, because I am quite confused as to why this "fix" even works...
This (conditional) statement is a false positive:
if(isset($_POST['submitted']) == 1)
What you need to do is either break them up into two separate statements:
if(isset($_POST['submitted']) && $_POST['submitted']== 1)
or just remove the ==1.
Your code is also open to a serious SQL injection. Updating a table and setting columns from user input is not safe at all.
At best, use a prepared statement.
https://en.wikipedia.org/wiki/Prepared_statement
However, please note that you cannot bind a table and/or a column should you want to convert that to a prepared statement method.
Therefore the following will fail (when using a PDO prepared statement as an example):
$q = "UPDATE :table SET :name = :name WHERE id = :id;
or
$q = "UPDATE ? SET name = :name WHERE id = :id;
Read the following about this method, where that cannot be used:
Can I parameterize the table name in a prepared statement?
Can PHP PDO Statements accept the table or column name as parameter?
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).'';
}
}
}
}
?>
I am doing an exercise from the book PHP & MYSQL in easy steps. It involves an HTML form to update a row in a database then various PHP scripts to check the the input data for HTML code and make it into a secure format. However, the code just does not work the way the book says. I went to the publisher's website and downloaded the code example, but no joy.
Instead of a form with the name of the row below it, instead I get the form, then below that "No valid new name submitted". Then below that the current name of row in the table which I want to change. When I try to enter and submit data into the form it makes no difference. It displays exactly the same page. The code is below.
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Ensuring security
</title>
</head>
<body>
<form action="secure.php" method="POST">
<p>New Name : <input type="text" name="name">
<input type="submit"></p></form>
<?php
require('../connect_db.php');
if (!empty($POST['name']) && !is_numeric($_POST['name'])) {
$name = $POST['name'];
$name = mysqli_real_escape_string($dbc, $name);
$name = strip_tags($name);
$q = 'UPDATE towels SET name "' . $name . '" WHERE id= 1';
mysqli_query($dbc, $q);
} else {
echo 'No valid new name submitted';
}
$q = 'SELECT * FROM towels WHERE id = 1 ';
$r = mysqli_query($dbc, $q);
while ($row = mysqli_fetch_array($r, MYSQLI_NUM)) {
echo "<p>Name : $row[1] </p>";
}
mysqli_close($dbc);
I'd appreciate any ideas on this. I have spent about 3 hours and been on the publishers website, but I am still at square one.
There is no superglobal array $POST so you have to change $POST['name'] to $_POST['name'].
PHP can't see that array so it evaluates !empty($POST['name']) as false and never executes code with update query.
And, like #BartFriederichs said, buy better book. I don't think you'll learn something valuable from current one.
update: There must be a minor syntax error in some accompanying validation for $_GET variable. I rewrote everything carefully and the script now works. Thank you all!
I've spent more than 5 hours trying to find what's wrong with my code.
1st page: a db query retrieves some vimeo videos from the db and presents each one of them with an "edit" link which dynamically gets the video's id (vimeo 8-digit id). To do this, I just call the following function:
function edit_portfolio_videos() {
global $connection;
$query = "SELECT * FROM portfolio_videos ORDER BY video_id ASC";
$portfolio_videos_set = mysql_query($query, $connection);
confirm_query($portfolio_videos_set);
while ($portfolio_video = mysql_fetch_array($portfolio_videos_set)) {
echo "<iframe src=\"http://player.vimeo.com/video/";
echo $portfolio_video['video_code'];
echo "?title=0&byline=0&portrait=0&color=ffffff\" width=\"400\" height=\"230\" frameborder=\"0\" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe><br />";
echo "Edit this Video";
}
}
2nd page: This is the page where each video will be edited by the administrator. Example URL would be something like "http://www.my_website.com/edit_portfolio_video.php?videocode=34956540". On this page, I use the following function to get the array from the previous page's script:
function get_selected_video_by_id($video_code) {
global $connection;
$query = "SELECT * FROM portfolio_videos ";
$query .= "WHERE video_code = '$video_code' ";
$query .= "LIMIT 1";
$videos_set = mysql_query($query, $connection);
confirm_query($videos_set);
if ($video = mysql_fetch_array($videos_set)) {
return $video;
} else { $video = NULL; }
}
and then...
$selected_video = get_selected_video_by_id($_GET['videocode']);
in order to put every kind of data related to the selected video in the edit form:
<form action="edit_portfolio_video.php?videoid=<?php echo $selected_video['video_code']; ?>" method="post">
<input type="text" name="video_title" value="<?php echo $selected_video['video_title']; ?>" />
</p>
<p>Video Code (vimeo):<br />
<input type="text" name="video_code" value="<?php echo $selected_video['video_code']; ?>" />
</p>
<p>Video Description:<br/>
<textarea name="video_description" rows="5" cols="70"><?php echo $selected_video['video_description']; ?></textarea>
</p>
<p>
<input type="submit" name="submit" value="Save Video" />
</p>
</form>
But the form's fields don't get populated, as there seems to be a problem with the $video variable I'm trying to get (returned from get_selected_video_by_id function). The video code is stored as "INT" (length: 11) in the database and is printed as string in the 2nd page's URL. I've tried to write the function's query in many ways but I can't get it to work.
I'd appreciate some help on this, thank you all.
Note: The confirm_query function does this simple job:
function confirm_query($result_set) {
if (!$result_set) {
die("Database query failed: " . mysql_error());
}
}
I think you should try this instead for your get_selected_video_by_id SQL query.
$query = "SELECT * FROM portfolio_videos WHERE video_code = ".$video_code;
Of course watch out for SQL injection in your parameters, and also, as someone already suggested please consider using PDO or MySQLi.
Your Form seems strange:
you are using a POST mode to pass a GET value (edit_portfolio_video.php?videoid=...etc...).
But this shouldn't be the problem.
In this line:
$selected_video = get_selected_video_by_id($_GET['videocode']);
are you sure the GET parameter you are passing is videocode? Or is it videoid?
I'm trying to get a row from the DB using php, i've made an html form that's supposed to take a book title from users and gets the review from the DB about this book, and then post it in an input text, the form's action leads to the following function :
function GetReview($BookTitle)
{
require'DB.php';
if(empty($_POST['BookTitle']))
{
echo " You must enter a book name!";
return false;
}
$BookTitle = mysql_real_escape_string($BookTitle);
$q="Select Reviews from Users_Booklist where (Book_Title like '%" .$BookTitle."%');";
if(!mysql_query($q,$con))
{
die("Error".mysql_error());
}
else
{
$row = mysql_fetch_row($q);
?>
<html>
<head><title>Delete Review </title>
</head>
<body>
<br>
<form name="DeleteReview " action="DeleteReviewsFunction.php" method="post">
Review: <input type="text" name="Review" size="200" value="<?php echo $row[0]; ?>"/>
<input type="submit" value="Delete Review" />
</form>
</body>
</html>
<?php
}
}
GetReview($_POST['BookTitle'])
However, it leads me to the next form with nothing in the input text and this warning:
Warning: mysql_fetch_row(): supplied argument is not a valid MySQL result resource in C:\AppServ\www\GetReview.php on line 20
I've searched and tried different code but still same result.
Could anyone please tell me where the error is???... Thanks
$qq = mysql_query($q,$con);
if(!$qq) {
// (...)
$row = mysql_fetch_row($qq);
I'm not going to be a lot of help, but your question seems to be where the error is occuring, and I can tell you that.
It's in the $row = mysql_fetch_row($q); line.
You can tell this because the error record starts with mysql_fetch_row(), and the above line is the only mention of mysql_fetch_row() in the code.
Check the SQL query by printing the output of $q variable with:
echo $q;
Now, try to execute it from your MySQL client. Collect the results (if there are) and check for errors.
A suggestion: If you want, you can use a tool like ezSQL that can be very useful (especially for code organization)