I wanna do a dynamic gallery takin the images names and locations (folders where they are in) from a database.
Gallery would have always 15 photos (the last entrys in the db) so I need to sabe the images directory and names into variables to pass they to the HTML for the carousel.
I got a column "álbum_name" with the name of the álbum (folder where the image is in) and another called "img_name" wich gots the imagenames.jpg, so I need to add a / between they. I was thinking in something like:
$sql = "SELECT album_name, img_name FROM gallery WHERE status = 1 ORDER by date DESC LIMIT 15";
$result = mysqli_query($conn, $sql);
$photo0;
$photo1;
$photo2;
$photo3;
$photo4;
$photo5;
$photo6;
$photo7;
$photo8;
$photo9;
$photo10;
$photo11;
$photo12;
$photo13;
$photo14;
$img_num = mysqli_num_rows($result );
for ($i = 0; $i < $img_num ; $i++) {
// and here something to pass for each row álbum_name . "/" . img_name to the variables.
}
I was looking that for this things PHP man use while and fech_array or fech_row, but they doesnt do what I m tryng to...
Thanks.
You should have a look to the arrays
It is very easy to get an array of results, see this example (code not tested, but it should work):
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world"); // Create a connection
$mysqli->query("SELECT album_name, img_name FROM gallery WHERE status = 1 ORDER by date DESC LIMIT 15"); // Perform the query
$gallery = $mysqli->fetch_array(MYSQLI_ASSOC); // Get the results. MYSQLI_ASSOC is used here to return an associative array with the name of each table field
That's it! You can see what's inside your array $gallery
<?php
echo '<pre>';
var_dump($gallery);
echo '</pre'>;
And you can iterate it without using any counter with a foreach! :D
<?php
foreach ($gallery as $image) {
echo '<p>Album name:'.$image['album_name'].'</p>';
echo '<img src="/images/'.img_name.'/>"';
}
$sql = "SELECT CONCAT(album_name, '/', img_name) FROM gallery WHERE status = 1 ORDER by date DESC LIMIT 15";
Related
I need to display the latest 3 articles individually from the database (title, description, content and image).
$title_query = "SELECT title, description, content, image FROM articles ORDER BY id DESC LIMIT 10";
$title_result = mysqli_query($con, $title_query) or die(mysqli_error($con));
while($row = mysqli_fetch_array($title_result))
{
$title = $row['title'];
$description = $row['description'];
$content = $row['content'];
$image = $row['image'];
}
echo $title;
Currently this only gets the latest one. How can I set variables for the second and third latest one? So I can have:
$title1
$title2
$title3
etc.
Thanks
the way you construct the code, it is supposed to echo out the 3rd item's tittle. so what you should do is go through loop and keep adding them to array like below:
and since you want latest 3 items, so wht not you limit it to only 3 items like below:
$title = array();
$title_query = "SELECT title, description, content, image FROM articles ORDER BY id DESC LIMIT 3";
$title_result = mysqli_query($con, $title_query) or die(mysqli_error($con));
while($row = mysqli_fetch_array($title_result)) {
$title[] = $row['title'];
}
print_r($title);
The request what you have made to display the latest articles individually based on the id published into the DB. You need to modify the loop what you have provide over to the question.
If you want to display multiple products outside of any looping statement you have to make it store the values in an array() and after that you can use anywhere else outside the loop.
In order to make the variable as an array you can initialize an array() either in any of the two methods as you prefer.
Method: 1 - You can initialize the array() when the query returns the TRUE value.
Method: 2 - You can initialize the array() at the top of the page too.
Initializing is based on the convenience of the developer who is developing the code.
The basic Strategy for the MYSQL Limit Statement.
MySQL: SELECT LIMIT Statement
Description: The MySQL SELECT LIMIT statement is used to retrieve records from one or more tables in MySQL and limit the number of records returned based on a limit value.
Syntax:
The syntax for the SELECT LIMIT statement in MySQL is:
SELECT expressions
FROM tables
[WHERE conditions]
[ORDER BY expression [ ASC | DESC ]]
LIMIT row_count
And hence you need to modify the query like follows so that you can display the latest three articles as per your requirement.
<?php
$title_query = "SELECT `title`, `description`, `content`, `image` FROM `articles` ORDER BY `id` DESC LIMIT 0,3";
$title_result = mysqli_query($con, $title_query) or die(mysqli_error($con));
$counting = $title_result->num_rows;
if($counting==0)
{
echo 'No Datas found';
}
else
{
// This part will execute if the count is greater than 0
$row=[];
while($fetch = $title_result->fetch_assoc()) {
$row[] = $fetch;
}
}
// here you can loop through to display the data.
foreach ($row as $key => $single_data) {
?>
Title: <?php echo $single_data['title']; ?>
Description: <?php echo $single_data['description']; ?>
Content: <?php echo $single_data['content']; ?>
Image: <img src="PATH to FOLDER WHERE YOU HAVE SAVED THE IMAGE ALONG WITH <?php echo $single_data['image']; ?>" />
<?php
}
?>
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
I'm not keen on how to make an array from database. Tried to avoid learning those but apparently it's in need for now.
Basically my database is structured with millions of rows. Player Name and Snap (Unix TimeStamp) are usually "duplicated" but with different data in those rows (city, x, y, etc).
Ideally, trying to figure out HOW to make an array via SELECT statement, something like:
Output, I would like would be something like:
Name = Snap => (how many city on those day), Snap => (how many city on another day).. so on..
Question here is, what's the proper array "command" (if you call that) to pull the name ONCE and pull multiple snap with the counts based on the snap.
My SELECT goes:
// SELECT count(*), player, snap
// FROM DB WHERE GROUP BY snap, player ORDER BY snap, player DESC
while ($row = fetch_assoc($Result) {
// How you go about putting array here?
}
It'll be done like this:
$Result = mysql_query("SELECT count(*) as count, player,
snap FROM DB GROUP BY snap, player ORDER BY snap, player DESC");
while ($row = mysql_fetch_array($Result) {
print_r( $row );
echo "This is the count value -> " . $row['count'];
}
I agree with the comment about needing to read up a little more on the basics, but you can do something like the following, to create your multidimensional array:
<?php
$results = array();
$Result = 'SELECT count(*),player,snap FROM DB WHERE GROUP BY snap,player ORDER BY snap,player DESC';
while ($row = fetch_assoc($Result){
if (!isset($results[$row['player']][$row['snap']]) {
$results[$row['player']][$row['snap']] = 0;
}
$results[$row['player']][$row['snap']] += $row['count(*)'];
}
?>
Try these first:-
http://phpsense.com/2006/php-mysql/
http://www.freewebmasterhelp.com/tutorials/phpmysql
You need basics on SQL as well.
You can try
$sql = "SELECT count(*) as count, player,
snap FROM DB GROUP BY snap, player ORDER BY snap, player DESC";
/* Connect To Database */
$mysqli = new mysqli ( "localhost", "username", "password", "database" );
/* check connection */
if ($mysqli->connect_errno) {
printf ( "Connect failed: %s\n", $mysqli->connect_error );
exit ();
}
$result = $mysqli->query ( $sql );
$array = array();
if ($result) {
while ( $row = $mysqli->fetch_assoc ( $result ) ) {
$array[$row['player']] += $row['count'];
}
print_r($array); // Return array
}
I am trying to get custom data from my wordpress database, but my knowledge in sql ist that good. Could some one help me?
Please look at my example.
I am trying to echo out image names (filename) from table (wp_ngg_pictures) that have galleryid = 2
So in this example I would get the list of :
bildes-140.jpg
bildes-127.jpg
bildes-133.jpg
bildes-152.jpg
And so on....
Assuming your using PHP all you would do is connect to your database and then do something like this
$result = mysql_query("SELECT * FROM wp_ngg_pictures WHERE galleryid = 2")or die (mysql_error());
while ($row = mysql_fetch_assoc($result)) {
echo $row['filename'];
}
If you wanted more specific results it would be a little different.
Fixed the errors.. sorry bout that, still learning myself.
This should Loop though all galleries with id of 2 and echo out the id and file name.
$GetAlbum=2;
$sql = "SELECT * FROM YOURDATABASE.wp_ngg_pictures WHERE galleryid LIKE '%".$GetAlbum."%'";
$result=mysql_query($sql) or die ('Error! Could not get gallery Databse.');
$num=mysql_num_rows($result);
$i=0;
while ($i < $num) {
$gallery=mysql_result($result,$i,"galleryid");
$galleryImg=mysql_result($result,$i,"filename");
echo 'ID '.$gallery.' File '.$galleryImg.'';
}
SELECT filename from wp_ngg_pictures WHERE galleryid = 2
i'm using a php function to get dome mysql data from other mysql host than my webserver.
Function:
public function theMysqli($build){ // $build is given by othe code (no usedata)
$mysqli = new mysqli($server, $user, $password, $database);
$catid = array( /* +/- 40 id's */ ); //data is $catid = configs::songcats();
$type = array( /* +/- 15 captical letters */ ); //data is $type = configs::songtype();
$limit = 20;
$lstart = $_post['page'];
if($lstart == ''){
$lstart = 0;
}
else{
$lstart = $lstart * $limit;
}
$sletter = $_POST['letter'];
$search = $sletter.'%';
$catquery = "SELECT songid FROM category WHERE catID IN('".implode("', '", $catid)."')";
if ($db = $mysqli->query($catquery)){
while($row = $db->fetch_array()){
$idsong[] = $row;
}
$db->close();
}
foreach($idsong as $gt){
$songid[] = $gt['songid'];
}
// songid is a array over the 30000 values
$countquery = "SELECT id FROM songlist WHERE songtype IN('".implode("', '", $type)."') AND id IN('".implode("', '", $songid)."') AND songname LIKE '".$search."'";
if ($db = $mysqli->query($countquery)){
$countr = $db->num_rows;
$db->close();
}
$pages = ceil($countr / $limit);
$songquery = "SELECT id, songname, artist, copyright, duration FROM songlist WHERE songtype IN('".implode("', '", $type)."') AND id IN('".implode("', '", $songid)."') AND songname LIKE '".$search."' ORDER BY songname ASC LIMIT $lstart, $limit";
if ($db = $mysqli->query($songquery)){
while($row2 = $db->fetch_array()){
$result[] = $row2;
}
$db->close();
}
if($built == 'counter'){
$final == $pages;
}
else if($build == 'gresult'){
$final == $result;
}
return $final;
}
Now my problem is the load time he need for this script it will be to long. Even when i set php.ini so that execute may be 300sec he will stuck by loading the page. Now i know you can get data grom mutiple mysql tables by one query but i can't find any solution to do that in combination with php implode function.
Total rows i must get by $_POST['letter'] M is +/- 1200; (web radio mp3 database)
Can someone help me to fix this function so i get no timeout's anymore.
Thanks
The problem here is that you're fetching a list from the database, and then sending that list back as part of a query. You should really be doing most of this stuff in SQL, using either JOIN or nested queries. This will make your program much faster.
First, create a table for all of your catids and types. Your catquery should then be:
SELECT songid
FROM category
WHERE catID IN (
SELECT id
FROM catids
)
Use the same sort of pattern to join your queries together. It looks like you can cut down most of your code here to just one SQL query. You'll save a ton of time and memory by not having to send all that data back and forth between your program and the database.
Some reading material for you:
SQL Joins: http://beginner-sql-tutorial.com/sql-joins.htm
SQL Subquery: http://beginner-sql-tutorial.com/sql-subquery.htm