Separate records with comma - php

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);

Related

I want to use two where conditions in php to get data from mysql

My problem is this:
<?php
// Connect to database server
mysql_connect("localhost", "root", "abcabc") or die (mysql_error ());
// Select database
mysql_select_db('iite') or die(mysql_error());
// Get data from the database depending on the value of the id in the URL
$strSQL = "SELECT * FROM table1 WHERE id=" . $_GET["id"];
$rs = mysql_query($strSQL);
// Loop the recordset $rs
while($row = mysql_fetch_array($rs)) {
// Write the data of the person
echo'<h1>'. $row['title'].'</h1>';
echo'<h1>'. $row['price'].'</h1>';
}
// Close the database connection
mysql_close();
?>
I want to show related posts, for this I need to insert this:
$sql = "SELECT * FROM table1 where title like '%keyword%' limit 5";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["price"]. " " . $row["title"]. "<br>";
}
} else {
echo "0 results";
}
so how can I insert the related post part near
$strSQL = "SELECT * FROM table1 WHERE id=" . $_GET["id"];
and how to echo?
Thanks
You can use OR or AND for combining different where conditions(according to requirement) in query :
Ex;
$strSQL = "SELECT * FROM table1 WHERE id=" . $_GET["id"] ." OR title like '%keyword%' limit 5";
$strSQL = mysql_query(SELECT * FROM table1 WHERE id=" . $_GET["id"] ." OR title like '%keyword%' limit 5) or die(mysql_error());
$row_strSQL = mysql_fetch_assoc($strSQL );
$totalRows_strSQL = mysql_num_rows($strSQL );
if ($result->totalRows_strSQL > 0) {
// output data of each row
while($row_strSQL= $result->fetch_assoc()) {
echo "id: " . $row_strSQL["id"]. " - Name: " . $row_strSQL["price"]. " " . $row_strSQL["title"]. "<br>";
}
} else {
echo "0 results";
}
You don't need two seperate queries for that at all. Just use the OR operator in ur where clause like Where id=" . $_GET['id']." or title like '%keyword%'

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";

PHP MySQL Display counts

I have this query for counting the number of items in a category:
SELECT category, COUNT(*) AS category_count FROM users GROUP BY category
Which creates results looking like:
category category_count
========== ================
X 3
Y 2
Now, In PHP I want to display the counts of the categories. For example, I might want to echo the count from category X, how would I do it?
Thanks in advance
Assuming $result holds the result of your query:
while ($row = mysql_fetch_array($result))
{
echo 'Category: ' . $row['category'];
if ($row['category'] == 'X')
{
echo ' Count: ' . $row['category_count'];
}
echo '<br/>';
}
$res = mysql_query("SELECT category, COUNT(*) AS category_count FROM users GROUP BY category");
while($row = mysql_fetch_assoc($res)){
echo $row['category'].": ".$row['category_count']."<br/>";
}
$result = mysql_query("SELECT category, COUNT(*) AS category_count FROM users GROUP BY category");
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
{
if ( $row['category'] == 'x' )
{
echo $row['category_count'];
}
}
while ($row = mysql_fetch_array($result))
{
echo 'Category: ' . $row['category'] . ' Count:' . $row['category_count'];
echo "<br>";
}
It would be better if you use the where clause in your query.
SELECT COUNT(*) AS category_count FROM users WHERE category = 'x'
$conn = mysql_connect("address","login","pas s");
mysql_select_db("database", $conn);
$Var = mysql_query("query");
While ($row = mysql_fetch_assoc($var) { echo $var["column"] }.

Explode array and define Variables

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";

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