We have on a social project a member database, which includes, which member recommended an other member. The fields of the database looks like this:
id | name | email | code | recruit_by
Now we want to print a nested list of the structure, who recommended whom on all deep levels.
We didn't get it running with the following code:
<?PHP
mysql_connect("www.mysqlserver.net", "database1", "password") or die(mysql_error());
mysql_select_db("project_db1") or die(mysql_error());
echo "<ul>";
$result = mysql_query("SELECT * FROM registration") or die(mysql_error());
while($row = mysql_fetch_array($result))
{
echo "<li class=\"level0\">" . $row['id'] . " - " . $row['name'] . " - " . $row['email'] . " - " . $row['recruit_by'] . "</li>";
// 1. Level
$result2 = mysql_query("SELECT * FROM registration WHERE recruit_by LIKE " . $row['id']) or die(mysql_error());
while($row2 = mysql_fetch_array($result2))
{
echo "<li class=\"level1\">1. " . $row2['id'] . " - " . $row2['name'] . " - " . $row2['email'] . " - " . $row2['recruit_by'] . "</li>";
// 2. Level
$result3 = mysql_query("SELECT * FROM registration WHERE recruit_by LIKE " . $row2['id']) or die(mysql_error());
while($row3 = mysql_fetch_array($result3))
{
echo "<li class=\"level2\">2. " . $row3['id'] . " - " . $row3['name'] . " - " . $row3['email'] . " - " . $row3['recruit_by'] . "</li>";
// 3. Level
$result4 = mysql_query("SELECT * FROM registration WHERE recruit_by LIKE " . $row3['id']) or die(mysql_error());
while($row4 = mysql_fetch_array($result4))
{
echo "<li class=\"level3\">3. " . $row4['id'] . " - " . $row4['name'] . " - " . $row4['email'] . " - " . $row4['recruit_by'] . "</li>";
// 4. Level
$result5 = mysql_query("SELECT * FROM registration WHERE recruit_by LIKE " . $row4['id']) or die(mysql_error());
while($row5 = mysql_fetch_array($result5))
{
echo "<li class=\"level4\">4. " . $row5['id'] . " - " . $row5['name'] . " - " . $row5['email'] . " - " . $row5['recruit_by'] . "</li>";
}
}
}
}
}
echo "</ul>";
?>
Very similar to an answer i gave here:
MySQL best practice: SELECT children recursive as performant as possible?
Again not the best use case for MySQL but yeah....
Dont do so many queries, do one
"SELECT * FROM registration"
Go through the result to build this as a tree like...
// use a database query to get this member info, here a simplified version
$member = array();
$member[] = array('id' =>'2', 'recruit_by' =>'1');
$member[] = array('id' =>'3', 'recruit_by' =>'2');
$member[] = array('id' =>'4', 'recruit_by' =>'3');
$member[] = array('id' =>'9', 'recruit_by' =>'1');
//use php to build a array containing all the recruit-relationships as a tree
function buildtree($member) {
$ref = array();
foreach($member as $mem){
$member_id = $mem['id'];
$parent = $mem['recruit_by'];
if(!is_array($ref[$member_id])) $ref[$member_id] = array('id' => $member_id);
if(!is_array($ref[$parent])) $ref[$parent] = array('id' => $parent);
$ref[$parent]['child'][] = &$ref[$member_id];
}
return $ref;
}
$tree = buildtree($member);
/// use a recursive function to output the tree
function echotree($tree, $parent = 0) {
foreach ($tree as $t) {
if($parent){
echo "$parent recruited " . $t['id'] . '<br>';
}
if(is_array($t['child']) && !$parent){
echotree($t['child'],$t['id']);
}
}
}
echotree($tree);
will give you:
2 recruited 3
1 recruited 2
1 recruited 9
3 recruited 4
should not be too hard to put this in whatever layout you wish.
Related
So What Im trying to do is have the user add a code to a form, and fill the form out, A to add to the table, D to delete, U to update... The delete isnt working, neither is the insert, is it my logic? also I want to print the table only once, and sometimes it does it twice... any advice?
$Code=$_POST["Code"];
if ($Code == "A")
{
$sql = "INSERT INTO movieDATA values ('$idno', '$Name', '$Genre', '$Starring', '$Year', '$BoxOffice')";
$result= mysqli_query($link,$sql) or die(mysqli_error($link));
$showresult = mysqli_query($link,"SELECT * from movieDATA") or die("Invalid query: " . mysqli_error($link));
while ($row = mysqli_fetch_array($showresult))
{
echo ("<br> ID = ". $row["IDNO"] . "<br> NAME = " . $row["Name"] . "<br>");
echo("Genre = " . $row["Genre"] . "<br> Starring = " . $row["Starring"] . "<br>");
echo("Year = " . $row["Year"] . "<br> Box Office = " . $row["BoxOffice"] . "<br>");
}
}
elseif ($Code == "D")
{
$sql = "DELETE FROM movieDATA WHERE IDNO = '$idno'";
$result= mysqli_query($link,$sql) or die(mysqli_error($link));
$showresult = mysqli_query($link,"SELECT * from movieDATA") or die("Invalid query: " . mysqli_error($link));
while ($row = mysqli_fetch_array($showresult))
{
echo ("<br> ID = ". $row["IDNO"] . "<br> NAME = " . $row["Name"] . "<br>");
echo("Genre = " . $row["Genre"] . "<br> Starring = " . $row["Starring"] . "<br>");
echo("Year = " . $row["Year"] . "<br> Box Office = " . $row["BoxOffice"] . "<br>");
}
}
elseif ($Code == "U")
{
$sql = "UPDATE movieDATA SET Name = '$Name', Genre = '$Genre', Starring = '$Starring', Year = '$Year', BoxOffice = '$BoxOffice' where IDNO = '$idno'";
$result= mysqli_query($link,$sql) or die(mysqli_error($link));
$showresult = mysqli_query($link,"SELECT * from movieDATA") or die("Invalid query: " . mysqli_error($link));
while ($row = mysqli_fetch_array($showresult))
{
echo ("<br> ID = ". $row["IDNO"] . "<br> NAME = " . $row["Name"] . "<br>");
echo("Genre = " . $row["Genre"] . "<br> Starring = " . $row["Starring"] . "<br>");
echo("Year = " . $row["Year"] . "<br> Box Office = " . $row["BoxOffice"] . "<br>");
}
}
?>
how to use str_replace with $row link
now my link is showing like this
example.com/view.php?category=laptop&model=dell i5
and i want like this
example.com/view.php?category=laptop&model=dell_i5
this is a link code
<a href=\"detail.php?category=" . $row['category'] . "&model=" . $row['model'] ."\" >
so how can i use str_replace with the link " . $row['model'] ."
please help me to solve this issue
Complete code
<?php
//connect to database
mysql_connect('localhost','user','password');
mysql_select_db('newalldata');
$page = (empty($_GET['page'])) ? 1 : $_GET['page'];
$max_results = 6;
$from = (($page * $max_results) - $max_results);
if(empty($_POST)) {
$query = "SELECT * FROM alldata LIMIT $from, $max_results";
}
$result = mysql_query("SET NAMES utf8"); //the main trick
$result = mysql_query($query) or die(mysql_error());
$rows = mysql_num_rows($result);
$count=0;
while($row = mysql_fetch_array($result))
{
if($count%6==0)
{
echo "<tr/>";
echo "<tr>";
}
echo "<td><hr><div class='style99' align='center'><img src='/media/image.php?width=200&height=210&image=/media/" . $row['photo'] . "' title=". $row['price'] ." alt=". $row['model'] ." style='FILTER: alpha(opacity=100);-moz-opacity: 1.0; opacity: 1.0;' onmouseover=BeginOpacity(this,100,40) onmouseout=EndOpacity(this,100)><p><font color='#3366FF'>" . $row['category'] . "</font></p><p><font color='#3366FF'>" . $row['model'] . "</font></p><p><font color='#336600'>" . $row['price'] . "</font></p><div></td>";
$count++;
}
?>
$var = str_replace(" ","_",$row['model']);
<a href=\"detail.php?category=" . $row['category'] . "&model=" . $var ."\" >;
should do it
You may check http://php.net/manual/de/function.str-replace.php
The first parameter is what you search ( in this case the " ") , the second is what u want to heave instead ("_") and then which string is checked.
My table 'viewlevels' has the following data (among other):
id |title
10 |Cenas
I'm running the SQL query:
SELECT title FROM viewlevels WHERE id=10
Which is returning "Cenas" as expected.
But using the following PHP script, I just get "texto= " , why?
$res = $db->query("SELECT title FROM viewlevels WHERE id=10");
$res->data_seek(0);
while ($row = $res->fetch_assoc()) {
echo " texto= " . $row['title'] . "\n";
};
To see both fields you have to echo those columns:
while ($row = $res->fetch_assoc()) {
echo " id= " . $row['id'] . "\n";
echo " texto= " . $row['title'] . "\n";
};
You don't need to use data_seek in this instance.
$res = $db->query("SELECT title FROM viewlevels WHERE id=10");
while ($row = $res->fetch_assoc()) {
echo " texto= " . $row['title'] . "\n";
}
Will work.
i'am working on a social project and we've just startet the registration for members.
Our members could recriute new members, so we have a database where is a field "recruit_by".
The DB fiels looks like this:
id | name | email | code | recruit_by
We now want to generate a list of the structure, who recruited whom on all levels.
I've tried to get this done, but it seems my skills are to less to get this done.
I get a list, but this is totaly unsorted :-(
Thanks for your help!
<?PHP
mysql_connect("www.mysqlserver.net", "database1", "password") or die(mysql_error());
mysql_select_db("project_db1") or die(mysql_error());
echo "<ul>";
$result = mysql_query("SELECT * FROM registration") or die(mysql_error());
while($row = mysql_fetch_array($result))
{
echo "<li class=\"level0\">" . $row['id'] . " - " . $row['name'] . " - " . $row['email'] . " - " . $row['recruit_by'] . "</li>";
// 1. Level
$result2 = mysql_query("SELECT * FROM registration WHERE recruit_by LIKE " . $row['id']) or die(mysql_error());
while($row2 = mysql_fetch_array($result2))
{
echo "<li class=\"level1\">1. " . $row2['id'] . " - " . $row2['name'] . " - " . $row2['email'] . " - " . $row2['recruit_by'] . "</li>";
// 2. Level
$result3 = mysql_query("SELECT * FROM registration WHERE recruit_by LIKE " . $row2['id']) or die(mysql_error());
while($row3 = mysql_fetch_array($result3))
{
echo "<li class=\"level2\">2. " . $row3['id'] . " - " . $row3['name'] . " - " . $row3['email'] . " - " . $row3['recruit_by'] . "</li>";
// 3. Level
$result4 = mysql_query("SELECT * FROM registration WHERE recruit_by LIKE " . $row3['id']) or die(mysql_error());
while($row4 = mysql_fetch_array($result4))
{
echo "<li class=\"level3\">3. " . $row4['id'] . " - " . $row4['name'] . " - " . $row4['email'] . " - " . $row4['recruit_by'] . "</li>";
// 4. Level
$result5 = mysql_query("SELECT * FROM registration WHERE recruit_by LIKE " . $row4['id']) or die(mysql_error());
while($row5 = mysql_fetch_array($result5))
{
echo "<li class=\"level4\">4. " . $row5['id'] . " - " . $row5['name'] . " - " . $row5['email'] . " - " . $row5['recruit_by'] . "</li>";
}
}
}
}
}
echo "</ul>";
?>
First, you are selecting all registrations, that results all the recuited users also.
I would suggest selecting only non-recuited users, assuming recruit_by is NULL, when this user is not recruited:
$result = mysql_query("SELECT * FROM registration WHERE recruit_by IS NULL") or die(mysql_error());
Secondly it is good to structure second level of recruits in another <ul></ul> tags like this:
<ul>
<li>User #1
<ul>
<li>User #103, recruited by user #1</li>
<li>User #142, recruited by user #1</li>
<li>User #93, recruited by user #1
<ul>
<li>User #992, recruited by user #93</li>
</ul>
</li>
</ul>
</li>
</ul>
This already gives you much better structure to work with and you can easily loop it in you PHP code (DRY - don't repeat yourself).
<?php
function createTree($level = 0, $recruiter_id = 0) {
$return = "";
if (!$recruiter_id) {
$results = mysql_query("SELECT * FROM registration WHERE recruit_by IS NULL") or die(mysql_error());
} else {
$results = mysql_query("SELECT * FROM registration WHERE recruit_by LIKE " . $recruiter_id) or die(mysql_error());
}
// Check if there is any recruits at all?
if (pg_num_rows($results) > 0) $return .= "<ul>\n";
else return "";
while ($row = mysql_fetch_array($results)) {
$return .= "<li class=\"level".$level."\">\n";
$return .= $level.". " . $row['id'] . " - " . $row['name'] . " - " . $row['email'] . " - " . $row['recruit_by']."\n";
// Add sub-recruits
$return .= createTree($level+1, $row['id']);
// Finish up the <li>
$return .= "</li>\n";
}
$return .= "</ul>\n";
return $return;
}
?>
I am trying to use json_encode() in a while loop while getting database results. Here is my code:
<?
$database = sqlite_open("thenew.db", 0999, $error);
if(!$database) die($error);
$query = "SELECT * FROM users";
$results = sqlite_query($database, $query);
if(!$results) die("Canot execute query");
while($row = sqlite_fetch_array($results)) {
$data = $row['uid'] . " " . $row['username'] . " " . $row['xPos'] . " " . $row['yPos'];
}
echo json_encode(array("response"=>$data));
sqlite_close($database);
?>
The output of this is
{"response":"lastUserID lastUser lastXPos lastYPos"}
I want it to be...
{"response":["1 Alex 10 12", "2 Fred 27 59", "3 Tom 47 19"]}
etc.
So I want the json_encode() function to put ALL users into the array rather than the last one. How would I do this? Thanks
Try:
<?
$database = sqlite_open("thenew.db", 0999, $error);
if(!$database) die($error);
$query = "SELECT * FROM users";
$results = sqlite_query($database, $query);
if(!$results) die("Canot execute query");
$data = array();
while($row = sqlite_fetch_array($results)) {
$data[] = $row['uid'] . " " . $row['username'] . " " . $row['xPos'] . " " . $row['yPos'];
}
echo json_encode(array("response"=>$data));
sqlite_close($database);
?>
Change this
while($row = sqlite_fetch_array($results)) {
$data = $row['uid'] . " " . $row['username'] . " " . $row['xPos'] . " " . $row['yPos'];
}
to
$data = array();
while($row = sqlite_fetch_array($results)) {
$data[] = $row['uid'] . " " . $row['username'] . " " . $row['xPos'] . " " . $row['yPos'];
}
Push each user to an array:
$data = array();
while($row = sqlite_fetch_array($results)) {
$data[] = $row['uid'] . " " . $row['username'] . " " . $row['xPos'] . " " . $row['yPos'];
}
echo json_encode(array("response"=>$data));