I'm working on a advanced search function but can't get it to return any values.
mysql_select_db($database_Audiologiska, $Audiologiska);
$where = array();
if (isset($_POST['Personnummer_search']))
{
$searchword = $_POST['Personnummer_search'];
$where[] = "vanster_implantat.patv LIKE '%".$searchword."%'";
}
if(isset($_POST['Namn_search']))
{
$name = $_POST['Namn_search'];
$where[] = "person.Namn LIKE '%".$name."%'";
}
if(isset($_POST['Efternamn_search']))
{
$surname = $_POST['Efternamn_search'];
$where[] = "person.Efternamn LIKE '%".$surname."%'";
}
if(count($where))
{
$query_SokvansterImp = "SELECT * FROM patient left join person on person.Personnummer = patient.Patient
left join vanster_implantat on vanster_implantat.Patv = patient.Patient
WHERE ".implode(" AND ",$where);
}
else//Visa all data
{
$query_SokvansterImp = "select * from patient left join person on person.Personnummer = patient.Patient left join vanster_implantat on vanster_implantat.patv = patient.Patient";
}
$SokvansterImp = mysql_query($query_SokvansterImp, $Audiologiska) or die(mysql_error());
$row_SokvansterImp = mysql_fetch_assoc($SokvansterImp);
$totalRows_SokvansterImp = mysql_num_rows($SokvansterImp);
Can you see if there is anything wrong with this code (except that it's not mysqli instead of mysql)?
Have you tried manually running that query; e.g. using the mysql command line tool or phpMyAdmin?
If you do, then you should get feedback on any potential errors, typos etc...
Also - just to be clear, do you actually perform mysql_query() on the query string, and mysql_fetch_array/fetch_row/fetch_assoc()?
Should look something like this:
$result = mysql_query($query_SokvansterImp) or die(mysql_error());
// die(mysql_error()); will cause the script to stop executing on error,
//and display the error message - you can leave it out but it's useful for debugging...
while ($row = mysql_fetch_assoc($result)) {
// Do stuff with the returned data - can be referenced by result column name
}
EDIT after comment #3:
Try swapping isset() in the conditions of your if-statements with if ($value != ''). It may be that the values are set (causing isset() to return true) even if there's no real text there...
Related
$sql = "SELECT * FROM
fbr.*, c.sample, ci.dob, ci.country, ci.sex
FROM `finalBloodReport` fbr ,`clients` c, `client_info` ci
WHERE fbr.sampleSerialNo = (CONCAT(c.resellerSerialId,'-',c.kitSerialNo) )
AND c.client_id = ci.id";
This is my query it works fine and gives the desired output,But since i am showing data in table i also want to get columns name only for this query to show them as table header .
I tried Something like this , but result is null.
$sql = "SHOW COLUMNS
fbr.*, c.sample, ci.dob, ci.country, ci.sex
FROM `finalBloodReport` fbr ,`clients` c, `client_info` ci
WHERE fbr.sampleSerialNo = (CONCAT(c.resellerSerialId,'-',c.kitSerialNo) )
AND c.client_id = ci.id";
Can anyone help ? I am not so good with mysql ; (
You need to retrieve column information after query is executed. This can be done by using mysqli_fetch_field()
You code should look like following
$result = mysqli_query($sql);
while($field = mysqli_fetch_field($result)) {
print $field->name . "\t";
}
while ($row = mysqli_fetch_row($result) {
print_r($row);
}
I'm getting this annoying error when my database row is empty,
But the rows are supposed to be empty until i add some values to it.
Any clues whats going wrong ? I tried to disable the problem by adding # before the variables but that doesn't work when they are in a foreach loop.
If I add data to the rows, the problems stops....
any ideas ?
some code.
$tweets = new Tweets();
foreach($tweets->fetch_tweets($_GET['uid']) as $tweet){
#$tweet_name = $tweet['username'];
#$tweet_date= $tweet['date'];
#$tweet_email= $tweet['email'];
}
function fetch_tweets($uid){ /*Mine and users I follow*/
$uid = (int)$uid;
$query = $this->link->query("SELECT user.id,
user.email,
user.username,
tweets.message,
tweets.date,
userdetails.profile_img,
userdetails.firstname,
userdetails.lastname,
following.id, following.user_id,
following.follow_id
FROM user
LEFT JOIN following ON user.id = following.user_id
JOIN userdetails ON user.id = userdetails.user_id
JOIN tweets ON userdetails.user_id = tweets.user_id
WHERE user.id='{$uid}' OR
user.id IN (SELECT follow_id
FROM following
WHERE following.user_id = '{$uid}' ) GROUP BY tweets.date ORDER BY tweets.date DESC "
);
$tweet = array();
while(($row = $query->fetch(PDO::FETCH_ASSOC)) !==FALSE) {
$tweet[] = $row;
} echo $query->rowCount();
return $tweet;
}
You need to check if the returned array is empty before you try to use it.
$tweets = new Tweets();
$res = $tweets->fetch_tweets($_GET['uid']);
if( empty($res) ) {
echo "no tweets.";
} else {
foreach($res as $tweet){
$tweet_name = $tweet['username'];
$tweet_date = $tweet['date'];
$tweet_email= $tweet['email'];
}
}
Also, you should always declare your functions before calling them. It's not a requirement in PHP as it is in most other languages, but it makes your code much easier to read.
Just run a code to check if number of rows is 0 before fetching the rows
i want to do sorting by clicking on the hyperlinked column header...
yes i managed to do it if i put sql statement in the if condition ..
example
td> <a style="width:100px;font-family:Arial;font-size:12px;color:white" href="?run=Process">Process</a></td>
php ;
$run = $_GET['run'];
if($run=="Process")
{
$sql = "select * from audit";
}
but the problem here... i want to assign sql statement before the if condition~
when i assign
$sql = "select audit.user,audit.tarikh,activity_ref.activity from audit left join activity_ref on audit.taskID = activity_ref.idactivity_ref
where audit.user = '".$_SESSION['USER']."'";
or
$user = $_POST["searchUser"];
if($user)
{
$sql = "select audit.user,audit.tarikh,activity_ref.activity from audit left join activity_ref on audit.taskID = activity_ref.idactivity_ref
where audit.user = '$user'";
}
the if condition == process does not understand $user value / $_session['User'] value..
ive assigned them with some value at the beginning.
ive been trying for all day long.. i guess i dont understand the concept well can you help me :( ..
it happened because i forgot to put this code ~
if($_SERVER['QUERY_STRING'])
{
}
it should be like this
if($_SERVER['QUERY_STRING'])
{
$run = $_GET['run'];
if($run=="Process")
{
$sql = "select audit.user,audit.tarikh,activity_ref.activity from audit left join activity_ref on audit.taskID = activity_ref.idactivity_ref
where audit.user = '".$_SESSION['USER']."'";
}
}
So what I'm trying to do is create a live friends search. To do this I need an array of names for AJAX to search through.
Heres my while loop.
if($_REQUEST['D'] == 'viewfriends') {
$FREINDS = array();
$FRIENDS_QUERY = "SELECT * FROM `FRIENDS` WHERE `USER` = '{$Modules['User']->Username}' AND `STATUS` = 'accepted' ORDER BY `ID` Limit 10 ;";
$FRIENDS_RESULT = mysql_query($FRIENDS_QUERY);
if(mysql_num_rows($FRIENDS_RESULT) > 0) {
while($FRIENDS_ROW = mysql_fetch_assoc($FRIENDS_RESULT)) {
$sql = "SELECT * FROM `USERS` WHERE `USERNAME` = '{$FRIENDS_ROW['FRIEND']}' ;";
$REQUEST_ROW = mysql_fetch_assoc(mysql_query($sql));
$FRIENDS = $REQUEST_ROW['USERNAME'];
}
echo json_encode($FRIENDS);
} else {
echo'<div class="update status">Sorry, You have no friends at this time. sadface.</div>';
}
}
I put the echo $FRIENDS in there as a test, right now it doesn't display anything. Where did I derp?
You can't echo an array. You can use either print_r($friends) to display the whole row of fields requested in the query (you request *)
or you can echo $friends['name'] (depending on how you declared name in your database)
try this:
if($_REQUEST['D'] == 'viewfriends') {
$FRIENDS = array();
$USERNAME = $Modules['User']->Username;
$SQL_QUERY = "SELECT F.*, U.* FROM FRIENDS AS F LEFT JOIN USER AS U ON F.USER = U.USERNAME WHERE F.USERNAME = '{$USERNAME}' AND STATUS = 'accepted' ORDER BY F.ID LIMIT 10";
$RESULTS = mysql_query($SQL_QUERY);
if(mysql_num_rows($RESULTS) > 0) {
while($ROW = mysql_fetch_assoc($RESULTS)) {
$FRIENDS[] = $ROW['USERNAME'];
}
echo json_encode($FRIENDS);
} else {
echo'<div class="update status">Sorry, You have no friends at this time. sadface.</div>';
}
}
$FRIENDS[] = $REQUEST_ROW['USERNAME'];
then print_r($FRIENDS); echo will output array you need to loop the array or echo json_encode($FRIENDS); to see something
also are you sure that USERNAME is uppercase and not just username in lowercase lowercase as well as for the table name.
also i think you can use a JOIN clause instead of making to SQL requests
You have syntax error:
$FREINDS = array(); should be $FRIENDS = array(); .
And also:
$FRIENDS = $REQUEST_ROW['USERNAME'] should be $FRIENDS[] = $REQUEST_ROW['USERNAME']
And
echo $FRIENDS; should be echo json_encode( $FRIENDS );
The PHP won't actually echo out an array. If you do an echo of an array, it outputs "Array". Plus your javascript wouldn't know what to do with a PHP array if it did pass it that way.
Try:
echo(json_encode($FRIENDS));
Also, you should really listen to the feedback in the comments. Your code is very vulnerable to attack and not set up to scale well for such a potentially huge app.
You have a couple of issues that make your code either less secure or less efficient. The most obvious inefficiency is that you are doing a database call inside your while loop, so if someone has 10 friends, that means you've done 11 database queries when you may have only needed one or two. Here are the two queries:
SELECT * FROM `FRIENDS`
WHERE `USER` = '{$Modules['User']->Username}'
AND `STATUS` = 'accepted' ORDER BY `ID` Limit 10
SELECT * FROM `USERS` WHERE `USERNAME` = '{$FRIENDS_ROW['FRIEND']}'
So before we determine if these two can be combined, the first big red flag is the SELECT *. I use it all of the time, but it will get you kicked out of the better database bars. In your case, it's really unnecessary. We know from the second query that the only thing you are using from the first query is the $FRIENDS_ROW['FRIEND'] to match against the USERNAME. So that first query can become:
SELECT FRIEND FROM `FRIENDS`
WHERE `USER` = '{$Modules['User']->Username}'
AND `STATUS` = 'accepted' ORDER BY `ID` Limit 10
You also have the SELECT * in the second query, and we can tell that (for now) the the only thing you are using is the USERNAME, so it can become:
SELECT USERNAME FROM `USERS` WHERE `USERNAME` = '{$FRIENDS_ROW['FRIEND']}'
Finally, we can see from the second query that the FRIEND name and the USERNAME are identical; otherwise why would you query for the usernames where the username equals the friend name. If that's the case, we can drop your second query completely, since we already know the usernames from the first query.
The reason why it's both inefficient and unsafe is because you are using the OG mysql functions, which are clunky and don't offer the option of prepared statements. Prepared statements let you (among other things) put variables in your query in such a way that when you actually call the query, the parts that are variables are known and can thus be sanitized, avoiding the horrors of mysql injections that everyone has mentioned.
I won't bore you with the play-by-play, but here is what your code might look like if you used the newer mysqli library with a prepared statement:
if($_REQUEST['D'] == 'viewfriends') {
$friends = array();
$friend_lookup = $mysqli->prepare("SELECT FRIEND FROM FRIENDS WHERE
USER = ? AND STATUS = 'accepted'
ORDER BY FRIEND");
$friend_lookup -> bind_param('s', $userName);
$userName = $Modules['User']->Username;
$friend_lookup -> execute();
$friend_lookup -> bind_result($friend);
while($friend_lookup -> fetch()) {
$friends[] = $friend;
}
if($friends) {
echo json_encode($friends);
} else {
echo "Sorry, no friends. Boo.";
}
}
Im trying to call all users from a database with the same interests as the current, logged in user on my website.
I have the following
// Get Session USER interest
$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;
$interest1 = $interests['1'];
$interest2 = $interests['2'];
$interest3 = $interests['0'];
// END INTERESTS
//USers with Same Interests
$interests_query = "SELECT * FROM produgg_users
join user_interests on produgg_users.id = user_interests.user_id
where interest = '$interest1' and produgg_users.id != '".$usersClass->userID()."'";
$interests_result = mysql_query($interests_query) or die(mysql_error());
if($interests_result != 0) {
while($interests_row = mysql_fetch_array($interests_result, MYSQL_ASSOC))
{
echo $interests_row['user_id'];
}
}
else
{
print "No users to display!";
}
//END SAME INTERESTS
which doesnt bring back any data, yet if I add (beneath //USers with Same Interests)
$interest1 = 'footy';
the interests_query seems to work, can anybody see where im going wrong?
My problem seems to lie here...
$interest1 = $interests['1'];
$interest2 = $interests['2'];
$interest3 = $interests['0'];
// END INTERESTS
//USers with Same Interests
$interest1 = 'footy';
If I manually assign a value to $interest variable it works, but i need to get use the value from the array above, does this make sense?
If your code brings back the correct data when you add $interest1 = 'footy'; line, that would imply that there is something wrong with the value of that variable when you don't. Have you tried var_dump($interest1); right under //Users with Same Interests line to see what kind of input you get from your interestsquery?
I would expect the var_dump to not return a valid string (since if it would, the query would work following the $interest1 = 'footy'; assumption), so you would have to look at what interestsquery returns wrong.
Looks like you querying user_id from user_interests as number, but from produgg_users as string. Maybe there's a problem
You can do it with one query:
$userID = mysql_real_escape_string($usersClass->userID());
$sql = "
SELECT * FROM user_interests AS ui1
JOIN LEFT user_interests AS ui2 ON ui1.id = ui2.id
JOIN LEFT produgg_users AS pu ON ui2.user_id = pu.id
WHERE ui.user_id = " . userID ;