MYSQL select only part of a column - php

I running a simple mysql query and trying to grab from the src column but I only want to grab the "video#.mp4" part - not the whole value (see picture attached below)
If anyone knows how to achieve this... I really appreciated it! Thank you for any help!
Code:
$con=mysqli_connect("localhost","test","123","test");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="SELECT id, title, src, type, poster_img FROM TABLE_NAME";
if ($result=mysqli_query($con,$sql))
{
$id = 0;
// Fetch one and one row
while ($row=mysqli_fetch_row($result))
{
// Show video#.mp4 here ///
echo '';
$id++;
}
// Free result set
mysqli_free_result($result);
}
mysqli_close($con);

I suggest you to store quality and video name in 2 different columns, because this will help you in searching etc.
In your example, you can achieve your desired result by using json_decode but again, it will work if you have valid json in src column.
Example:
$string = '[{"quality":"default","mp4":"video2.mp4"}]';
$array = json_decode($string,true);
print_r($array);
Result:
Array ( [0] => Array ( [quality] => default [mp4] => video2.mp4 ) )
Now you can get the index mp4 easily, if you have multiple file format, than you can group than inside your loop.

Related

Retreive element from PhP array

I am getting data from database in PhP array data_areas like this:
$query_area = "SELECT name FROM area where id>0";
$result = pg_query($con, $query_area) or die("Cannot execute query: $query_area\n");
if(pg_num_rows($result))
{
$data_areas=array();
while($row=pg_fetch_row($result))
{
$data_areas[] = array(
'name'=>$row[0]
);
}
pg_free_result($result);
pg_close($con);
$area1=$data_areas[0];
$area2=$data_areas[1];
}
How to retrieve the element from array in different variables, for example, I tried to retrieve data in area1 and area2 variable. Thank you
you can write like this;
$data_areas[0]['name']
Try Below code
$query_area = "SELECT name FROM area where id>0";
$result = pg_query($con, $query_area) or die("Cannot execute query: $query_area\n");
if(pg_num_rows($result))
{
$data_areas=array();
while($row=pg_fetch_row($result))
{
$data_areas[] = array(
'name'=>$row[0]
);
}
pg_free_result($result);
pg_close($con);
$area1=isset($data_areas[0]['name']) ?$data_areas[0]['name'] : '' ;
$area2= isset($data_areas[1]['name']) ? $data_areas[1]['name'] : '';
}
So first things first. You need first of all set up your array that you retrieve your data from the db.
Inside your while loop , and considering that you know what each of the rows has as associated value you can do something like:
$data_areas[] = array(
'name' => $row[0],
'surname' => $row[1],
'email' => $row[2]
);
This will create your array with all the values.
Now if you want to access/assign it's of those array values i am pretty sure you will need new dedicated arrays as your query retrieves all data from the table (small note that you don't need where id>0 as your id is auto increment so it will always be greater than 0)
Having said that we can move forward.
In order to access this data you can simple try:
print_r($data_areas['name']);
This will return you an array of all the names you have. So you don't need new table you can use the already existing one you have.
You are writing like this
$row[0]
Try writing this
$row['name']

PHP Selecting data from mysql with a list of items

I have a list file(buy.txt). It contains some lists of words/items. For example,"Book","Table","Fan".
I want to iterate through the list,and match the words of that list with my mysql table and select the data according to the list item from the mysql data. So,if I iterate,I should get all data of three items "Book","Table","Fan" from the mysql database. I get the data. But I get data of only one word/item from the list. For example,instead of "Book","Table","Fan",I get only "Fan" data from mysql table. Other two don't show up.
Looks like,I am not iterating the list file correctly. Can anyone help to get all data(i.e "Book","Table","Fan") not just one from the mysql....?
Looks like,I am not iterating the list file correctly. Can anyone help to get all data(i.e "Book","Table","Fan") not just one from the mysql....?
.And the 'buy.txt' file contains lists like this order :
Book
Table
Fan
Here is the php code...... :
<?php
$server='localhost';
$user='root';
$pass='123456';
$database='stock';
$all = array(); //let's store the data here
$link=mysqli_connect($server,$user, $pass, $database);
$file = "buy.txt";
$contents = file_get_contents($file);
$lines = explode("\n", $contents);
foreach($lines as $symbol) {
$sql= "SELECT * FROM `test` WHERE `price` = '$symbol'";
$data=mysqli_query($link,$sql);
$all[] = mysqli_fetch_array($data);
}
}
}
//now $all is an array and it contains all the infos, lets check it
print "<xmp>"; //<xmp> tag beautifies the output
print_r($all);
print "</xmp>";
?>
The output is :
Array
(
[0] =>
[1] =>
[2] =>
)
Thank you.

How do I scan an array and stop the scan when the number becomes false, and echo what number made the loop false in PHP

Basically I am creating a simple music player in PHP and I am setting the id of each song that is played in an array. I have a script which pulls a random number and plays the song with the corresponding id. I want to make it so that if the song has already played that it wont play again.
Currently I have it generate a random number, and if that number has already been played then it adds 1 to the random number.
The problem is if the number that is the result of adding 1 to the random number, it will then play that song again. I was attempting to store the songs played in an array and just increment the number until it doesn't exist in the array but I am struggling to find a solution to the problem.
My code is as follows:
<?php
session_start();
$con=mysqli_connect("blah blah blah");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if (!isset($_SESSION['played'])) {
$_SESSION['played'] = array();
}
$result = mysqli_query($con,"SELECT * FROM Data") ;
$num_rows = mysqli_num_rows($result);
$numsongs= .20 * $num_rows;
$numsongs=floor($numsongs);
$music = rand(1,$numsongs);
if (in_array($music, $_SESSION['played'])) {$music = $music+1;};
/* goes on to play music below */
$_SESSION['played'][] = $music;
?>
I didn't put my whole script in, the script works minus the repeating of songs. I only included a snippet of how I wrote the repeating script to give an idea of how I attempted it.
Thanks in advance!
I think you are looking for this...
$music = rand(1,$numsongs);
while(in_array($music, $_SESSION['played'])){
$music = $music+1;
echo 'in array '.$music;
}
echo 'Not in array '.$music;
AHAAA!! I figured it out! I ended up using switch() but in a different form.
if (empty($_SESSION['played1'])) {
for ($i = 1; $i <= $numsongs; ++$i) {
$_SESSION['played1'][] = $i;}}
shuffle($_SESSION['played1']);
$music1= $_SESSION['played1'][0];
$result = mysqli_query($con,"SELECT * FROM Data WHERE position = '$music1'") ;
while($row = mysqli_fetch_array($result)){
$del_val=$row[position];
if(($key = array_search($del_val, $_SESSION['played1'])) !== false) {
unset($_SESSION['played1'][$key]);}
Basically created an array between 1 and 10. Then used switch() to randomize the array. Then picked the first number in the array, used it in mysqli query, and then removed it from the array. Problem Solved!!

Comparing a php variable and mysql table element that has backslashes

I'm trying to create an online database of the music I locally have on my computer. I already have a table of every song in my library and would like to create a different table with just the song ID's (auto-incremented when I added the songs to my main table) that act as one of my playlists.
From what I can tell, the only 100% certifiable method for matching the songs is by the location on my disk ( C:\Users\username\Music\iTunes\iTunes Media\Music\Jonathan Coulton and GLaDOS\Portal\128 128 Still Alive Duet.mp3 ) as an example. In my PHP code I get the song location into a variable and if I print it relative to the equivalent song location in my MYSql table, they match up exactly but when I try to run a select statement using that, it gives me an error. From what I can tell this is being caused by the backslashes in the location info.
This is the select statement I'm using,
SELECT id FROM itunes WHERE Location=$locationval
where $locationval is the current song's location, id is the autoincremented id in my main table, and itunes is my main table.
Is there any way around this? And as I am a beginner, is the backslashes really the issue?
For reference here is the full code for importing the playlist, its using the DB plugin for PEAR (a PHP extension).
<?php
// define table name
define('TABLE_NAME', 'playlist');
// create database connection
require_once('DB.php');
$dsn = 'mysql://username:password#localhost/itunes';
$DB =& DB::connect($dsn);
if (DB::isError($DB)) {
die($DB->getMessage());
}
$DB->setFetchMode(DB_FETCHMODE_ASSOC);
// load text file
$file = file_get_contents('Portal.txt');
// explode on new line
$file = explode("\r", $file);
set_time_limit(0);
// loop through each line in the file
foreach ($file as $key => $value) {
// explode on tab to get column list
$exploded = explode("\t", $value);
// check for first row, which contains column headers
if ($key == 0) {
}
else{
if(count($exploded)>3)
{
$locationval=$exploded[26];
echo $exploded[26];
echo "<br />";
$result = mysql_query("SELECT id FROM itunes WHERE Location=$locationval");
//$result = mysql_query("SELECT * FROM itunes WHERE id=8292");
set_time_limit(0);
$row = mysql_fetch_row($result);
//test statements to see if the query worked
echo "Test: ";
echo $row['id'];
echo $row['Location'];
echo "<br />";
}
}
}
?>
Which was modified from the code here: http://ericlondon.com/posts/208-exporting-itunes-data-into-mysql-and-creating-sql-to-show-top-rated-albums
If any more info is needed, please let me know.
You need to escape the backslashes when using it in mysql as a string literal, so just replace your following line:
$result = mysql_query("SELECT id FROM itunes WHERE Location=$locationval");
for this one:
$result = mysql_query("SELECT id FROM itunes WHERE Location='". str_replace('\\','\\\\',$locationval) . "'");
that should do what you want.

How can I copy a database table to an array while accounting for skipped IDs?

I previously designed the website I'm working on so that I'd just query the database for the information I needed per-page, but after implementing a feature that required every cell from every table on every page (oh boy), I realized for optimization purposes I should combine it into a single large database query and throw each table into an array, thus cutting down on SQL calls.
The problem comes in where I want this array to include skipped IDs (primary key) in the database. I'll try and avoid having missing rows/IDs of course, but I won't be managing this data and I want the system to be smart enough to account for any problems like this.
My method starts off simple enough:
//Run query
$localityResult = mysql_query("SELECT id,name FROM localities");
$localityMax = mysql_fetch_array(mysql_query("SELECT max(id) FROM localities"));
$localityMax = $localityMax[0];
//Assign table to array
for ($i=1;$i<$localityMax+1;$i++)
{
$row = mysql_fetch_assoc($localityResult);
$localityData["id"][$i] = $row["id"];
$localityData["name"][$i] = $row["name"];
}
//Output
for ($i=1;$i<$localityMax+1;$i++)
{
echo $i.". ";
echo $localityData["id"][$i]." - ";
echo $localityData["name"][$i];
echo "<br />\n";
}
Two notes:
Yes, I should probably move that $localityMax check to a PHP loop.
I'm intentionally skipping the first array key.
The problem here is that any missed key in the database isn't accounted for, so it ends up outputting like this (sample table):
1 - Tok
2 - Juneau
3 - Anchorage
4 - Nashville
7 - Chattanooga
8 - Memphis
-
-
I want to write "Error" or NULL or something when the row isn't found, then continue on without interrupting things. I've found I can check if $i is less than $row[$i] to see if the row was skipped, but I'm not sure how to correct it at that point.
I can provide more information or a sample database dump if needed. I've just been stuck on this problem for hours and hours, nothing I've tried is working. I would really appreciate your assistance, and general feedback if I'm making any terrible mistakes. Thank you!
Edit: I've solved it! First, iterate through the array to set a NULL value or "Error" message. Then, in the assignations, set $i to $row["id"] right after the mysql_fetch_assoc() call. The full code looks like this:
//Run query
$localityResult = mysql_query("SELECT id,name FROM localities");
$localityMax = mysql_fetch_array(mysql_query("SELECT max(id) FROM localities"));
$localityMax = $localityMax[0];
//Reset
for ($i=1;$i<$localityMax+1;$i++)
{
$localityData["id"][$i] = NULL;
$localityData["name"][$i] = "Error";
}
//Assign table to array
for ($i=1;$i<$localityMax+1;$i++)
{
$row = mysql_fetch_assoc($localityResult);
$i = $row["id"];
$localityData["id"][$i] = $row["id"];
$localityData["name"][$i] = $row["name"];
}
//Output
for ($i=1;$i<$localityMax+1;$i++)
{
echo $i.". ";
echo $localityData["id"][$i]." - ";
echo $localityData["name"][$i];
echo "<br />\n";
}
Thanks for the help all!
Primary keys must be unique in MySQL, so you would get a maximum of one possible blank ID since MySQL would not allow duplicate data to be inserted.
If you were working with a column that is not a primary or unique key, your query would need to be the only thing that would change:
SELECT id, name FROM localities WHERE id != "";
or
SELECT id, name FROM localities WHERE NOT ISNULL(id);
EDIT: Created a new answer based on clarification from OP.
If you have a numeric sequence that you want to keep unbroken, and there may be missing rows from the database table, you can use the following (simple) code to give you what you need. Using the same method, your $i = ... could actually be set to the first ID in the sequence from the DB if you don't want to start at ID: 1.
$result = mysql_query('SELECT id, name FROM localities ORDER BY id');
$data = array();
while ($row = mysql_fetch_assoc($result)) {
$data[(int) $row['id']] = array(
'id' => $row['id'],
'name' => $row['name'],
);
}
// This saves a query to the database and a second for loop.
end($data); // move the internal pointer to the end of the array
$max = key($data); // fetch the key of the item the internal pointer is set to
for ($i = 1; $i < $max + 1; $i++) {
if (!isset($data[$i])) {
$data[$i] = array(
'id' => NULL,
'name' => 'Erorr: Missing',
);
}
echo "$i. {$data[$id]['id']} - {$data[$id]['name']}<br />\n";
}
After you've gotten your $localityResult, you could put all of the id's in an array, then before you echo $localityDataStuff, check to see
if(in_array($i, $your_locality_id_array)) {
// do your echoing
} else {
// echo your not found message
}
To make $your_locality_id_array:
$locality_id_array = array();
foreach($localityResult as $locality) {
$locality_id_array[] = $locality['id'];
}

Categories