How to match one ID from Multiple ID's? - php

I have this script below where it scans users that are allowed to see a post. How do i update it so that it will match the person viewing's ID to the one stored in the field. If it matches it works else it doesn't. The stored entries will be something like 99394david, 324234smith, 34343jane. So this script i have is not matching it.
$kit = mysql_real_escape_string($_GET['id']);
$sql="SELECT `Who_can_see` from `posts` where `post_id` = '$kit'";
$result=mysql_query($sql);
$query = mysql_query($sql) or die ("Error: ".mysql_error());
if ($result == "")
{
echo "";
}
echo "";
$rows = mysql_num_rows($result);
if($rows == 0)
{
print("");
}
elseif($rows > 0)
{
while($row = mysql_fetch_array($query))
{
$userallowed = htmlspecialchars($row['who_can_see']);
}
}
//$personid is drawn from the database. its the id of the
person viewing the link.
if ( $userallowed == $personid ) {
echo("allowed");
} else {
echo("not allowed");
die();
}
?>

I would simply add the $personid to the query (although I have doubts about how you are filling your posts table exactly...):
$sql="SELECT `Who_can_see` from `posts`
where `post_id` = '$kit'
AND `Who_can_see` = '$personid'";
If your result contains a row, the user is allowed to view the post.
By the way, I would also recommend using prepared statements to avoid any potential sql injection problems.
Edit: Based on the fact that Who_can_see can contain a comma separated list of entries, you can use your original script, and just change how you match, using for example stripos.
if ( stripos($userallowed, $personid) !== false ) {
// $personid is found in $userallowed
echo("allowed");
} else {
echo("not allowed");
die();
}

Related

Show alert message if MySQL php query match one condition [duplicate]

This question already has answers here:
How to pop an alert message box using PHP?
(9 answers)
Closed 1 year ago.
I have an online software that use php, html, js and MySQL as database.
I have two tables:
1- First table contains [name, imei, object_expire, object_expire_dt] - gs_objects
2- Second table contains [object_id, user_id, imei] - gs_user_objects
The code should be done in php where the user_id is got from the session, then the first query should get the imeis that matches the user_id from second table then it should get the expire date 'object_expire_dt' of each imei from the first table
after that it should check if there is an expire date that will expire within 20 days, if true, it should show alert message
Here is incomplete code that I tried to do
//notification for objects expiration
checkUserSession();
loadLanguage($_SESSION["language"], $_SESSION["units"]);
// check privileges
if ($_SESSION["privileges"] == 'subuser')
{
$user_id = $_SESSION["manager_id"];
}
else
{
$user_id = $_SESSION["user_id"];
}
$q = "SELECT * FROM `gs_user_objects` WHERE `user_id`='".$user_id."' ORDER BY `object_id` ASC";
$r = mysqli_query($ms, $q);
while($row=mysqli_fetch_array($r))
{
$q2 = "SELECT * FROM `gs_objects` WHERE `imei`='".$row['imei']."' ORDER BY `object_id` ASC";
$r2 = mysqli_query($ms, $q2);
while($row=mysqli_fetch_array($r2))
{
$Date_e = date("Y-m-d");
if ( $row['object_expire_dt'] > date('Y-m-d', strtotime($Date_e. ' - 20 days')))
{
alert("You have objects are going to expire soon");
}
}
}
the code didn't work, I need some help in it.
Thanks in advance
Here's how all this works: Your php program runs on your server, and accesses your database on the server. The purpose of your php program is to create programs to run on your users' browsers. Those programs written by php use the HTML, Javascript, and CSS languages.
If you want something to happen in a user's browser (like an alert box) that thing has to appear in a Javascript program written by your php program and sent to the browser. php doesn't have its own alert() function
Here's an easy, but somewhat sloppy, way to do that in your php program.
echo "<script type='text/javascript'>window.onload=function(){alert('$msg'))</script>";
What's going on here?
echo tells php to write its parameter to the html page
<script> whatever </script> is the way to embed Javascript in html
window.onload = function () { whatever } tells the browser to run a Javascript function when your html page finishes loading.
alert(message), in the function, pops up the alert message.
When you're troubleshooting this kind of thing, View Source ... is your friend.
you can use alert in javascript not in php
also you should use prepared statement.
//notification for objects expiration
checkUserSession();
loadLanguage($_SESSION["language"], $_SESSION["units"]);
// check privileges
if ($_SESSION["privileges"] == 'subuser'){
$user_id = $_SESSION["manager_id"];
}else{
$user_id = $_SESSION["user_id"];
}
$q = "SELECT * FROM gs_user_objects WHERE user_id = ? ORDER BY object_id ASC";
if ($r = $connection->prepare($q)) {
// if user_id contains string and is not integer you must use "s"
$r->bind_param("i",$user_id);
if ($r->execute()) {
$result = $r->get_result();
// check if result match one condition
if ($result->num_rows > 0) {
echo "result found";
while ($row = $result->fetch_assoc()) {
echo $row['some_column_name'];
}
}
}
}
Thanks Nikolaishvili and Jones,
Your answers helped me a lot I needed more edit on the if statements,
I did the code and the result is as I expected and it is online now, here the code is below so others can check it
//notification for objects expiration
// check privileges
if ($_SESSION["privileges"] == 'subuser')
{
$user_id = $_SESSION["manager_id"];
}
else
{
$user_id = $_SESSION["user_id"];
}
$q = "SELECT * FROM `gs_user_objects` WHERE `user_id`='".$user_id."' ORDER BY `object_id` ASC";
$r = mysqli_query($ms, $q);
$expiry_flag = 0;
$inactive_flag=0;
while($row=mysqli_fetch_array($r))
{
$q2 = "SELECT * FROM `gs_objects` WHERE `imei`='".$row['imei']."'";
$r2 = mysqli_query($ms, $q2);
while($row2=mysqli_fetch_array($r2))
{
$Date_e = date("Y-m-d");
if ( $row2['object_expire_dt'] < date('Y-m-d', strtotime($Date_e. ' + 20 days')))
{
if ($row2['object_expire_dt'] > '0000-00-00')
{
$expiry_flag = 1;
}
}
if ( $row2['object_expire_dt'] < date("Y-m-d"))
{
if ($row2['object_expire_dt'] > '0000-00-00')
{
$inactive_flag = 1;
}
}
}
}
if ($expiry_flag == 1)
{
echo '<script type="text/javascript">';
echo ' alert("my msg1")';
echo '</script>';
}
if ($inactive_flag == 1)
{
echo '<script type="text/javascript">';
echo ' alert("my msg2")';
echo '</script>';
}
Thanks

Fetching data from two MySQL tables simlutenously with PHP + AJAX

I'm creating a search box that queries two MySQL tables and lists the results in real time. For now though, I have a working prototype that will query only one table. I've written the following PHP code in conjunction with JQuery and it works wonderfully:
HTML
<input onkeyup="search(this);" type="text">
<ol id="search-results-container"></ol>
Javascript
function search(input) {
var inputQuery = input.value;
/* $() creates a JQuery selector object, so we can use its html() method */
var resultsList = $(document.getElementById("search-results-container"));
//Check if string is empty
if (inputQuery.length > 0) {
$.get("search-query.php", {query: inputQuery}).done(function(data) {
//Show results in HTML document
resultsList.html(data);
});
}
else { //String query is empty
resultList.empty();
}
}
and PHP
<?php
include("config.php"); //database link
if(isset($_REQUEST["query"])) {
$sql = "SELECT * FROM students WHERE lastname LIKE ? LIMIT 5";
/* Creates $stmt and checks if mysqli_prepare is true */
if ($stmt = mysqli_prepare($link, $sql)) {
//Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "s", $param_query);
//set parameters
$param_query = $_REQUEST["query"] . '%';
//Try and execute the prepared statement
if (mysqli_stmt_execute($stmt)) {
$result = mysqli_stmt_get_result($stmt);
//get number of rows
$count = mysqli_num_rows($result);
if ($count > 0) {
//Fetch result rows as assoc array
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
echo "<h1>Students:</h1>"; //Header indicates student list
for ($i = 0; $i < $count; $i++) {
$name = $row["lastname"];
echo "<p>$name</p>";
}
}
else { //Count == 0
echo "No matches found.<br>";
}
}
else { //Execution of preped statement failed.
echo "Could not execute MySQL query.<br>";
}
} // end mysqli_prepare
} // end $_RESQUEST isset
?>
The details of the students table are arbitrary, except for the fact that it has a String column that lists the student's last name.
My problem is that there is also a staff table which is effectively the same as students but for a different purpose. I'd like to query the staff table at the same time as students, but have the results separated like so:
<h1>Students:</h1>
<p>Student1</p>
<p>Student2</p>
<h1>Staff</h1>
<p>Staff1</p>
<p>Staff2</p>
The obvious answer would be to add another $sql statement similar to the one on Line 5 and just do both queries serially - effectively doubling the search time - but I'm concerned this will take too long. Is this a false assumption (that there will be a noticeable time difference), or is there actually a way to do both queries alongside each other? Thanks in advance!
If the two tables have identical structures, or if there is a subset of columns which could be made to be the same, then a UNION query might work here:
SELECT *, 0 AS type FROM students WHERE lastname LIKE ?
UNION ALL
SELECT *, 1 FROM staff WHERE lastname LIKE ?
ORDER BY type;
I removed the LIMIT clause because you don't have an ORDER BY clause, which makes using LIMIT fairly meaningless.
Note that I introduced a computed column type which the result set, when ordered by it, would place students before staff. Then, in your PHP code, you would just need a bit of logic to display the header for students and staff:
$count = mysqli_num_rows($result);
$type = -1;
while ($count > 0) {
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
$curr_type = $row["type"];
if ($type == -1) {
echo "<h1>Students:</h1>";
$type = 0;
}
else if ($type == 0 && $curr_type == 1) {
echo "<h1>Staff:</h1>";
$type = 1;
}
$name = $row["lastname"];
echo "<p>$name</p>";
--$count;
}

While loop and if statement not recognizing Database input correctly

Have the following php query:
if ($result = mysqli_query($conn, "SELECT scholarship1, scholarship2, scholarship3, scholarship4, scholarship5, scholarship6, scholarship7, scholarship8, scholarship9, scholarship10, date1, date2, date3, date4, date4, date5, date6, date7, date8, date9, date10 FROM scholarships")) {
$row_cnt = mysqli_num_rows($result);
if (($row_cnt) > 0) {
while(mysqli_fetch_assoc($result)) {
if ((['scholarship4'] == null) AND (['scholarship3'] != null)) {
echo "YES";
}
else {
echo "NO";
}
}
}
}
Connection to the database was successful.
$row_cnt > 0 recognizing data in database.
My if statement returns "NO" when 'scholarship4' is clearly NULL and 'scholarship3' clearly has data.
I essentially copied this code from another of my pages that was working properly, so I am flabbergasted as to what is going on here.
One thing I did remove was while($row = ...) since the original data input was not of the 'select' variety. Also, please keep in mind, this is just testing the if statement initially, whereas many if statements are currently hidden from the loop.
Please let me know if more information is needed. Thanks for any and all help.
When you fetch the data, you need to store it and then reference this array in your test...
while($row = mysqli_fetch_assoc($result)) {
if (($row['scholarship4'] == null) AND ($row['scholarship3'] != null)) {

adding further conditions to mysql loop

<?php
$query = $_GET['query'];
// gets value sent over search form
$min_length = 6;
// you can set minimum length of the query if you want
if(strlen($query) >= $min_length){ // if query length is more or equal minimum length then
$query = htmlspecialchars($query);
// changes characters used in html to their equivalents, for example: < to >
$query = mysql_real_escape_string($query);
// makes sure nobody uses SQL injection
$raw_results = mysql_query("SELECT * FROM cwnational WHERE (`postcode` = '$query') OR (`structure` LIKE '%".$query."%')") or die(mysql_error());
if(mysql_num_rows($raw_results) > 0){ // if one or more rows are returned do following
while($results = mysql_fetch_array($raw_results)){
echo "<p><h3>".$results['postcode']."</h3>".$results['structure']."</p>";
}
while($results = mysql_fetch_array($raw_results)){
if($results['structure'] = "National") {
echo "print national_table";
} else {
echo "print local_table";
}
}
else{ // if there is no matching rows do following
echo "No results";
}
}
else{ // if query length is less than minimum
echo "Minimum length is ".$min_length;
}
?>
</body>
I'm totally stumped now..
When I successfully match a $query, I want to use the 2nd part of the array which should be a column called structure and use that as a switch to either print table_local or table_national from the db.
re-wrote it after getting to grips with the correct approach,
if (empty($searchTerm)) {
echo "<h1>Empty search term</h1>";
$sqlQuery = false;
} elseif (strlen($searchTerm) < $minQueryLength) {
echo "<h1>Search term must be at least ".$minQueryLength." characters long.";
$sqlQuery = false;
} else {
if (strlen($firstPart) + strlen($secondPart) == 7) {
$sqlQuery = $mysqli->query("SELECT `postcode`, `structure` FROM `cwnational` WHERE `postcode` LIKE '".$firstPart." ".$secondPart."'");
} else {
$sqlQuery = $mysqli->query("SELECT `postcode`, `structure` FROM `cwnational` WHERE REPLACE(`postcode`, ' ', '') LIKE '".$searchTerm."%'");
}
}
if (is_object($sqlQuery) && $sqlQuery->num_rows >= 1) {
$resultArr = array();
while($row = $sqlQuery->fetch_assoc()) {
$resultArr[$row['postcode']] = array();
$priceQuery = $mysqli->query("SELECT `base_rate`, `commit_mbps` FROM `pricing` WHERE `structure` = '".$row['structure']."'");
if ($priceQuery->num_rows >= 1) {
while ($price = $priceQuery->fetch_assoc()) {
$resultArr[$row['postcode']][$price['commit_mbps']] = ((float)$price['base_rate'] + $transit[$price['commit_mbps']] ) + ( ( $transit[$price['commit_mbps']] + (float)$price['base_rate'] ) * ((float)$apiUser['margin']/100) ) ;
}
}
}
You're reading the result set twice. This will work for the first loop, but won't execute the second because you've already reached the end. If you need to read the results twice, use this:
mysql_data_seek ($raw_results , 0 )
immediately before the second loop to set the pointer to the beginning again.
Of course, you should be using mysqli...
what's going wrong now? I see you need to add an equals sign here:
if($results['structure'] == "National") {
note: double equals for php conditional
It also looks like you have an "else" coming out of a "while", that won't work. And you did this "while" loop twice, I'd combine them into a single "While":
while($results = mysql_fetch_array($raw_results)){

Mystified about making a PHP double-query dynamic list work. Using PHP 5.3.5

I'm trying to create a dynamic list (5 row results) in php by first getting data from one table then using a resulting var to get the latest uploaded "image_links" (just 1 from each of the 5 artists) from another table -- then echo out.
The code here gives me the only one row with the latest image. When I comment out the "// get the latest image link uploaded ///" section of the code I get the 5 rows of different artists I really want but, of course, w/o images. I tried (among a bunch of things) mysql_result() w/o the while statement but that didn't work.
So what am I missing?
Thanks
Allen
//// first get the artists followed ////////////////
$QUERY= "SELECT * FROM followArtist WHERE user_id = $user_id ";
$res = mysql_query($QUERY);
$num = mysql_num_rows($res);
if($num>0){
while($row = mysql_fetch_array($res)){
$artist_name = $row['artist_name'];
$artist_id = $row['artist_id'];
$date_lastSent = $row['date_lastSent'];
$date_artPosted = $row['date_artPosted'];
$date_notePosted = $row['date_notePosted'];
//// get new notice data /////
if ($date_artPosted >= $date_lastSent) {
$artp = "new artwork posted";
}else{
$artp = "";
}
if ($date_notePosted >= $date_lastSent) {
$notep = "news/announcement posted";
}else{
$notep = "";
}
if ($artp!="" && $notep!="") {
$and = " and<br />";
}else{
$and = "";
}
if ($artp=="" && $notep=="") {
$no = "No new images or news posted since your<br /> last visit, but we'll let you know when there is.";
}else{
$no = "";
}
//////// get the latest image link uploaded ////////////////////////////////////
$QUERY2="SELECT image_link FROM artWork WHERE artist_id ='$artist_id' AND make_avail = '1' ";
//ORDER BY date_submit DESC
$res = mysql_query($QUERY2);
$num = mysql_num_rows($res);
if($num>0 ){
while($row = mysql_fetch_assoc($res)){
mysql_fetch_assoc($res);
$image_link= $row['image_link'];
}
//////// end of get the latest images uploaded ////////////////////////////////
echo "<tr align=\"center\" height=\"115px\">
<td align=\"left\" width=\"15%\"> <a href=\"process_artist_idImages.php?artist_id=$artist_id&search=search\">
<img src=slir/w115-h115/$path$image_link /></a></td>
<td align=\"center\" width=\"80%\"
<span class=\"deviceMedLtGrayFont\">$artist_name</span>
<br /><br />
<a href=\"process_artist_idImages.php?artist_id=$artist_id&search=search\"/>
$artp</a>
<a href=\"process_artist_idImages.php?artist_id=$artist_id&search=search\"/>
$and$no</a>
<a href=\"process_artist_idImages.php?artist_id=$artist_id&search=search\"/>
$notep</a>
</td>
</tr>";
} //// end bracket for getting latest image link
} ///loop end for getting followed artist data
} ///end: if ($num>0) clause<code>
If I read your code correctly, I see you looping using data from query1 in the control structure, and a lookup on query2 within each loop. You are reusing the variables in your loop1 control structure for query2 ($num and the query handle ($res)) for the second loop. Probably not desirable within the loop.
You're sharing the variables $num and $res between the two queries ... your original properties will be overwritten when the second query is run. Use different property names for the inner query.
Example of problem:
$result = QueryA();
while( $row = $result->getRow() )
{
// -- You're overwriting the original result here ...
$result = QueryB();
// Next time the loop runs, it will run using the result from QueryB();
}
So change ...
$res = mysql_query($QUERY2);
$num = mysql_num_rows($res);
if($num>0 )
{
while($row = mysql_fetch_assoc($res))
{
mysql_fetch_assoc($res);
$image_link= $row['image_link'];
}
to
$res2 = mysql_query($QUERY2);
$num2 = mysql_num_rows($res2);
if($num2 > 0)
{
while($row2 = mysql_fetch_assoc($res2))
{
$image_link= $row2['image_link'];
}
this is a mess - as others have said you're using the same variables for different purposes.
That you're storing integers which seem to represent enumerations in a char field is bad.
You're iterating through the second result set to find the last record (from an unsorted result set!).
You only need one query - not 2.
SELECT f.artist_name, f.artist_id, f.dateLastSent....
SUBSTR(
MAX(
CONCAT(DATE_FORMAT(date_submit, '%Y%m%d%H%i%s'), a.image_link)
), 15) as img_link
FROM followArtist f
LEFT JOIN artWork a
ON (a.artist_id=f.artist_id AND a.make_avail = '1')
WHERE user_id = $user_id
GROUP BY f.artist_name, f.artist_id, f.dateLastSent....

Categories