Comparing a php variable and mysql table element that has backslashes - php

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.

Related

How to export data from MySQL to CSV?

I am trying to export data from MySQL to CSV using PHP from a website. When a user clicks generate the report it will automatically create and this will be downloaded as a file on their computer. The code below I have been following an online tutorial but I have run into some issues. Currently, it will download but will only show one row with one date value from the MySQL data.
I was wondering what I need to do to show all the data in the csv file and how do I ensure that the names of the Rows are printed as well.
#header("Content-Disposition: attachment; filename=record.csv");
$select = "SELECT * FROM DBtable WHERE user_id=$id";
$result2 = $conn->query($select);
while ($row = $result2->fetch_assoc()) {
$data = $row['pain']."\n";
$data = $row['sleep']."\n";
$data = $row['mood']."\n";
$data = $row['heartrate']."\n";
$data = $row['time_of_entry']."\n";
}
echo $data;
exit();
Instead of setting the $row values to $data, you should echo instead
#header("Content-Disposition: attachment; filename=record.csv");
$select = "SELECT * FROM DBtable WHERE user_id=$id";
$result2=$conn->query($select);
while($row=$result2->fetch_assoc()){
echo $row['pain']."\n";
echo $row['sleep']."\n";
echo $row['mood']."\n";
echo $row['heartrate']."\n";
echo $row['time_of_entry']."\n";
}
exit();
Your code just keeps setting $data to a rows value, without actually doing anything with it. Each line overwrites the previous, so when you do echo $data, you are echoing the last value it was set to which in your case was the last loops "time of entry" value.
As for adding "names of the Rows", currently the code puts in a value then a new line. You probably want to replace "\n" with ",", so one loops data is one one line, then before the closing while loop, echo a "\n" to insert a new line character. You can then put the titles in the same way, using an echo, and comma seperated titles, followed by a new line character.
For example
echo $row['pain'].",";
echo $row['sleep'].",";
echo $row['mood'].",";
echo $row['heartrate'].",";
echo $row['time_of_entry'].",";
echo "\n";

how to explode array with certain key in php

I'm developing an app about books and I had a table for contents. before, I made a mistake and I split content in myself and insert them in database. after inserting 90 books I had 1000 records and I found out that it was wrong. Now, I create a table of content and I insert all content of every books(every book has a record), so I want to split content with character(*).
but it doesn't work.
It is my Previous code:
$sql2 = "SELECT tblcontent.content
from tblcontent,tblstory
where tblcontent.storyid=tblstory.storyid
and tblcontent.storyid='$storyid'";
$r2 = #mysqli_query($dbLink,$sql2);
$result2 = array();
while($res2 = #mysqli_fetch_assoc($r2))
{
$result2[] = $res2;
}
and I've added this code:
$result2=explode("*",$result2);
and
if(isset($result2)){
echo json_encode(array("result2"=>$result2));
}
But it doesn't work.Thanks in advance

Empty array in PHP with MySql

I am trying to code it so users can type in their -- or others -- usernames which will be converted in their UUID then returns that user's stats from my MySql databse.
The code I attempted this with is
$username = $_POST['searchbox'];
$json = file_get_contents("https://api.mojang.com/users/profiles/minecraft/".$username);
$obj = json_decode($json);
$id = $obj->id;
$rank = Database::query("SELECT * FROM playerdata WHERE uuid=:uuid", array(':uuid'=>"".$id))[0]['rank'];
echo 'Showing results for '.$_POST['searchbox'].' '.$id.' Rank: '.$rank;
Except when I run this code it outputs:
"Showing results for kingbluesapphire 0d8d246d11c54cbbb197c6bc8ba01ee2 Rank:"
I know it's not a problem with the connection to the database because other queries are working
My goal right now is to get the field in the MySql Database thats called rank and I would like to display their rank.
Given the discussion in the comments, either you have to find out what is removing the dashes which I highly recomend to or change your query to:
$rank = Database::query("SELECT *
FROM playerdata
WHERE replace(uuid, '-','')=:uuid",
array(':uuid'=>"".$id))[0]['rank'];
Databases need to be given the exact value you are looking for, any different character in a equals operation will not give you any data.
It's more like:
<?php
if(isset($_POST['searchbox']){
$sb = $_POST['searchbox']);
$json = json_decode(file_get_contents("https://api.mojang.com/users/profiles/minecraft/$sb"));
if($queryRes = $connection->query("SELECT * FROM playerdata WHERE uuid={$json->id}")){
if($queryRes->num_rows){
$o = $queryRes->fetch_object(); // guessing there's only one row or you would put this in a while loop
echo "Showing results for $sb {$o->uuid} Rank:{$o->rank}";
}
}
else{
die($connection->connect_error);
}
}
?>
I'm assuming uuid is a number. Do tell.

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!!

PHP multiple entries

I'm creating a small project with PHP/MYSQL but i can't get my query working the way i need it. I have 2 tables
Table 1 (char):
Id, name.
Table 2 (spells):
Id, char, spell_name.
I'm getting the output:
Name Spell1
Name Spell2
Name Spell3
But I need it to be:
Name Spell1
Spell2
Spell3
Here's my query:
$query = "SELECT char.name AS name, spells.spell_name AS spell
FROM char, spells
WHERE (char.id = spells.spell_name)";
Any ideas?
I think you're gonna have to first get the ID of the character to query, and then pull the spells s/he has access to. Example:
$char_id = 0; // value would be assigned arbitrarily.
$query = "SELECT *
FROM 'spells' s
WHERE s.char = $char_id;";
$result = $pdo->query($query);
while($row = $result->fetchObj()){
// do something with the spells obj here
}
With SQL, you need to grab full rows at a time, so I believe the situation you want isn't possible.
As Goldentoa11 wrote. Make two selects, or create query with two result sets (more selects in one command), or accept current state (is normal and you can verify data consistency). I prefer current state, but sometimes use any of described solution (based on query frequency, size of result etc.).
If you need to list such data, you can than use something like this:
$currentName = null;
while ($row = mysql_fetch_object($result))
{
if ($currentName != $row->name)
{
echo "<b>" . $row->name . "</b><br />";
$currentName = $row->name;
}
echo $row->spell_name . "<br />";
}

Categories