Link only visible for certain users? - php

How would I make a hyperlink from my product table visible for a session user that is subscribed in my user table while a non-subscribed user can not see the link from the product table?
This is the current code I have.
<?php
$db = mysql_connect("localhost", "", "");
mysql_select_db("",$db);
$result = mysql_query("SELECT * FROM inventoryTable",$db);
$query="select * from users where sub = 'yes'";
$id=mysql_query($query);
echo "<TABLE style=\"background-color: #FFFFFF; border: 10px solid A4A4A4;\">";
echo"<TR><TD><B>Title</B>
<TD><B>Authors First Name</B>
<TD><B>Authors Last Name</B>
<TD><B>ISBN</B><TD>
<B>Publisher</B>
<TD><B>Course Number</B>
<TD><B>Source</B></TR>";
while ($myrow = mysql_fetch_array($result))
{
echo "<TR><TD>".$myrow["title"].
"<TD>".$myrow["authorsFirst"].
"<TD>".$myrow["authorsLast"].
"<TD>".$myrow["ISBN"].
"<TD>".$myrow["publisher"].
"<TD>".$myrow["courseNum"];
If($_SESSION['username']== '$id')
{"<td>".$myrow["source"];
} else {
echo "<TD>"."Please subscribe to View";
}
echo "</TABLE>";
}
?>
My if statement is always returning false. I am wanting the users from my user table that have a 'yes' in their sub field to be able to view the source field from my inventoryTable.

If($_SESSION[username]== subscribed Id or name){ $myrow["link"]}else{blank }

Related

If a users user group has the same name as a usergroup in the usergroup database, then display color

So basically I have a user group system on my site, where you can assign certain groups to different users. Right now, it's half working. The issue is that only one user group at a time is being used.
As you can see
I want every user with a user group to have their user groups color shown, but right now it's not doing that.
Here is my code:
if ($result = $mysqli->query("SELECT `id`, `name`,`color1`,`color2` FROM `usergroup`")) {
while ($row = mysqli_fetch_assoc($result)) {
$userfromdb = $row["name"];
$color1 = $row["color1"];
$color2 = $row["color2"];
}
}
Later down the line, I have the code that makes a user with a user group its color
<span style="background: #ffffff;background: url('/assets/img/textparticle.gif'), linear-gradient(to right, <?php if ($usergroup === $userfromdb) { echo $color1; } ?> 0%, <?php if ($usergroup === $userfromdb) { echo $color2; } ?> 100%);-webkit-background-clip: text;-webkit-text-fill-color: transparent;font-weight:700;<?php if ($usergroup === $userfromdb) { echo "text-shadow: 0px 0px 10px #32a852"; } ?>">
Here is what the usergroup database looks like
Here is what the account database looks like
I think what you are trying to do is this. Use the usergroup variable to select only one row. It is also faster than fetching all users and iterating through them.
if ($result = $mysqli->query("SELECT `id`, `name`,`color1`,`color2` FROM `usergroup` where `name`='$usergroup`")) {
while ($row = mysqli_fetch_assoc($result)) {
$userfromdb = $row["name"];
$color1 = $row["color1"];
$color2 = $row["color2"];
}
}

Turn PHP MySQL query output into variable

I have a problem that is giving me a headache. I'm fairly new to PHP and MySQL interacting, and coding in general (about 3 months since I first dived into it), so I'm still learning the ropes, so to speak.
The thing is, I have a page that receives data through $_POST from another. All is fine for well. The page receives the data, which is an ID number, and echoes the item's characteristics available in the database corresponding to that ID.
This part of the code works just fine.
$sql = "SELECT nome, preco, `status` FROM produtos WHERE id = $_POST[id]";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_assoc($result)){
echo "Nome: "."<span style='color: red;'>".$row["nome"].
"</span>".
"<br>"."Preço: "."<span style='color: red;'>".
"R$".$row["preco"]."</span>"."<br><br>".$row["status"];
}
}
What I want, is to turn the values echoed into variables, so that I can set them as default value in another form and send that one to another page. Apparently, $row['nome'], for example, isn't available for re-use outside of the instance above.
<form method="post" action="?p=venda">
<input type="text" name="nome" value="<?php echo $row["nome"]; ?>">
<input type="text" name="preco" value="<?php echo $row["preco"]; ?>">
<input type="submit" name="change" value="Efetuar">
</form>
I know this code is prone to SQL injection, but I'm not looking into it right now. This will be a sort of offline program to help me with organizing some of my stuff, so, for now, I don't have to worry about security (not that I'll keep ignoring these issues).
Thanks in advance.
Assign $row to a variable and treat it as an array() outside the while loop.
$sql = "SELECT nome, preco, `status` FROM produtos WHERE id = $_POST[id]";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_assoc($result)){
$array = $row; // assign $row a variable.
echo "Nome: "."<span style='color: red;'>".$row["nome"].
"</span>".
"<br>"."Preço: "."<span style='color: red;'>".
"R$".$row["preco"]."</span>"."<br><br>".$row["status"];
}
}
// example
echo($array['nome']);
OK I'll tell you this, its actually unnecessary to sanitize every post. Its only necessary if your authenticated users are web users and there is a blank that they type code in.
In closed production environments, where your users are, you can safe guard the environment in several ways, but this is off topic here.
anyways, you have a DB chart that has a an Id column, the item name, and I am guessing stock or production status.
your display, I don't use spans, but I'll show you how I do it with tables.
So lets make your query for your colums: nome, preco, status
Here are the two methods, the first one is called looped result method which is mostly used for more than one row in the db table:
<?php
//load it in a variable and trim the outside spaces away if you are entering this from a blank form
$id=trim($_POST[id]);
///this should look familiar to you
$sql = "SELECT nome, preco, status FROM produtos WHERE id ='".$id."'";
///but I use the shorthand method here to get my results.
$result = $conn->query($sql);
///Now we loop and shift colum information into variables
/// in a incremental loop, the colums are numbered starting with 0
echo "<table align=center bgcolor=fff2e2 border=1>\n";
while ($data = $result->fetch_row()) {
////I print my table header, and start the data row, if I want it as several ids I will reset here too (which I will do here if you want to play with this)
echo '<tr><th>Nome</th><th>Preco</th><th>Status</th></tr>';
echo '<tr>';
for ($m=0; $m<$result->field_count; $m++) {
if ($m==0){
$nome='';
$nome=$data[$m];
echo '<td bgcolor="#ff0000">'.$nome.'</td>';
} else if ($m==1){
$preco='';
$preco=$data[$m];
echo '<td bgcolor="#ff0000">'.$preco.'</td>';
}else if ($m==2){
$status='';
$status=$data[$m];
echo '<td bgcolor="#ffffff">'.$status.'</td>';
}
}
//////now if I was building a query chart with submit to another I would put my form and my hidden inputs here before i close the table row with /tr, and my submit button would be my first cell value
echo "</tr>";
}
echo "</table>";
You could do the regular colum /row method since it is one ID, which would look like this I used the span format here so you can get the idea of how html is typically expressed in php:
$id=trim($_POST[id]);
$sql = "SELECT nome, preco, status FROM produtos WHERE id ='".$id."'";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
$nome=stripslashes($row['nome']);
$preco=stripslashes($row['preco']);
$status=stripslashes($row['status']);
echo 'Nome: <span style="color: red;">'.$nome.'</span><br>Preço: <span style="color: red;">'.$preco.'</span><br><br>'.$status;
///notice my quote usage above
here is my table example if I was going to list the whole db table in a scrollable list, and submit it to a file called detail.php
<?php
$sql = "SELECT nome, preco, status FROM produtos";
$result = $conn->query($sql);
echo "<table align=center bgcolor=e3fab5 ><td>";
echo '<div style="width: 500px; height: 450px; overflow: auto; border 5px dashed black; background color: #ccc;">';
echo "<table align=center bgcolor=fff2e2 border=1>\n";
while ($data = $result->fetch_row()) {
echo '<tr><th>Nome</th><th>Preco</th><th>Status</th></tr>';
echo '<tr>';
for ($m=0; $m<$result->field_count; $m++) {
if ($m==0){
$nome='';
$nome=$data[$m];
echo '<td bgcolor="#ff0000"><form action="detail.php" method="post"><input type="submit" name="id" value="'.$nome.'"></td>';
} else if ($m==1){
$preco='';
$preco=$data[$m];
echo '<td bgcolor="#ff0000">'.$preco.'<input type="hidden" name="preco" value="'.$preco.'"></td>';
}else if ($m==2){
$status='';
$status=$data[$m];
echo '<td bgcolor="#ffffff">'.$status.'<input type="hidden" name="status" value="'.$status.'"></td>';
}
}
echo "</form></tr>";
}
echo "</table>";
echo "</div></table>";
?>

mysql fetch array is not showing result

So I have been working on this code for a while. I believe I am really close. My if statement that is inside my while loop isn't showing any data in the area it's suppose to show. I know mysql is old and deprecated. I am going to change it once I figure this out.
$result = mysql_query("SELECT * FROM inventoryTable",$db);
$result2 = mysql_query("SELECT * FROM users WHERE username='$username' and sub = 'yes'",$db);
echo "<TABLE style=\"background-color: #FFFFFF; border: 10px solid A4A4A4;\">";
echo"<TR><TD>"."<B>Title</B>"."</td>";
echo"<TD>"."<B>Authors First Name</B>"."</td>";
echo"<TD>"."<B>Authors Last Name</B>"."</td>";
echo"<TD>"."<B>ISBN</B>"."</td>";
echo"<TD>"."<B>Publisher</B>"."</td>";
echo"<TD>"."<B>Course Number</B>"."</td>";
echo"<TD>"."<B>Source</B>"."</td></TR>";
while ($myrow = mysql_fetch_array($result))
{
echo "<TR><TD>".$myrow["title"]."</td>";
echo "<TD>".$myrow["authorsFirst"]."</td>";
echo"<TD>".$myrow["authorsLast"]."</td>";
echo "<TD>".$myrow["ISBN"]."</td>";
echo "<TD>".$myrow["publisher"]."</td>";
echo "<TD>".$myrow["courseNum"]."</td>";
while ($subResults = mysql_fetch_row($result2))
{
If($subResults == 'yes' )
{
echo "<td>".$myrow["source"]."</td>";
} else {
echo "<TD>"."Please subscribe to View"."</td>";
}
echo "</TABLE>";
}
}
?>
This is the part of my code that isn't showing any results.
while
while ($myrow = mysql_fetch_array($result))
{
echo "<TR><TD>".$myrow["title"]."</td>";
echo "<TD>".$myrow["authorsFirst"]."</td>";
echo"<TD>".$myrow["authorsLast"]."</td>";
echo "<TD>".$myrow["ISBN"]."</td>";
echo "<TD>".$myrow["publisher"]."</td>";
echo "<TD>".$myrow["courseNum"]."</td>";
while ($subResults = mysql_fetch_row($result2))
{
If($subResults == 'yes' )
{
echo "<td>".$myrow["source"]."</td>";
} else {
echo "<TD>"."Please subscribe to View"."</td>";
}
echo "</TABLE>";
}
}
I want my session user to be able to see the source from my inventory table if they have a yes in the sub field. If they do not have a yes in the sub field, they will see please subscribe to view. Am i doing the mysql_fetch incorrectly or is there a problem because I have 2 while loops going on at once.
you need to have "==" to compare two values, otherwise you assign the second value to the first variable:
...If($username == $subResults)...
or to use a strict comparison of type and content, use "==="
If($username === $subResults)
also I am thinking the code should be
...If($subResults ==="yes"){echo"....///desired content";}else{echo"...//alternate content";}...
and you are missing the echo statement and closing </td> in the code
"<td>".$myrow["source"];
should be
echo"<td>".$myrow["source"]."</td>";
in fact - aren't you missing the closing td's in all of the cells?

allowing just friends to comments in their profile page

i have a profile page that contain a comment system and i just allow the owner of the profile to write their comments now i want to allow friends also to write how to do that ???
in the members table i have a friend_array field that contain the ids of users that are friend with this user
the friend request system include ajax and jquery
code.php
$blab_form="";
if(isset($_SESSION['user_id']))
{
if($_SESSION['user_id']==$id)
{
$blab_form='
'.$blab_output_msg.'<br />
<div style="background-color:#D2F0D3;border:#999 1px solid; padding:8px;">
<form action="profile.php" method="post" enctype="multipart/form-data" name="blab_form">
<textarea name="blab_field" cols="" rows="4" style="width:100%;">
</textarea><br />
(220 Char Max)
<input type="submit" name="submit" value="Blab"/>
</form></div>';
//$sql = mysql_query("DELETE FROM blabing WHERE u_id ='$id'")or die(mysql_error());
}
}
friend_request_system
<?php
//****************friend request system********************//
// for securing the request with and encryption to be more secure.
if(isset($_SESSION['wpit']))
{
$_SESSION['wipt'];
}
$theRundomNum = rand(99999999999999,9999999999999);
$_SESSION['wipt'] = base64_encode($theRundomNum);
//*********for distinguich the users*************//
//if member is a viewer
$friendLink = "";
if(isset($_SESSION['user_id'])&&$_SESSION['user_id']!=$id)
{
//for quering friend array for the viewer if he is not the owner
$sqlArray = mysql_query("SELECT friend_array FROM members WHERE user_id ='".$_SESSION['user_id']."' LIMIT 1")or die(mysql_error());
while($row = mysql_fetch_array($sqlArray))
{
$iFriendArray = $row['friend_array'];
}
$iFriendArray = explode("," , $iFriendArray);
if(in_array($id, $iFriendArray))
{
$friendLink = 'Remove Friend';
}
else
{
$friendLink = 'Add as Friend';
}
$interactionBox='<div class="interactionLinksDiv">
'.$friendLink.'
</div>';
}
//if member is the profile ower
else
{
$interactionBox = '<div class="interactionLinksDiv">
Freind Request List </div>';
}
?>
if($_SESSION['user_id']==$id) is specific to the blog owner, right? So you make this conditional check if the session id is in an array of acceptable id's. Something like this:
// assuming you already populated the $iFriendArray as outlined in your question
$iFriendArray[] = $id; // add blog owner to the friend array
if(in_array($_SESSION['user_id'], $iFriendArray))
{
// can comment
}
This has been updated to use the friend array as updated in your question.
Any questions feel free to ask and I may update.

list onclick event problem in php

I'm trying to display the new dynamic list by clicking dynamic list. Why do i call them dynamic list? Because the data is from database.
My idea is generating a list of companies, when i click one company, a list of all sites in the company is displayed; And then when i click the one site of one company, a list of all employees in the site is displayed.
Now i have met a problem. When i click any item in list of companies, a list of sites in the last item of company list shows. And when i click any item in the list of sites, a list of employees of last item in sites is showed.
Do you know why?
Here is the code and result image:
<script language="JavaScript">
function toggle(id,id2,id3) {
var state = document.getElementById(id).style.display;
if (state == 'block') {
document.getElementById(id).style.display = 'none';
if (id2 != undefined)document.getElementById(id2).style.display = 'none';
if (id3 != undefined)document.getElementById(id3).style.display = 'none';
} else {
document.getElementById(id).style.display = 'block';
}
}
</script>
<style type="text/css">
#main{
position:relative;
top:20px;
left:20px;
width:200px;
background: lightblue;
}
#hidden {
position:relative;
top:5px;
left:280px;
width:200px;
background: lightgrey;
display: none;
}
#hidden2 {
position:relative;
top:-12px;
left:580px;
width:200px;
background: lightgreen;
display: none;
}
#hidden3 {
position:relative;
top:100px;
left:20px;
width:200px;
background: lightpink;
display: none;
}
</style>
<?php
error_reporting(E_ALL ^ E_NOTICE);
include("./conn/connect.php");
$query = "SELECT * FROM entreprise ORDER BY id";
$result = mysql_query($query) or die("result failed: ".mysql_error());
?>
<div id="main" >
<?php
echo "<ul>";
while($row = mysql_fetch_assoc($result)){
echo "<li onclick=\"toggle('hidden','hidden2','hidden3');\">".$row['name'].'<li>';
$query2 = "SELECT * FROM site WHERE eid = '".$row['id']."'";
//$query2 = "SELECT * FROM site WHERE eid = ".$row['id'];
//$result2 = mysql_query($query2) or die("query2 result error".mysql_error());
$result2 = mysql_query($query2) or die("query2 result error".mysql_error());
}
echo "</ul>";
?>
</div>
<div id="hidden" >
<?php
echo "<ul>";
while($row2 = mysql_fetch_assoc($result2)){
echo "<li onclick=\"toggle('hidden2','hidden3')\">".$row2['name'].'< >';
$query3 = "SELECT * FROM salarie WHERE siteid =".$row2['id'];
//echo $query3;
$result3 = mysql_query($query3) or die("query3 result error".mysql_error());
}
echo "</ul>";
?>
</div>
<div id="hidden2" >
<?php
echo "<ul>";
while($row3 = mysql_fetch_assoc($result3)){
echo "<li onclick=\"toggle('hidden3')\">".$row3['prenom'].'< >';
$query4 = "SELECT * FROM salarie WHERE id =".$row3['id'];
$result4 = mysql_query($query4) or die("query4 result error".mysql_error());
}
echo "</ul>";
?>
</div>
<div id="hidden3">
<?php
echo "<table>";
while($row4 = mysql_fetch_assoc($result4)){
echo "<tr><td>".$row4['prenom'].'</td>';
echo "<td>".$row4['nom'].'</td></tr>';
}
echo "</table>";
?>
</div>
Result image:
Pretty simple: Your PHP code is executed ONCE when you access the site.
So for example the result of this block
while($row = mysql_fetch_assoc($result)){
echo "<li onclick=\"toggle('hidden','hidden2','hidden3');\">".$row['name'].'<li>';
$query2 = "SELECT * FROM site WHERE eid = '".$row['id']."'";
//$query2 = "SELECT * FROM site WHERE eid = ".$row['id'];
//$result2 = mysql_query($query2) or die("query2 result error".mysql_error());
$result2 = mysql_query($query2) or die("query2 result error".mysql_error());
}
is that $result2 holds all the sites of the last company in your list. This is then used in the next loop to generate the corresponding list of sites. Look at the source of the generated HTML file.
PHP is a server side language, the code is executed at the server and it is not re-executed by your Javascript functions (i.e. not executed in the browser).
What you are after is dynamically loading the data from your server with AJAX and pass into the generated HTML.
Edit:
You could also do it without Ajax: Rewrite your PHP like this:
$sitequeries = array()
while($row = mysql_fetch_assoc($result)){
echo "<li onclick=\"showSites('sites_$row['id']');\">".$row['name'].'<li>';
$query = "SELECT * FROM site WHERE eid = '".$row['id']."'";
$sitequeries[$row['id']] = mysql_query($query2 or die("query2 result error".mysql_error());
}
and
<?php
foreach($sitequeries as $id => $query) {
echo "<ul class='sites' id='sites_$id'>";
while($row2 = mysql_fetch_assoc($query)){
//...
}
echo "</ul>";
}
?>
This is not a working example but should give you the right idea. You have to adjust your JS accordingly to show only the corresponding lists, e.g.:
function showSites(id) {
// Hide all lists with class 'site' here and only display the list with id 'id' e.g. 'sites_5'
}
But note that this is not a good solution if you have a lot of companies, site, employes, etc. as the generation of the HTML may take a while. Then Ajax is a better choice.
Your toggle() Function needs 3 Parameters
You set on some places just 2 parameters
echo "<li onclick=\"toggle('hidden2','hidden3')\">".$row2['name'].'< >';
Shoud be
echo "<li onclick=\"toggle('hidden1','hidden2','hidden3')\">".$row2['name'].'< >';
I would do some things about your code:
Split the data acquiring stuff from the rest. At the beginning, get the data from the required tables and keep it in PHP variables. Then, do something with them using a JS framework... something according to your requirements
The problem with your approach is that you are NEVER telling anyone which row's ID should be sent... hence, it sends the id from the row selected by default, which happens to be the last one parsed by HTML parser on the browser. It means, the last one...
Your PHP code does not match your goal. $result2 will always be the last ID found in $result1, and so on.
If you need to generate result2 based on what the user selects in result1, then you need to either create rows for every possible selection then use javascript to show or hide, or utilize Ajax calls (much better).
Might wanna look into JQuery instead of doing it the way you currently are. But streetparade is correct.
Your approach to this task is a bit wrong, I think.
What do you do in the first loop? You setting $result2 variable and you want to access it in the next loop. And in next loop $result2 is set to the last record of first loop.
Have you heard about AJAX? jQuery may be?

Categories