I need to do a MySQL query to search for an inexact match / match containing the submitted value.
The following is an example of what is in my database:
id img
1 1001_ABC_01.jpg
2 1001_ABC_02.jpg
3 1002_ABC_01.jpg
4 1002_ABC_02.jpg
5 1002_ABC_03.jpg
6 1002_ABC_04.jpg
7 1002_ABC_05.jpg
8 1003_ABC_01.jpg
9 1003_ABC_02.jpg
10 1003_ABC_03.jpg
I need the query to search for the first part of the filename (1002) and and assign each returned result in the img field a different variable. The maximum amount of variables would be 5.
For example, if I search 1002, it should assign the following variables:
<?php
$img1 = '1002_ABC_01.jpg';
$img2 = '1002_ABC_02.jpg';
$img3 = '1002_ABC_03.jpg';
$img4 = '1002_ABC_04.jpg';
$img5 = '1002_ABC_05.jpg';
?>
so that way I can echo each filename result individually.
Again, the maximum amount of variables here will be 5, so if more than 5 results are returned, only the first 5 will be assigned variables.
Please let me know if this is possible and how to write a PHP script to do it.
SELECT img FROM <table_name> WHERE img LIKE '%search%' ORDER BY ID DESC LIMIT 5;
You could substring function, if the first four integers are fixed like this:
select substring(img,1,4) from <table_name> where img = 'search' order by ID DESC limit 5;
I hope this will help you. Always try to use latest apis and function like MySqli try to avoid mysql_* functions because they are depreciated and MySqli is also faster then mysql_ functions
$img = '1002'; // For example
$connection = new Mysqli(host, user, password, database);
$sql = "SELECT img FROM <table_name> WHERE img LIKE '$img%' LIMIT 5";
if($connection->query($sql)){
$counter = 1;
while ($row = $connection->fetch_object()){
${'img'.$counter} = $row->img;
$counter++;
}
}
$query = "SELECT * FROM my_table WHERE img_name LIKE '%1002%' LIMIT 5";
foreach ( $fetched_row as $value ) {
echo $value [ 'img_name' ]; // or whatever you want to do
}
Something like that.
Use this query
SELECT img as IMG
FROM my_table
WHERE img LIKE '1002%'
order by id desc
LIMIT 5
<?php
$query="SELECT id,img as image FROM image_table
where img like '%$keyword%' limit 5";
$res=mysql_query($query) or die(mysql_error());
while ($img = mysql_fetch_array($res)) {
echo $img['image'];
}
?>
$con = new Mysqli(host, user, password, database);
$result = $con->query("SELECT * FROM table WHERE image LIKE %$search% ORDER BY id DESC LIMIT 5");
if($result){
while ($row = $con->fetch_object()){
$img_arr[] = $row;
}
}
I hope this will help you.
$queryStr = "SELECT img FROM table_name WHERE search_str LIKE '1002%'";
$query = mysql_query($queryStr);
while($row = mysql_fetch_assoc($query)){
$imageArray[] = $row;
}
// Print the array
echo '<pre>';
print_r($imageArray);
echo '</pre>';
// How to use the array
foreach($imageArray as $key=>$val){
echo 'File Name: '.$val;
echo '<br />';
echo '<img src="'.$val.'" />';
echo '<hr />';
}
// Now show first five result
// Alternet: You can use LIMIT and order by with mysql
// With php
for($i=0;$i<5;$i++){
echo 'File Name: '.$imageArray[$i];
echo '<br />';
echo '<img src="'.$imageArray[$i].'" />';
echo '<hr />';
}
To search for a partial match you can use the LIKE operator in SQL. In this case you could write:
$sql = "SELECT img FROM tablename WHERE img like '1002%'";
How to perform this query and obtain the results in PHP depends on the database API you are using: old MySQL? MySQLi? PDO? Also, 1002 is probably user input, in which case you have to protect your program against SQL injection attacks.
As to the second part, are you sure you want different variable names and not an array? Arrays are much easier to use. You can get different variable names if you first accumulate the data in an array and then use extract:
$result = array();
$counter = 1;
$rs = mysql_query($sql); // using old mysql API
while ($row = mysql_fetch_array($rs)) {
$result["img".$counter] = $row[0];
$counter = $counter + 1;
}
extract($result);
// now $img1, $img2, $img3, ... are defined
your code will look like this:
$input = '1002'; // For example
$query = "SELECT id, img FROM table_blah WHERE img LIKE '$input%' LIMIT 5";
This query is basically selecting id, and img from the table table_blah, and img must be the same as 1002, and % meaning absolutely anything from there on. Limited to 5 results.
Then:
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
// Code for each result here.
// id = $row['id']
// img = $row['img']
}
$query = "SELECT * FROM img_table WHERE img_name regexp concat('1002', '%')"
$results = mysql_query($query);
then $results is an array of img strings
Related
I'm trying to create an image gallery with a for loop iterated by a counter of database rows.
To make it more clear: for each row in the table, get only the id(primary index) number and the image link from the server (not all the info in the row). With that information, echo an HTML image tag with the link inside the 'src=' and the id inside the 'alt='.
Two problems here:
1- the id number of the first row isn't zero.
2- I don't have a clue on how to get the total number of rows and to fetch only those two informations (id and img source).
That way, I could subtract the total number of rows minus the id number of the first row and using it to put an end on the loop.
So how to echo this dynamic html snippet based on my databse with PHP?
My code:
<?php
$link = mysqli_connect('localhost','user','pass','db');
$result = mysqli_query($link, "SELECT * FROM `table`");
$rows = mysqli_num_rows($result);
/* free result set */
mysqli_free_result($result);
$caption = mysqli_query($link, "SELECT ");
for($i=0; $i < $rows; $i++) {
echo "<img src='$imageURL' alt='$idNumber'>";
}
?>
You need to use sql functions to iterate through the dataset results. Replace your for loop... replacing 'image_url_column' and 'id_number_column' with the name of your actual columns in your db:
while ($row = while ($row = mysqli_fetch_assoc($caption)){){
echo "<img src='".$row['image_url_column']."' alt='".$row['id_number_column']."'>";
}
This is a really easy task.
First we fetch the data from the database using mysqli_query to do the query.
Then we use mysqli_fetch_array to get an array so then we can loop through it and echo each item.
After that, we mysqli_num_rows to get the total number of rows returned and increment it by 1 so it is not zero.
NOTE: Since you are going to increment the id to avoid getting a '0', don't to forget to minus '1' if you intend to use that id for some server-side purpose.
$result = mysqli_query($link, "SELECT * FROM `table`"); //query sql
$result_array=mysqli_fetch_array($result, MYSQLI_ASSOC);//return array from the query
$count = mysqli_num_rows($result); //get numbers of rows received
foreach($result as $row){ //do a foreach loop which is really simple
echo "<img src='". $row['img_column_name_from_db'] . "' alt='" .$row['id_column_name_from_db'] + 1 . "'>"; //echo data from the array, + 1 to "$row['id_column_name_from_db']" so that 'alt=' doesn't start from '0'.
}
echo $count;
You can use the count function of MySql to achieve the total number of rows.
also you can do this via mysqli_num_rows() function of mysql.
Code:
<?php
$link = mysqli_connect('localhost','user','pass','db');
$caption = mysqli_query($link, "SELECT id, img, count(id) as total from table");
echo
//$rows = mysqli_num_rows($result);
while($rows = mysqli_fetch_assoc($caption)){
echo "<img src='$rows[img]' alt='$rows[id]'>";
echo "Total Rows: ".$rows[total];
}
?>
How to display only one row at random at the same time from DB. Everything works fine, but all rows are displayed. thanks
<?php
$sql = "SELECT id,name FROM table ";
$rows = array();
$result = $objCon->query($sql);
while($row = $result->fetch_assoc())
{
$rows[] = $row;
}
shuffle($rows);
echo '<ol>';
foreach($rows as $row)
{
echo '<li><h3>'.$row['id'].' = '.$row['name'].'</h3></li>';
}
echo '</ol>';
?>
Change your SQL request:
SELECT id,name FROM table ORDER BY RAND() LIMIT 1;
You can do it using PHP:
....
shuffle($rows);
$randomRow = reset($rows);
....
But the better way is to change your SQL query:
$query = "SELECT id, name FROM table ORDER BY RAND() LIMIT 1;"
<?php
$sql = "
SELECT id, name
FROM table
ORDER BY RAND()
LIMIT 1 ";
$result = mysql_query($sql);
// As you are only return a single row you do you require the while()
$row = mysql_fetch_array($result);
echo '<ol>';
echo '<li><h3>'.$row['id'].' = '.$row['name'].'</h3></li>';
echo '</ol>';
?>
By adding an ORDER BY RAND() in your sql query you are asking MySQL to randomly order the results then at a LIMIT to restrict the number of rows you would like returned.
The example code is written based on selecting a single row. If you would like more, e.g. 5, you will need to add a while loop.
I've been writing a script to display the names of users based on whether they are assigned an even or odd comment id. It calls up data from 2 different tables in the same database. Here is the table information:
Table 'comments' has the columns commentid, tutorialid, name, date: Table 'winners' has the columns pool, pool2, pool3, pool4, pool5, pool6, pool7. Table 'comments' has multiple rows that are updated through user input. Table 'winners' has only 1 row with numbers that are randomly generated daily.
The first part of the script that displays "Result 1" and "Result 2" is working properly. The part that isn't working is the part that calls up the usernames. I only want to display the usernames that corralate with the result that is displayed IE if Result 1 is chosen then I only want the usernames with even 'commentid's displayed.
<?php
$db = mysql_connect('localhost', 'username', 'pass') or die("Database error");
mysql_select_db('dbname', $db);
$query = "SELECT pool FROM winners";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result))
if ($row['pool'] % 2) {
echo "<h4>Result 1</h4>";
$names = get_names(1);
foreach($names as $name) {
echo $name . "<br/>";
}
} else {
echo "<h4>Result 2</h4>";
$names = get_names(0);
foreach($names as $name) {
echo $name . "<br/>";
}
}
function get_names($pool_result)
{
$name_array = array();
$query = "SELECT * FROM comments where mod('commentid',2) = $pool_result";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
array_push($name_array, $row['name']);
}
return $name_array;
}
?>
Can anyone figure out why this isn't working?
The SELECT statement with the mod is not referencing the field. Should be backticks instead of single quotes. Single quotes indicate a string constant, which would result in a constant result set (mod('commentid',2) appears to have a result of 0). It should be something like this:
$query = "SELECT * FROM comments where mod(`commentid`,2) = $pool_result";
Adding quotes around commentid treats it as a string, and you can't mod a string by an integer. Try the following instead:
$query = "SELECT * FROM comments WHERE commentid % 2 = $pool_result";
This was taken from the following Stack question: select row if the "value" % 2 = 1. MOD()
First, I coded this, which looks inside a table, gets the last 10 entries, and displays them. The output is as expected, a list of the 10 last entries in the database.
$query = "SELECT dfid FROM downloads_downloads ORDER BY did DESC limit 10";
$dlresult = mysql_query( $query );
$i=0;
$num = mysql_num_rows ($dlresult);
while ($i < $num) {
$dfid= mysql_result($dlresult,$i,"dfid");
echo "<b>filenumber:</b> $dfid <br>";
++$i;
}
But I don't just need the filenumber. I need the actual filename and url from another table. So I added a select statement inside the while statement, using the file number.
But for some reason, this code only displays one filename instead of 10. I know, from the above code, it's getting all 10 file numbers.
$query = "SELECT dfid FROM downloads_downloads ORDER BY did DESC limit 10";
$dlresult = mysql_query( $query );
$i=0;
$num = mysql_num_rows ($dlresult);
while ($i < $num) {
$dfid= mysql_result($dlresult,$i,"dfid");
$query2 = "SELECT file_name, file_name_furl FROM downloads_files WHERE file_id = '$dfid'";
$dlresult2 = mysql_query( $query2 );
$dlfile_name= mysql_result($dlresult2,$i,"file_name");
$dlfile_name_furl= mysql_result($dlresult2,$i,"file_name_furl");
echo "filenumber: $dfid <br>"; //Shows 10, as expected.
echo "filename: $dlfile_name - $dlfile_name_furl <br>"; //Shows only 1?
++$i;
}
I can manually execute the sql statement and retrieve the file_name and file_name_furl from the table. So the data is right. PHP isn't liking the select within the while statement?
Looks like you're only going to ever have 1 row, in your 2nd select statement, because you are just selecting one row, with your where statement.
So, you're only going to ever have row 0 in the 2nd statement, so its only finding row 0 on the first loop. try instead:
$dlfile_name= mysql_result($dlresult2,0,"file_name");
$dlfile_name_furl= mysql_result($dlresult2,0,"file_name_furl");
However, insrtead of making 11 separate queries, try using just one:
$link = new mysqli(1,2,3,4);
$query = "SELECT downloads_downloads.dfid, downloads_files.file_name, downloads_files.file_name_furl FROM downloads_downloads LEFT OUTER JOIN downloads_files ON downloads_files.file_id = downloads_downloads.dfid ORDER BY downloads_downloads.dfid DESC limit 10;
$result = $link->query($query) ;
if((isset($result->num_rows)) && ($result->num_rows != '')) {
while ($row = $result->fetch_assoc()) {
echo "filenumber: $row['dfid'] <br>";
echo "filename: $row['file_name'] - $row['file_name_furl'] <br>";
}
Read up on mysql joins http://www.keithjbrown.co.uk/vworks/mysql/mysql_p5.php
I'm not sure if this is syntax correct, but it gives you the right idea =)
Pretty new to all this, so if I am going about my puzzle in a crazy way please tell me!
I have a table in a mySQL database with the columns title, hyperlink, imagelink
I want the php to select a row at random, then be able to save the title, hyperlink and imagelink as php variables. (so I can then output them into html)
so I could have for e.g
psuedoey code to get the idea
chosenNumber = randomNumber();
$chosenTitle = title[chosenNumber]
$chosenHyperlink = hyperlink[chosenNumber]
$chosenImagelink = imagelink[chosenNumber]
echo "<a href = $chosenTitle><img src= $chosenImagelink/> $chosenTitle </a>";
I think I need to use an assoc array like this here but I am very confused, because I looked through the various php mySQL fetch_assoc fetch_row etc and can't find which one to do what i need :(
What I have so far is
// database table name information
$number = "number";
$title = "title";
$hyperlink = "hyperlink";
$imagelink = "imagelink";
// sql to select all rows of adverts
$sql = "SELECT $number, $title, $hyperlink, $imagelink FROM $table";
//execute the sql
$data = mysql_query($sql, $link);
//count the number of rows in the table
$bannerCount = mysql_num_rows($data);
//generate a random number between 0 and the number of rows
$randomNumber = mt_rand(0, $bannerCount); //do I need to do bannerCount-1 or similar here?
$chosenNumber = $randomNumber;
//select data from a random row
First time post, be kind please, and thanks for any replies or explanations!
Using ORDER BY RAND() LIMIT 1 is a decent way to get a single row out of a smaller table. The downside to using this method is that RAND() must be calculated for every row in the table, and then a sort must be performed on this non-indexed value to calculate the row you want. As your table grows, ORDER BY RAND() becomes horribly inefficient. The better way to handle this is to first get a count of the number of rows in the table, calculate a random row number to read, and use the LIMIT [offest,] count option on your SQL query:
$sql = "SELECT COUNT(*) as rows FROM $table"
$res = mysql_query($sql);
if (!$row = mysql_fetch_assoc($res)) {
die('Error Checking Rows: '.mysql_error());
}
$rows = $row['rows'];
// now that we know how many rows we have, lets choose a random one:
$rownum = mt_rand(0, $rows-1);
$sql = "SELECT number, title, hyperlink, imagelink FROM $table LIMIT $rownum,1";
$res = mysql_query($sql);
$row = mysql_fetch_assoc($res);
// $row['number'] $row['title'] etc should be your "chosen" row
This first query asks the SQL Server how many rows are available, then LIMITs the result set of the actual query to only return 1 row, starting at the random number row we picked.
I think if you use the "limit" clause, it would be quite efficient:
SELECT number, title, hyperlink, imagelink FROM $table order by rand() limit 1
Why do you set up variables for the table name and field names?
If you want to get records randomly, you can simply modify your sql query and each time you will get random ordering of records, just add order by rand() to your query and limit clause if you want to get just one random record:
$sql = "SELECT $number, $title, $hyperlink, $imagelink FROM $table
order by rand() limit 1";
Once you have done that, you need to use functions like mysql_fetch_array or mysql_fetch_object to get the rows actually:
$data = mysql_query($sql, $link);
while ($row = mysql_fetch_array($data))
{
echo $row['title'] . '<br />';
echo $row['hyperlink'] . '<br />';
echo $row['imagelink'] . '<br />';
}
With:
$row = mysql_fetch_array($data)
You have $row array available at your disposal to echo values at any place of your page like:
echo $row['title'];
echo $row['hyperlink'];
echo $row['imagelink'];