I'm trying to make a search function on this website that loops through my $result_array. I've tried a bunch of different approaches on my own but to no avail. Thought it was about time I asked here. This is my code:
<?php
include 'database_info.php';
$search_string = $_POST['search1'];
$query = "SELECT * FROM customers_info WHERE first_name='$search_string'";
//Try to query the database
if($result = $data_connect->query($query)){
echo '<br /><br />Successfully sent query!<br /><br />';
}
else {
echo 'Error getting customers from the database: '.mysqli_error($data_connect).'<br />';
}
//Create Table
echo "<table id='Grid'><tr>";
echo "<th>customer_id</th>";
echo "<th>First Name</th>";
echo "<th>Last Name</th>";
echo "<th>Email</th>";
echo "<th>Country</th>";
echo "<tr>\n";
$class = "odd"; //Keep track of whether a row is equal or odd
//Loop through all the rows returned by the query, creating a table row for each
while($result_array = mysqli_fetch_assoc($result)){
echo "<tr class=\"$class\">";
echo "<td>".$result_array['customer_id']."</td>";
echo "<td><a href='view_customer.php?email=".$result_array['email']."'>" .$result_array['first_name']. "</a></td>";
echo "<td>" .$result_array['last_name']. "</td>";
echo "<td>" .$result_array['email']. "</td>";
echo "<td>" .$result_array['country']. "</td>";
echo "</td></tr>\n";
//If the last row was even make the next one odd
if($class =="odd"){
$class ="even";
}
else{
$class = "odd";
}
}
echo "</table>";
$data_connect->close();
?>
Can anybody tell me a way I could accomplish this? A function or approach I could use?
P.S.
My current approach is to alter the query, this does work but then I can only search for the customer first_name for example. I want to be able to search for email address or last_name or country. These are all columns in my database.
Your query should be like:-
$query = "SELECT * FROM customers_info WHERE (first_name LIKE '%$search_string%' OR email LIKE '%$search_string%')";
This is how your query should be:
$query = "SELECT * FROM customers_info WHERE first_name='".$search_string."';";
Should work
If your PHP loop works then it's your SQL that needs to change.
Try something like:
$search_string = str_replace(" ","|",$search_string);
$query = sprintf("SELECT * FROM customers_info WHERE (
first_name REGEXP '%s' OR
last_name REGEXP '%s' OR
email REGEXP '%s'", $search_string, $search_string, $search_string)
I prefer using sprintf but that's just a personal preference. So basically I replace any white space in your $search_query with a pipe '|'. This is so REGEXP in the SQL query can search for more than one thing e.g. search Foo Bar will now search Foo and Bar which expands your results. This is optional, however.
The query simply uses a series of OR statements so that it searches in different columns.
Hope this helps!
The most secure practice for any database related stuff, is to use the PDO.
The PDO will escape your query that will avoid SQL Injections, and moreover it is easy to fetch the details.
For example of the connetivity and fetching the data:
$db = new PDO("$type:host=localhost;dbname=x;charset=utf8","user","password");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$query = $db->select("SELECT * FROM customers_info WHERE first_name LIKE %:first_name%");
$query->bindParam(':first_name', $_POST['search1']);
$query->execute();
$result = $query->fetchAll();
var_dump($result);
Moreover to get it work with few attributes like email etc use for example this query:
$query = $db->select("SELECT * FROM customers_info WHERE first_name LIKE %:search% OR email LIKE %:search% OR second_name LIKE %:search%");
$query->bindParam(':search', $_POST['search1']);
Related
I'm trying to grab a user submission from a database with two columns. One for Artist and one for title. I want to take their input from the simple form and output all of the similar results into a table on the next page. I've included the entire script I've written thus far. I'm not getting any errors on the page, but I'm also not getting any results. I've spent several days looking online to see if I can clear this up on my own, but I've had no such luck. Sorry for being so wordy, but I'm new to this site and wanted to provide as much detail as possible.
<?php
include("db_connect.php");
// - get form data from "searchform.php"
$song_query = $_GET['song_query'];
// - column 1 and column 2 are all we're looking for in the db
// - title and artist are currently the two cols. Table is named
"song_list"
$col1 = "title";
$col2 = "artist";
$tablename = "song_list";
echo "<H1>Search results</H1>";
if ($song_query == "") {
echo "What are you going to sing? You didn't enter a search term! Please
try again.";
exit;
}
// - pick the db connection out of the included file and give error if
failed.
mysqli_select_db($conn, $db_name) or die(mysqli_error());
// - cleans up string inputted by user to avoid harmful code insertion
into form
$song_query = strtoupper($song_query);
$song_query = strip_tags($song_query);
$song_query = trim($song_query);
// - set up parameters for accessing the query of the db
$sql = "SELECT $col1, $col2 FROM $tablename WHERE $col1, $col2 LIKE
'%$song_query%'";
$result = mysqli_query($conn, $sql);
if (isset($_GET['$result'])){
if (mysqli_num_rows($result) > 0){
echo "<table><tr>";
echo "<th>Artist</th>";
echo "</tr>";
while($row = mysqli_fetch_array($result)){
echo "<tr>";
echo "<td>" . $row['$result'] . "</td>";
echo "</tr>";
echo "</table>";
}
}
}
?>
You have wrong SQL, which is getting constructed at runtime
$sql = "SELECT $col1, $col2 FROM $tablename WHERE $col1, $col2 LIKE
'%$song_query%'";
which becomes
$sql = "SELECT title, artist FROM $tablename WHERE title, artist LIKE
'%$song_query%'";
Look at WHERE title, artist LIKE here
$song_query gets value from $_GET['song_query'],which changes at runtime.
This WHERE $col1, $col2 LIKE '%$song_query%' is invalid syntax you need to say
WHERE col1 LIKE '%something%' AND col2 LIKE '%something%'
So this should fix the problem
$sql = "SELECT $col1, $col2
FROM $tablename
WHERE $col1 LIKE '%$song_query%'
AND $col2 LIKE '%$song_query%'";
Although this is wide open to SQL Injection Attack
Even if you are escaping inputs, its not safe!
Use prepared parameterized statements
$sql = "SELECT title, artist
FROM songlist
WHERE title LIKE ? AND artist LIKE ?";
$stmt = $conn->prepare($sql);
$val = sprintf('%%%s%%', $song_query);
$stmt->bind_param('ss',$val, $val);
$stmt->execute();
$stmt->bind_result($title, $artist);
echo "<table><thead><tr>";
echo "<th>Artist</th><td>Title</th>";
echo "</tr></thead><tbody>";
while ($stmt->fetch()) {
echo "<tr>";
echo "<td>$artist</td>";
echo "<td>$title</td>";
echo "</tr>";
}
echo "</tbody></table>";
Also note you made a couple of mistakes building your table that I think I have fixed.
I'm trying to display an SQL table using PHP, by only passing in the table name and then working out the number of rows and columns to display the table correctly.
So far I've managed to retrieve the column names, but I'm having trouble getting it to display more than the first column's value, like this:
ID | lastName | firstname | etc..
10 | 11 | 13 | 16 | 19 | etc..
As an example.
Here is my code for retrieving the column headers:
$STH = $conn->prepare("SELECT * FROM $tableName");
$STH->execute();
$STH = $conn->query("SELECT * FROM $tableName");
$STH->setFetchMode(PDO::FETCH_ASSOC);
$headerQuery = $conn->prepare("DESCRIBE employees");
$headerQuery->execute();
$table_fields = $headerQuery->fetchAll(PDO::FETCH_COLUMN);
$num_fields = count($table_fields);
echo "<table border='1'>
<tr>";
for ($x=0;$x<$num_fields;$x++)
{
echo "<th>$table_fields[$x]</th>";
}
echo "</tr>";
And here is the code for retrieving the values, which is not working correctly:
for ($x=0;$x<$num_fields;$x++)
{
echo "<tr>";
foreach ($table_fields as &$fieldname)
{
while($row = $STH->fetch())
{
echo "<td>" . $row[$fieldname] . "</td>";
}
}
echo "</tr>";
}
Any assistance is extremely appreciated, along with any advice on how I could do what I've already got working more efficiently.
Thanks!
I feel like such an idiot for missing it, I was using the complete wrong variable for counting the rows (and not to mention the loop structure was all wrong, too)
$fieldValue = $conn->query("SELECT * FROM $tableName");
$fieldValue->setFetchMode(PDO::FETCH_ASSOC); // We'll come back to this later.
$headerQuery = $conn->prepare("DESCRIBE $tableName"); // Get our table headers from the input table.
$headerQuery->execute();
$table_fields = $headerQuery->fetchAll(PDO::FETCH_COLUMN);
$num_fields = count($table_fields); // Find out how many headers there actually are and make it a useful variable.
$sql = "SELECT COUNT(*) AS rowscount FROM $tableName"; // Run a count query to find out how many rows are in the table.
$results = $conn->query($sql)->fetchAll(PDO::FETCH_ASSOC); // n.b. - This comes out as a multi-dimensional array. This is annoying.
$num_rows = $results[0]['rowscount']; // Get the value out of the array so it's not clogging up the code.
// echo ("Number of rows: " . $num_rows); // Debugging - this was showing as 0 or 1 for the longest time, until I realised it was multidimensional above.
echo "<table border='1'><tr>"; // Build the table
for ($x=0;$x<$num_fields;$x++) // Working through the headers one by one.
{
echo "<th>$table_fields[$x]</th>"; // This was the easy bit, displaying the column headers.
}
echo "</tr>";
for($x=0;$x<$num_rows;$x++) // Now we need to go down the rows,
{
while($row = $fieldValue->fetch()) // This is where our $fieldValue comes in, pluck out the value of each field before putting it in.
{
echo "<tr>";
foreach ($table_fields as &$fieldname)
{
echo "<td>" . $row[$fieldname] . "</td>";
}
echo "</tr>";
}
}
$conn = null; // Terminate the connection. You're not needed anymore.
echo "</table>"; //Close the table
I am trying to create a rumour-based website. In one part of the site, there is a working feature where you are post rumours and the rumours are shown.
But i am working on the homepage so that the two latest rumours are placed into a table. With my code below, there is a table with no rows, despite data being in the mysql table, and this error message:
Warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource in /websites/123reg/LinuxPackage22/th/eq/li/theqlick.com/public_html/leeds.php on line 212
Any idea? My code is below:
$query = "SELECT * FROM rumour ORDER BY id DESC";
$row = mysql_fetch_assoc($query);
$id = $row['id'];
$name = $row['name'];
$description = $row['description'];
echo "<table class ='rumour' border='1'>";
echo "<tr>";
echo "<td style = 'font-size:18pt;font-family:Noteworthy-Bold;'> Hot Rumours </td>";
echo "<tr>";
echo "<td class = 'td1'>". text2link($row['description']). "</td>";
echo "</tr>";
echo "<tr>";
echo "<td class = 'td1'>". text2link($row['description']). "</td>";
echo "</tr>";
echo "</table>";
You're posting a string into mysql_fetch_assoc, and not a mysql_query...
$query = "SELECT * FROM rumour ORDER BY id DESC";
Should be
$query = mysql_query("SELECT * FROM rumour ORDER BY id DESC");
Use are directly using $query in mysql_fetch_assoc($query) which is string type.
You forget to get result. Use this instead:
$query="Your query here";
$result=msqyl_query($query);
$row = mysql_fetch_assoc($query);
You have forget to execute you query using mysql_query function
Try this code may be help you
$query = "SELECT * FROM rumour ORDER BY id DESC";
$result=mysql_query($query);
$row = mysql_fetch_assoc($result);
The manual for that function says:
array mysql_fetch_assoc ( resource $result )
You are passing it a string containing a query, not the result of running a query.
You need to pass it through mysql_query first.
… at least you do if you continue using mysql_*, which you shouldn't. It is obsolete and you should use a modern replacement.
I created a website that has multiple logins and unique informations to it.. i want to retrieve the data from one user. example my username is qwert and my password is 1234, I want to retrieve his unique information to the database. I used the sample code in w3schools and it selects all the data but all I want to do is to retrieve the data from the user which is only logged in.
can anyone help me about this? any help will be much appreciated.
mysql_select_db("xone_login", $con);
$result = mysql_query("SELECT * FROM admin WHERE username = '$myusername' ");
echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['overtime'] . "</td>";
echo "<td>" . $row['daily_rate'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
?>
Replace the code in SQL in that tutorial with this (and adapt the table and column names) one:
SELECT * FROM USERS where name ='qwert' and pass = MD5('1234')
And take care at sanitizing your variables in order to avoid SQL injection attacks !
You need to use a where clause
Also you will need to specify limits on the query to restrict the result set to 1 record
$select = "SELECT * FROM usertable WHERE username = '$user' LIMIT 0, 1";
$query = mysql_query($select) or die(mysql_error());
$result = mysql_fetch_assoc($query);
//Prints the array
print_r($result);
From a MySQL table called "submission" containing the fields "loginid, submissionid, title, url, datesubmitted, displayurl", I would like to print an HTML table thats contains all "title" and corresponding "datesubmitted" where "loginid" equals "$profile." The code I am trying to use is below. It isn't working. Any ideas why it isn't working?
Thanks in advance,
John
$profile = $_GET['profile'];
$sqlStr = "SELECT loginid, submissionid, title, url, datesubmitted, displayurl
FROM submission
WHERE loginid = $profile
ORDER BY datesubmitted DESC";
$result = mysql_query($sqlStr);
$arr = array();
echo "<table class=\"samplesrec\">";
while ($row = mysql_fetch_array($result)) {
echo '<tr>';
echo '<td class="sitename1">'.$row["title"].'</td>';
echo '</tr>';
echo '<tr>';
echo '<td class="sitename2">'.$row["datesubmitted"].'</a></td>';
echo '</tr>';
}
echo "</table>";
Your query is probably failing.
Try echoing the return from mysql_error(); after trying the query to see what the issue might be.
You should also protect your input against injection. If loginID is a username, you need to surround a string in a mySQL query with quotes - if loginID is a username. If it's an integer you may be okay.
There are more robust ways to do this but simply:
$profile = mysql_real_escape_string($_GET['profile']);
$sqlStr = "SELECT loginid, submissionid, title, url, datesubmitted, displayurl
FROM submission
WHERE loginid = '$profile'
ORDER BY datesubmitted DESC";
$result = mysql_query($sqlStr);
if($result) {
// Handle output
}
else {
echo 'query failed';
// don't leave this here in production!
echo mysql_error();
}
One problem I can see is you are not checking in the return value of mysql_query()
mysql_query() returns false if it fails to execute the query. So you need to do a check, something like:
$result = mysql_query($sqlStr);
if(! $result) {
//....error occured...prepare $message
die($message);
}
your question regards to debugging, the most important programming art. Noone can find an error for you, you have to do it yourself. With help of little tricks.
change $profile = $_GET['profile']; to $profile = intval($_GET['profile'];)
change $result = mysql_query($sqlStr); to
$result = mysql_query($sqlStr) or trigger_error(mysql_error()." in ".$sqlStr);
andd following 2 lines at the top of your code, run it again and see what it say. if still nothing, you don't have matching records in your table.
ini_set('display_errors',1);
error_reporting(E_ALL);