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
Related
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.
I want to get some variables from a form and i will use those variables to make a search bar for example:
$var=$_POST['var']
I want to put this variable in a request like this:
$SQL = 'SELECT * FROM Table ORDER By $var'
Any suggestions please? How can I transform this request to a dynamic request? thank you :)
The code is:
<form>
<lable for="Variable">
<input type ="text" name="variable" placeholder="Search by : ">
</form>
<?php
$variable = $_POST['variable']
sql = 'SELECT * FROM Total ORDER BY $variable';
?>
Please refer to PDO and for order by review.
your select query would be
SELECT * FROM yourtable ORDER BY DATABASE_FIELD;
At first,
use method="POST" and action="file.php" (but action is not strictly needed, in some cases like processing by AJAX)
<form method="POST" action="file.php">
<lable for="Variable">
<input type ="text" name="variable" placeholder="Search by : ">
</form>
At second you need sanitize input taken from form (it means, you have to eliminate anything that would harm your pages - with this PDO or else layer can help).
At third, you need to rewrite
sql = 'SELECT * FROM Total ORDER BY $variable'
to
sql = "SELECT * FROM Total ORDER BY $variable"
or
sql = 'SELECT * FROM Total ORDER BY '.$variable
because else used variable would be used as is written, instead its content (given by form).
Since you're new it would be wise to embed some good practices from the start. Documentation for reference would be PDO and Prepared Statements.
An example PDO tutorial can be found on W3Schools, along with a tutorial on handling form data with PHP.
This is an example of a simple search
PHP:
<?php
$search = $_POST["search"];
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM `profile` WHERE `email`='$search'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
HTML:
<form action="profile.php" method="post">
<input type="text" name="search"><br>
<input type="submit">
</form>
Hope it helps
I just started learning php and mysql and i might already be way ahead of myself. The thing i would like to create is a webpage where ppl can sign up for an event, so far so good, the form to submit their first name, last name, age and email adress is working and its actually sending te information to the database.
Next thing i want to create is a page where i can display all the database records submitted (except for the email adress). This is also working, but I wanted to play around with dynamic urls.
When i visit my page http://www.example.com/ppl.php?id=1 i get the information of the first database record displayed but i also wanted to see if i could get this to work with names instead of ids so i tried to edit my code and use http://www.example.com/ppl.php?name=john this does only return an error and however there are a few people called john in the database no records are displayed.
So i would like to know if what i want is actually possible and how do i get this to work with my current code.
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "event";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$id = $_GET['id'];
$firstname = 'firstname';
$lastname = 'lastname';
$age = 'age';
$sql = "SELECT * FROM people WHERE id = $id";
$result = $conn->query($sql);
echo "<table id='display' width='600' align='center'>";
echo"<tr><td> Firstname</td> <td> Lastname</td> <td> Age</td>";
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo"<tr><td width='33%'> $row[$firstname]</td> <td width='33%'> $row[$lastname]</td> <td width='33%'> $row[$age] cm</td></tr>";
}
} else {
echo "0 results";
}
$conn->close();
?>
Try to change the query:
$sql = "SELECT * FROM people WHERE id = $id";
To:
$name = $_GET['name'];
$sql = "SELECT * FROM people WHERE name LIKE '%$name%'";
Then echo for each one John you find.
Also consider using CSS like this.
<style>
#display {
width: 600px;
}
#display td {
width: 33%;
}
</style>
You should be looking for two separate $_GET keys: id OR name.
<?php
if (isset($_GET['id'])) {
// logic to get row by ID
} elseif (isset($_GET['name'])) {
// logic to get row by Name
} else {
// logic if no $_GET keys are set
}
I would recommend not using the name field for a find because it's not a primary key in your database - it may not be unique. Your query may return multiple results depending on what data is being stored.
Edit: To answer the question of where to place this in the code sample above, consider placing it where the query string is declared.
<?php
if (isset($_GET['id'])) {
$id = $_GET['id'];
$sql = "SELECT * FROM people WHERE id = $id";
} elseif (isset($_GET['name'])) {
$name = $_GET['name'];
$sql = "SELECT * FROM people WHERE name = '$name'";
}
From there you can keep the same query execution logic. But as I stated, I'd advise against using the name field as a key because it may not be unique.
Okay this is abit hard to explain but I currently have a website where I'm using PHP and MySQL to pull tables into the web pages and display them. I've been able to make a search function to look for specific values in the table. I'll show you my code.
<!DOCTYPE php>
<html>
<head>
<link rel="stylesheet" href="style.php" media="screen">
</head>
<body>
<a id="TableButton" href="/Test.php">Items Table</a>
<a id="Clear" href="index.php">Clear Search</a>
<center>
<form method="GET" id="SearchPerson">
<select name="Drop" id="Select">
<option value="FirstName">First Name</option>
<option value="Surname">Surname</option>
<option value="MobileNumber">Mobile Number</option>
<option value="Code">Code</option>
<option value="TeamGroup">Team Group</option>
<option value="Home">Home</option>
</select>
<input type="text" name="Box">
<input type="submit" value="Search">
</form>
</center>
<?php
$host = "localhost";
$user = "root";
$pass = "password";
$db = "Database";
$connection = mysql_connect($host, $user, $pass) or die ("Unable to connect!");
mysql_select_db($db) or die ("Unable to select database!");
if($_REQUEST['Drop']=='MobileNumber') {
$MobileNumber = $_REQUEST['Box'];
$query = "SELECT * From Person WHERE MobileNumber = $MobileNumber";
}
elseif($_REQUEST['Drop']=='Code') {
$Code = $_REQUEST['Box'];
$query = "SELECT * From Person WHERE Code = '$Code'";
}
elseif($_REQUEST['Drop']=='TeamGroup') {
$TeamGroup = $_REQUEST['Box'];
$query = "SELECT * From Person WHERE TeamGroup = '$TeamGroup'";
}
elseif($_GET['Drop']=='FirstName') {
$FirstName = $_REQUEST['Box'];
$query = "SELECT * From Person WHERE FirstName = '$FirstName'";
}
elseif($_GET['Drop']=='Surname') {
$Surname = $_REQUEST['Box'];
$query = "SELECT * From Person WHERE Surname = '$Surname'";
}
elseif($_REQUEST['Drop']=='Home') {
$Home = $_REQUEST['Box'];
$query = "SELECT * From Person WHERE Home = '$Home'";
}
else{
$query = "SELECT * FROM Person";
}
print "<center id=Title>Person Table</center>";
$result = mysql_query($query) or die ("Error in query: $query. ".mysql_error());
if (mysql_num_rows($result) > 0) {
$row = mysql_fetch_assoc($result);
print '<center><table><tr>';
foreach($row as $name => $value) {
print "<th>$name</th>";
}
print '</tr>';
while($row) {
print '<tr>';
foreach($row as $key=>$value) {
if($key=='MobileNumber'){print "<td><a href='/Test.php?MobileNumber=$value'>$value</a></td>";}
elseif($key=='TeamGroup'){print "<td><a href='/Test.php?TeamGroup=$value'>$value</a></td>";}
elseif($key=='Group'){print "<td><a href='/Test.php?Home=$value'>$value</a></td>";}
else{print "<td>$value</td>";}
}
print '</tr>';
$row = mysql_fetch_assoc($result);
}
print '</table></center>';
}
else {
echo "No People found!";
}
mysql_free_result($result);
mysql_close($connection);
?>
</body>
</html>
Problem is even though I've got the search working it only works if I have the full values whereas i want it so say that i put part of someone mobile number in then itll display the mobile numbers that have those parts of the value in it. For example say that a few people had a mobile number starting with 0783 and I type that into the search box I want it to show up all people with 0783 in their mobile number.
What you are looking for is "SELECT * FROM Person WHERE MobileNumber LIKE '%".$_POST['MobileNumber']."%'", which will look for any string that contains the string you want, but may also be longer on either side. For example, "foo" will return the rows with values "foobar", "barfoo", "barfoobar" and of course "foo", but not "fo".
The % is a wildcard here, which means that you can also do something like "SELECT * FROM Person WHERE MobileNumber LIKE '".$_POST['MobileNumber']."%'" if you specifically want to return rows with values starting with your string ("foobar", but not "barfoo" in our example above).
Please also note the " and '.
Also:
Don't use mysql_query. It's depreciated and will be removed in future versions of PHP. Use PDO or mysqli instead.
Your code is definitely not safe. At least use prepared statements to prevent injection. I would advise against using addslashes as it is very prone to resulting in double escapes if you are not paying attention, and as far as you may also want to go the magic_quotes, be aware it is not portable and may cause you trouble if you rely solely on this. Use mysql_real_escape_string instead, as it is very mysql-oriented and specific.
Alrighty, so i'm quite a beginner when it comes to PHP and MySQL programming so the problem might be quite noobish but anyway here's my situation. I've got a content page with a dropdown menu that should give me a $_POST value (the options are taken from a database column): here's the code for that
<link href="../css/pagestyle.css" rel="stylesheet" type="text/css" />
<?php
include("../panel/config.php");
$db = mysqli_connect($server, $username, $password, $database);
if(mysqli_connect_errno()) { //if connection database fails
echo("Connection not established " .
mysqli_connect_error($db) . "</p>");
}
$query = "SELECT username FROM users WHERE email = '1' ORDER BY username ASC";
$result = mysqli_query($db,$query);
if (!$result) {
echo("Error, the query could not be executed: " .
mysqli_error($db) . "</p>");
mysqli_close($db);
}
echo "
<form action='myscript' method='post'>
<select name='test'>
<option value = 'none' selected = 'selected' >
`Select a DJ:` </option>";
while ($row = mysqli_fetch_assoc($result)){
echo '<option value="' . $row['username'] . '">' . $row['username']. '</option>';
}
echo"
<input type='submit' value='submit' name='submit'>
</select>
</form> ";
?>
Quite a bit of code for such a small function i know. Anyway the drop down menu gets its options from a database column and that works fine, now when i press the submit button, it runs another php page that's coded like this:
<link href="../css/pagestyle.css" rel="stylesheet" type="text/css" /><html>
<?php
include("../panel/config.php");
$con = mysqli_connect($server, $username, $password, $database);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$id = $_POST['test'];
$order = "UPDATE `habboxli_system`.`users` SET `points` = points+1 WHERE `users`.`username` ='$id'";
mysql_query($order);
echo "name is $id";
mysqli_close($con);
echo "Vote posted!";
?>
This code should take the value that was chosen in the drop down menu and use it to update a specific cell in the database, i signed it to a variable called $id just for testing purposes but the value seems to be blank, so from that i presume that the drop down menu didn't return a value when it navigated from the original page (www.mywebsite.com/#/option.php) to the myscript.php page (www.mywebsite.com/#/myscript.php). Any help on how to get this to work would be much appreciated.
As was said in the comments, you are using the mysql_query function mixed in with the mysqli functions.
I got the code to work for me by changing
mysql_query($order);
To:
mysqli_query($con, $order);
You can also debug what was passed to the script by simply printing the $_POST array:
print_r($_POST);