Explode array and define Variables - php

I have the following which returns
"soccertennisfootball"
$interestsquery = "SELECT * FROM user_interests WHERE user_id = " . $usersClass->userID();
$result = mysql_query($interestsquery);
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
echo "{$row['interest']}";
}
Can somebody please explain how I can explode the data and assign it as variables? I've been looking around at tutorials but they all seem to have some sort of delimeter?
Ive tried the following oly its acting very weird and printing out multiple times?
the following...
$interestsquery = "SELECT * FROM user_interests WHERE user_id = " . $usersClass->userID();
$result = mysql_query($interestsquery);
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
$interests[] = $row['interest'];
$interest1 = $interests[0];
$interest2 = $interests[1];
$interest3 = $interests[2];
print $interest1 . " - " . $interest2 . " - " . $interest3;
}
Prints out
"Tennis - Tennis - Footy - Tennis -Soccer - Footy"

They aren't a single string, you're just echoing it out. Store it somewhere. This code stores it in a new array. It may be useful but it really depends on what you want to do with it.
$interests = array();
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
$interests[] = $row['interest'];
}

In each iteration of the while loop, you can only access one of the results (first 'soccer', then 'tennis', then 'football'). In your second code block, you're trying to somehow access all three inside the while loop.
Instead, inside the while loop, push that single result into an array:
$interests = array();
while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$interests[] = $row['interest'];
//First 'soccer' will be pushed into $interests, then 'tennis', then 'football'.
}
Now that you have all the values in the array, you can access each individually. This is done OUTSIDE the while loop:
echo $interests[0] . ' - ' . $interests[1] . ' - ' . $interests[2];
This will print "soccer - tennis - football".
Alternately, like some have said, you can loop through the $interests array and echo each value, or do whatever else you'd like with them.

Put them in an array, then do as you will with it after.
$interests = array();
while (...)
{
$interests[] = $row['interest'];
}

Use extract method from php http://php.net/manual/en/function.extract.php
$interestsquery = "SELECT * FROM user_interests WHERE user_id = " . $usersClass->userID();
$result = mysql_query($interestsquery);
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
extract($row);
echo $interest;
}

Use below snippet to store values in array
$interestsquery = "SELECT * FROM user_interests WHERE user_id = " . $usersClass->userID();
$result = mysql_query($interestsquery);
$result = array();
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
$result[] = $row['interest']
}
print_r($result);

Given your clarifications (using MySQL, interest is the only column, and sample output) I would suggest using GROUP_CONCAT(). This puts it all on the MySQL side and allows you to pull the single row from $result.
Try the following sample query:
$query = "SELECT GROUP_CONCAT(interest SEPARATOR ' - ') FROM user_interests
WHERE user_id = " . $usersClass->userID() . "
GROUP BY user_id";

Related

Output of DISTINCT and <> from SQL Query issue

I am obtaining some values from an array and making a match against these values in an SQL Query.
The code for this is as follows:
foreach($files as $ex){
$search = substr($ex,3,4);
echo $search . '<br>';
echo '<br>';
$sql = 'SELECT DISTINCT `pdb_code` FROM pdb WHERE `pdb_code` <> "' . $search . '" LIMIT 4';
}
$result = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_array($result)){
echo 'SQL' . $row['pdb_code'] .'<br>';
$pdb[] = $row['pdb_code'];
}
The issue that I am having is that the <> seems not to be working.. I have even tried using the != operator, but still having the same issue.
The output of $search from the array are :
101m
102l
102m
103l
The output of SQL from the query is still:
101m
102l
102m
103l
Your code doesn't seem that logical, as you generate numerous SQL statements and then just execute the last one.
However I assume what you want to do is take a list of files, extract a string from each file name and then list all the pdb_code values from the table which are not already in the string.
If so something like this would do it. It takes each file name, extracts the sub string and escapes it, putting the result into an array. Then it builds one query, imploding the array to use in a NOT IN clause:-
<?php
$search_array = array();
foreach($files as $ex)
{
$search = substr($ex,3,4);
echo $search . '<br>';
echo '<br>';
$search_array[] = mysql_real_escape_string($search);
}
if (count($search_array) > 0)
{
$sql = "SELECT DISTINCT `pdb_code` FROM pdb WHERE `pdb_code` NOT IN ('" . implode("','", $search_array) . "') LIMIT 4";
$result = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_array($result))
{
echo 'SQL' . $row['pdb_code'] .'<br>';
$pdb[] = $row['pdb_code'];
}
}
You have to use not in:
SELECT * FROM table_name WHERE column_name NOT IN(value1, value2...)
Try this:
$searchIds = implode(',',$search);
$sql = "SELECT DISTINCT `pdb_code` FROM pdb WHERE `pdb_code` NOT IN ('$searchIds') LIMIT 4";

Separate records with comma

I'm new to php and I want to separate the records with a comma.
Database:
the table in sql
I use this code to get the data:
<?php
$id = get_the_ID();
$sql = "SELECT *
FROM tablename
WHERE parent_id=$id";
$result = $conn->query($sql);
while($row = mysqli_fetch_array($result))
{
echo "Test: " . $row["value"]. "<br>";
}
mysqli_close($con);
?>
It return twice as:
Test: Test
Test: Test1
I want to separate the records with a ',' like this:
Test: Test, Test1
Store your values in an array and than implode with ",". You will get the result:
$id = get_the_ID();
$sql = "SELECT *
FROM tablename
WHERE parent_id=$id";
$result = $conn->query($sql);
$yourArr = array();
while($row = mysqli_fetch_array($result))
{
$yourArr[] = $row["value"];
//echo "Test: " . $row["value"]. "<br>";
}
echo "Test: ". implode(",",$yourArr);
You can do this entirely in MySQL using GROUP_CONCAT:
<?php
$id = get_the_ID();
$sql = "SELECT `parent_id`, GROUP_CONCAT(`value` SEPARATOR ', ') AS comma_separated_values
FROM tablename
WHERE `parent_id` = '$id'
GROUP BY `parent_id`";
$result = $conn->query($sql);
while ($row = mysqli_fetch_array($result))
{
echo 'Test: ' . $row["comma_separated_values"]; // Test: test, test2
}
mysqli_close($con);
?>
You should change the "comma_separated_values" name to something more appropriate for your data.
In your particular case, you would not need the while() loop either as we're limiting the MySQL to a single row.
If you were to remove the WHEREparent_id= '$id' from the SQL query, then you could return the results of multiple parent_id values. For example:
while ($row = mysqli_fetch_array($result))
{
echo 'Parent ' . $row['parent_id'] .': ' . $row["comma_separated_values"] . '<br>';
}
Would return:
Parent 292: Test1, Test2
Parent 293: Test3, Test4
Parent 294: Test5, Test10, Test50
etc...
you can use update query for this
$query="Update tablename set value=CONCAT(value,',test1') where parentid='295'";
$result=mysqli_query($conn,$query);

Mysql query for multiple array values

I have this query:
$relatedtags = $video->tags;
$relatedtagsagain = explode(",", $relatedtags);
$query_parts = array();
foreach ($relatedtagsagain as $item) {
$query_parts[] = "'%".mysql_real_escape_string($item)."%'";}
$string = implode(",", $query_parts);
$result = $cachedb->get_results("SELECT ".DB_PREFIX."videos.title,".DB_PREFIX."videos.id as vid,".DB_PREFIX."videos.thumb, ".DB_PREFIX."videos.views,".DB_PREFIX."videos.duration,".DB_PREFIX."users.name, ".DB_PREFIX."users.id as owner FROM ".DB_PREFIX."videos LEFT JOIN ".DB_PREFIX."users ON ".DB_PREFIX."videos.user_id = ".DB_PREFIX."users.id where ".DB_PREFIX."videos.tags LIKE {$query_parts[0]} OR ".DB_PREFIX."videos.tags LIKE {$query_parts[1]} limit 0,".get_option('related-nr')." ");
How can get results for more $query_parts[] like $query_parts[2] and $query_parts[3] or from all the array? using LIKE $query_parts[] wont work.
lets go back to the basic of programming, this can be solved in many ways, like using array_mapping(see comment of scrowler), loops and many more:
sample using foreach loop:
foreach ($relatedtagsagain as $item) {
$query_parts[] = " videos.tags LIKE " . "'%". mysql_real_escape_string($item) . "%' ";
}
$parsed_query_parts = implode('OR', $query_parts);
$result = $cachedb->get_results("SELECT ".DB_PREFIX."videos.title,".DB_PREFIX."videos.id as vid,".DB_PREFIX."videos.thumb, ".DB_PREFIX."videos.views,".DB_PREFIX."videos.duration,".DB_PREFIX."users.name, ".DB_PREFIX."users.id as owner FROM ".DB_PREFIX."videos LEFT JOIN ".DB_PREFIX."users ON ".DB_PREFIX."videos.user_id = ".DB_PREFIX."users.id WHERE" . $parsed_query_parts . " limit 0,".get_option('related-nr')." ");

Explode array and assign as variables

I have a table in the following structure...
ID USER_ID INTEREST
1 290 soccer
2 290 tennis
3 290 badminton
4 560 netball
I want to grab all values from the table where the user id is equal to the session user id and assign them as variables.
I have the following which works but displays the data very peculiarly..
$interestsquery = "SELECT * FROM user_interests WHERE user_id = " . $usersClass->userID();
$result = mysql_query($interestsquery);
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
$interests[] = $row['interest'];
$interest1 = $interests[1];
$interest2 = $interests[2];
$interest3 = $interests[3];
print $interest1 . " - " . $interest2 . " - " . $interest3;
}
The above however outputs something along the lines of...
- - tennis - - tennis - badminton -
Can anybody see where I'm going wrong?
This should do what you need:
$interestsquery = "SELECT `interest` FROM `user_interests` WHERE `user_id` = " . $usersClass->userID();
$result = mysql_query($interestsquery);
$interests = array();
while(list($interest) = mysql_fetch_array($result))
$interests[] = $interest;
print explode($interests, ' - ');
Think what happens to your loop at the first iteration:
$interest is an empty array
you fetch the first value and put it into $interest[0],
you fill $interest1 with the value that lies into $interest[1] (it is empty)
same for $interest2 and $interest3
you print ""." - ".""." - ".""
in the second run:
$interest is [0=>soccer]
you fetch the second value and put it into $interest[1],
you fill $interest1 with the value that lies into $interest[1] tennis
same for $interest2 and $interest3 (that are still empty)
you print "tennis"." - ".""." - ".""
and so on.
You need print the result when you exit the while loop (and the code is still flawed as
it don't get the value into the index 0 of the array).
An alternative should be:
$interestsquery = "SELECT `interest` FROM `user_interests` WHERE `user_id` = "
. $usersClass->userID();
$result = mysql_query($interestsquery);
$interests = array();
// you fetch just a field, fetch_row will be sufficent
while($interest = mysql_fetch_row($result)) {
array_push($interests, $interest[0]);
}
echo implode(' - ', $interests);
$interests = array();
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
$interests[] = $row['interest'];
}
$int_count = count($interests);
$i=0;
foreach ($interests as $interest) {
$var = 'interest' . ($i + 1);
$$var = $interest;
$i++;
}
print $interest1 . " - " . $interest2 . " - " . $interest3;

retrieving a mysql query

I have written a mysql query and fetched the result as an assoc array using mysql_fetch_assoc().The query returns a list for two fields.I am looping through this field using through the result array and am extracting the value.how do i display the two fields since doing a plain echo is not working for me?The code which i have written is
Thanks in advance.
$query = "SELECT x,y FROM table";
$result = mysql_query( $query , $resourcelink);
while( $s= mysql_fetch_assoc( $result ) )
{
extract( $s );
echo $x . " - " . $y . "<br />";
}
I advise against using extract. it makes code very hard to follow.
I'd just do this:
$query = "SELECT x,y FROM table";
$result = mysql_query( $query , $resourcelink);
while( $s= mysql_fetch_assoc( $result ) ) {
echo $s['x'], ' - ', $s['y'], '<br/>';
}
mysql_fetch_assoc returns an array of mappings of key to value. As you didn't retrieve one and two from the database, $one and $two ($s['one'] and $s['two'] respectively) don't exist. Therefore do something like this, using the columns you selected as keys.
$query = "SELECT x,y FROM table";
$result = mysql_query( $query , $resourcelink);
while( $s= mysql_fetch_assoc( $result ) )
{
echo $s['x'] . " - " . $s['y'] . "<br />";
}
Or if you want to continue using extract (I don't recommend it, it can lead to some hard to track down bugs)
$query = "SELECT x,y FROM table";
$result = mysql_query( $query , $resourcelink);
while( $s= mysql_fetch_assoc( $result ) )
{
extract($s);
echo $x . " - " . $y . "<br />";
}
extract is a bad practice, furthermore your columns are probably called x and y and not one and two.
i suggest using the following:
echo htmlspecialchars($s['x']), ' - ', htmlspecialchars($s['y']);
According to your SELECT statement mysql_fetch_assoc() returns an array like array('x'=>something, 'y'=>something)and extract() would "translate" that to $x='something' and $y='something', not $one and $two.
Try
error_reporting(E_ALL);
$query = "SELECT x,y FROM table";
$result = mysql_query( $query , $resourcelink) or die(mysql_error());
echo 'there are ', mysql_num_rows($result), " records in the result set\n";
while( false!==($row=mysql_fetch_array($result, MYSQL_ASSOC)) ) {
echo $row['x'], ' ', $row['y'], "\n";
}

Categories