Search MySQL database with LIKE statement - php

I need to return search results of users in my database.
At the moment, I have managed to use the LIKE function in the MySQL query to return a results count, but I need it to echo the usernames of all the results, not just the first result:
<?php
// mysql details
$host="localhost"; // Host name
$username="classified"; // Mysql username
$password="classified"; // Mysql password
$db_name="jaycraftcommunity"; // Database name
$tbl_name="members"; // Table name
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// form variable to local
$search = $_POST['username'];
// make query
//$sql = "SELECT * FROM $tbl_name WHERE (username='$search' OR verified='$search')"; // sql query
$sql = "SELECT username FROM $tbl_name WHERE username LIKE '%$search%'"; // sql query
$result = mysql_query($sql); // do query
// handle query data
$count = mysql_num_rows($result);
$row = mysql_fetch_row($result);
$array = mysql_fetch_array($result);
echo $count;
foreach( $row as $arrays ): ?>
<tr>
<td><?php echo htmlspecialchars( $arrays ); ?></td>
<br />
</tr>
<?php
endforeach;
?>
The HTML form looks like this:
<h2>Search</h2>
<form method="post" action="search_engine.php">
Search for:
<input type="text" name="username">
<input type="submit" value="Search for username">
</form>
At the moment, if you go to http://dev.jaycraft.co/player/dupe/search.php you can see it in action. Search for individual letters, it show how many results there are with echo $count, but only echos the first result.
Thanks

Every call of mysql_fetch_row($result) will return another row and advance the cursor. You simply need to use a while() to loop over all rows in the result:
while($row = mysql_fetch_row($result)) {
echo $row[0];
}}
For ease of use, it's better to use mysql_fetch_assoc($result); which will return an associative array:
while($row = mysql_fetch_assoc($result)) {
echo $row['username'];
}}

You can
<?php
$sql = mysql_query($sql);
while($row = mysql_fetch_assoc($sql)){
echo $row['username'].'<br />';
}
?>
But please use mysqli instead of mysql! http://www.php.net/manual/en/book.mysqli.php

When you are using the prepare line, the above solutions do not work, given the substitution symbol is the same as the like symbol. Try making the search parameter within the prepare, by preformating it as a string. Then just loop through the available rows by the foreach or for loop.
$Table_Name = $wpdb->prefix.'tablename';
$SearchField = '%'. $YourVariable . '%';
$sql_query = $wpdb->prepare("SELECT * FROM $Table_Name WHERE ColumnName LIKE %s", $SearchField) ;
$rows = $wpdb->get_results($sql_query, ARRAY_A);
if(!empty($rows))
{
$TotalRows = $wpdb->num_rows;
foreach($rows as $row)
{
echo $row['field name'];
}
}

you need a while loop through your rows:
while($row = mysql_fetch_array($result){
foreach( $row as $cell): ?>
<tr>
<td><?php echo htmlspecialchars( $cell); ?></td>
<br />
</tr>
<?php
endforeach;
?>
}
mysql_fetch_row and mysql_fetch_array are almost unique functions, they both get the next row from the result set. you could use mysql_fetch_assoc to fetch the values with as key the database column name. (this is recommended)

Related

Updating dynamic links from database results

I'm playing around with PHP a bit and am trying out dynamic links. My problem is that the corresponding ID is not correctly to the URL with my code, so I have the same link everytime.
Here is what I have:
<?php
$connection = mysqli_connect('localhost', 'root', 'password');
mysqli_select_db($connection, 'filme');
$query = "SELECT * FROM filme";
$result = mysqli_query($connection, $query);
$filmID = mysqli_fetch_assoc($result);
$array = array();
while($row = mysqli_fetch_assoc($result)){
$array[] = $row['Name'] . " - " . $row['Preis'];
}
$chunks = array_chunk($array, 4);
$filmID = mysqli_fetch_assoc($result);
echo "<table class='filme'>";
foreach ($chunks as $chunk){
echo '<tr>';
foreach ($chunk as $val) {
?><td><?php echo $val; ?> </td><?php
}
echo '</tr>';
}
echo "</table>";
mysql_close();
?>
What I'm trying to do is display a table with four columns, that in every cell has a string in the format of "Film name - Price" and this string should be a link that leads to the page with the according ID. This code does display my four column table, but it is missing the first item of my database and the ID is the same for every link, namely the ID of that first film that is missing. So every URL looks like this:
http://localhost/dvd.php?Film_ID=1000
But the film with the ID 1000 is not even listed. I thought about putting that nested foreach loop in a while loop with
while($filmID = mysqli_fetch_assoc($result)){
...
}
But with that I get a blank page.
I have just about no experience with php, so sorry if I'm missing something really obvious.
You are going about this the wrong way. There's no link here between the contents of $array and $filmID. Indeed, $filmID is probably empty because you've already run through your result set earlier. Imagine your database result set is like a stack of papers. Each call to fetchAssoc() reads one sheet of paper, and sets it aside. Once you reach the end of the result set, there's nothing left to read, so your next calls will fail. You need to do all your database fetch in a single loop. As well, you should not be using mysql_close() with mysqli.
<?php
$connection = mysqli_connect('localhost', 'root', 'password');
$connection->select_db('filme');
$query = "SELECT * FROM filme";
$result = $connection->query($query);
$array = array();
while($row = mysqli_fetch_assoc($result)){
$array[] = $row;
}
$chunks = array_chunk($array, 4);
echo "<table class='filme'>";
foreach ($chunks as $chunk){
echo '<tr>';
foreach ($chunk as $film) {
?><td><?php echo "$film[Name] - $film[Preis]"; ?> </td><?php
}
echo '</tr>';
}
echo "</table>";
mysqli_close();
Or, better yet, just use the more modern PDO library:
<?php
$connection = new PDO("mysql:host=localhost;dbname=filme", "root", "password");
$query = "SELECT `Film_ID`, `Name`, `Preis` FROM filme";
$result = $connection->query($query);
$chunks = array_chunk($result->fetchAll(PDO::FETCH_ASSOC), 4);
?>
<table class='filme'>
<?php foreach ($chunks as $chunk):?>
<tr>
<?php foreach ($chunk as $film):?>
<td>
<?=htmlspecialchars("$film[Name] - $film[Preis]")?>
</td>
<?php endforeach?>
</tr>
<?php endforeach?>
</table>
Note this code is much more efficient and easier to read due to use of alternative syntax and short echo tags to keep PHP and HTML mixing to a minimum. Ideally your PHP would be in a totally separate file.

PHP passing Array

I have two php page.
In the first I have looping checkbox array :
<td><input type="checkbox" name="cek[]" value=" <?php echo "$kodeinventarisit" ?>"></td>`
Then i submit form from page one to page two :
<?php
include 'koneksi.php';
$cek = $_POST['cek'];
$jumlah_dipilih = count($cek);
for($x=0;$x<$jumlah_dipilih;$x++){
$jojo = $cek[$x];
$coba = "select * from msstok where kodeinventarisit = '$jojo' ";
$cobaquery = mysql_query($coba);
$hasil = mysql_fetch_array($cobaquery);
$jenis = $hasil['jenis'];
?>
<input name="kode" type="text" id="license" value="<?php echo htmlentities($jenis) ; ?>" readonly="readonly" />
<?php
echo "$jojo";
}
?>
The problem is in the sql query return nothing, I try echo "$jojo" and it's print the value but in the text field is empty..
Does anyone have suggestions on how to fix this?
Thank You Very Much
1
What you are doing is bad.
Load your data before your loop and loop every result to print them.
2
Protect your sql request from injection.
Connect
$db = new mysqli("","root","","");
Prepare your request
$sql = "select * from msstok where kodeinventarisit = ? ";
$res = $db->prepare($sql);
$res->bind_param("sssd",$jojo);
Get results
$res->execute();
Documentation : http://php.net/manual/fr/book.mysql.php
If you want to pass the array you need to check if arrive in you second page.
<pre>
print_r($_POST['cek']);
</pre>
Now, if arrive here, you can read the values like this:
<?php
// If is array(), then you can go to loop
if(is_array($_POST['cek']))
{
// Run the loop
foreach($_POST['cek'] as $value)
{
// Show values per line
echo $value. "<br/>";
}
}
?>
You can read only 1 value of your array
<?php echo $_POST['cek'][0]; ?>
<?php echo $_POST['cek'][1]; ?>
<?php echo $_POST['cek'][2]; ?>
Conclusion
You can't pass array to SQL in query. If you want to use it, this is the only way with implode.
$coba = "SELECT * FROM msstok WHERE kodeinventarisit IN (".implode(',', $jojo).")";
$records = mysql_query($coba, $connection);
while ($row = mysql_fetch_array($records)) {
echo "Name: " . $rows['name'] . "<br />"; // replace the name for column you want
}

PHP: Delete || Confirm delete

I am having a problem.
I am creating a script that allows a person to select a record by it's primary ID and then delete the row by clicking a confirmation button.
This is the code with the form:
"confirmdelete.php"
<?php
include("dbinfo.php");
$sel_record = $_POST[sel_record];
//SQL statement to select info where the ID is the same as what was just passed in
$sql = "SELECT * FROM contacts WHERE id = '$sel_record'";
//execute SELECT statement to get the result
$result = mysql_query($sql, $db) or die (mysql_error());//search dat db
if (!$result){// if a problem
echo 'something has gone wrong!';
}
else{
//loop through and get dem records
while($record = mysql_fetch_array($result)){
//assign values of fields to var names
$id = $record['ID'];
$email = $record['email'];
$first = $record['first'];
$last = $record['last'];
$status = $record['status'];
$image = $record['image'];
$filename = "images/$image";
}
$pageTitle = "Delete a Monkey";
include('header.php');
echo <<<HERE
Are you sure you want to delete this record?<br/>
It will be permanently removed:</br>
<img src="$filename" />
<ul>
<li>ID: $id</li>
<li>Name: $first $last</li>
<li>E-mail: $email</li>
<li>Status: $status</li>
</ul>
<p><br/>
<form method="post" action="reallydelete.php">
<input type="hidden" name="id" value="$id">
<input type="submit" name="reallydelete" value="really truly delete"/>
<input type="button" name="cancel" value="cancel" onClick="location.href='index.php'" /></a>
</p></form>
HERE;
}//close else
//when button is clicked takes user back to index
?>
and here is the reallydelete.php code it calls upon
<?php
include ("dbinfo.php");
$id = $_POST[id];//get value from confirmdelete.php and assign to ID
$sql = "SELECT * FROM contacts WHERE id = '$id'";//where primary key is equal to $id (or what was passed in)
$result=mysql_query($sql) or die (mysql_error());
//get values from DB and display from db before deleting it
while ($row=mysql_fetch_array($result)){
$id = $row["id"];
$email = $row["email"];
$first= $row["first"];
$last = $row["last"];
$status = $row["status"];
include ("header.php");
//displays here
echo "<p>$id, $first, $last, $email, $status has been deleted permanently</p>";
}
$sql="DELETE FROM contacts WHERE id = '$id'";
//actually deletes
$result = mysql_query($sql) or die (mysql_error());
?>
The problem is that it never actually ends up going into the "while" loop
The connection is absolutely fine.
Any help would be much appreciated.
1: It should not be $_POST[id]; it should be $_POST['id'];
Try after changing this.
if it does not still work try a var_dump() to your results to see if it is returning any rows.
if it is empty or no rows than it is absolutely normal that it is not working.
and make sure id is reaching to your php page properly.
Ok as you are just starting, take care of these syntax, and later try switching to PDO or mysqli_* instead of mysql..
Two major syntax error in your code:
Parameters must be written in ''
E.g:
$_POST['id'] and not $_POST[id]
Secondly you must use the connecting dots for echoing variables:
E.g:
echo "Nane:".$nane; or echo $name; but not echo "Name: $name";
Similarly in mysql_query
E.g:
$sql = "SELECT * FROM table_name WHERE id="'.$id.'";
I hope you get it..take care of these stuff..

MySQL retrieval from database not retrieving multiple rows

I'm trying to retrieve all data with the LIKE query from the users input and match it to the database, it works but only returns one record but I have many records in the table.
It returns the closest record it can find,
so say for example I have 2 records who's ItemDesc field contains the characters 'The', when I search for 'The' in my input box and click submit it returns the closest (earliest created) record when it is supposed to return both.
<?php
$username = "a3355896_guy";
$password = "++++++";
$hostname = "mysql5.000webhost.com";
$dbh = mysql_connect($hostname, $username, $password) or die("Unable to connect to MySQL");
mysql_select_db("a3355896_book") or die("Unable to connect to database");
$ItemDesc = $_POST['ItemDesc'];
$query = "select * from StockItems where ItemDesc LIKE '%$ItemDesc%'";
$result=mysql_query($query);
$num=mysql_num_rows($result);
mysql_close();
?>
Sorry was supposed to included the retrieval:
<?php
if ($num>0)
{
echo "<center><table border=1><tr><th>Item Code</th><th>Item Desc</th>";
echo "<th>Item Stock Qty</th>";
echo "<th>Item Unit Price</th><th>Item Category</th></tr>";
$ItemCode = mysql_result($result,$i,"ItemCode");
$ItemDesc = mysql_result($result,$i,"ItemDesc");
$ItemStockQty = mysql_result($result,$i,"ItemStockQty");
$ItemUnitPrice = mysql_result($result,$i,"ItemUnitPrice");
$ItemCategory = mysql_result($result,$i,"ItemCategory");
echo "<tr><td>$ItemCode</td><td>$ItemDesc</td><td align=right>";
echo "$ItemStockQty</td>";
echo "<td align=right>$ItemUnitPrice</td>";
echo "<td>$ItemCategory</td></tr>";
echo "</table></center>";
}
else
{
echo "<form name='DeleteStock2'>";
echo "<p> Sorry, $ItemDesc does not exist!<p>";
echo "<input type='button' value='Leave' onclick='history.go(-1)'>";
}
?>
You aren't actually accessing your data here- you need to iterate over the result set.
$setLength = mysql_num_rows($result);
for($i = 0; $i < $setLength; $i++){
//Here, mysql_fetch_assoc automatically grabs the next result row on each iteration
$row = mysql_fetch_assoc($result);
//do stuff with "row"
}
Unless you ARE doing that and you just chose to not include it in your snippit. Let us know :)
--Edit--
First off, I apologize- out of old habit I suggested that you use mysql_fetch_assoc instead of the mysqli set of functions.
Try using the fetch_assoc or fetch_array functions, it could solve your issue. I've never used the method you used, I think it has been deprecated for a while.
Check it out here:
http://php.net/manual/en/mysqli-result.fetch-assoc.php

error in storing data to mysql however echo gives correct output

in my tableX some datas are there which looks like this
<h1>ghhhhhh!</h1>
http://twitter.com/USERNAME
<h1></h1>
http://3.bp.blogspot.com/_fqPQy3jcOwE/TJhikN8s5lI/AAAAAAAABL0/3Pbb3EAeo0k/s1600/Srishti+Rai1.html
<h1></h1>
http://4.bp.blogspot.com/_fqPQy3jcOwE/TJhiXGx1RII/AAAAAAAABLc/XNp_y51apks/s1600/anus7.html
<h1></h1>
http://cyz.com/_fqPQy3jcOwE/TJhh1ILX47I/AAAAAAAABKk/gX-OKEXtLFs/s1600/4r-2.html
<h1></h1>
http://cyz.com/_fqPQy3jcOwE/TJhiHGgb-KI/AAAAAAAABK8/zEv_41YzMhY/s1600/19+(1).html
<h1></h1>
http://cyz.com/_fqPQy3jcOwE/TJhihkpZZKI/AAAAAAAABLs/zDnlZkerBd8/s1600/Pooja+Gurung.html
when i echo the same php code it gives correct output but when i am storing these details in mysql only one row is getting stored in mysql row.
my code is this
<?php
include('connect.php');
$idmg=$_POST["id"];
$res =mysql_query("select * from tablea");
$row = mysql_fetch_array($res);
if(sus== '0'){
$output=''.$row['content'].'';
echo $output;//this output gives the above result but when i store in db it stores first row
mysql_query ("INSERT INTO tablea (content) VALUES ('$output')");
} ?>
Your insert is failing because you have unescaped data in $output. Take DCoder's advice above and use PDO or mysqli.
Is there a reason you have sql_fetch_array() and not mysql_fetch_array() ?
You also need to iterate through your results if you want more than one row.
<?php
include('connect.php');
$idmg =$_POST["id"];
$res =mysql_query("select * from tablea");
$row = sql_fetch_array($res)
if($sus== '0'){
$output=mysql_real_escape_string($row['content']);
echo $output;
mysql_query ("INSERT INTO tablea (content) VALUES ('$output')");
}
?>
And as #DCoder said, you should be using prepared statements, the code you have now is vulnerable to SQL injection.
Your code some-what corrected:
<?php
include('connect.php');
$idmg=$_POST["id"];
$res = mysql_query("select * from tablea");
$row = mysql_fetch_array($res);
if($sus== '0'){ // what is sus? If variable.. should be $sus
$output = $row['content']; // .'' is literally nothing..
echo $output;
mysql_query ("INSERT INTO tablea (content) VALUES ('$output')");
}
?>
What I think you are trying to do:
<?php
include('connect.php');
$idmg = $_POST["id"]; // not actually used
$res = mysql_query('SELECT * FROM tablea');
while($row = mysql_fetch_array($res)) {
$output = $row['content'];
echo $output;
// do anything else you want.. in your case ?enter the data back in?
mysql_query("INSERT INTO tablea(content) VALUES('$output')");
}
?>
What you should be using:
<?php
$idmg = $_POST['id']; // <-- not actually used
$res = $mysqli_connection->query('SELECT * FROM tablea');
while($row = $res->fetch_array(MYSQLI_ASSOC)) {
$output = mysqli_connection->real_escape_string($row['content']);
echo $output;
// Do whatever else you like
$mysqli_connection->query("INSERT INTO tablea(content) VALUES('$output')");
}
$res->free();
$mysqli_connection->close();
?>

Categories