MySQL Query not calling data based on variable - php

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 ;

Related

How to output a value of an other table from an indexed field in mySQL?

I have two MySQL tables
users with id, user_formOfAdress and serveral additional fields. Field user_formOfAdress contains the id of table formofadress
formofadress with id, formOfAdress_german and serveral additional fields, for example id 1 = Mr., id 2 = Mrs.
The record of the users table is identified by a Session variable.
To output not the id of the field user_formOfAdress but the value of the table formofadress.formOfAdress_german (for example Mr. or Mrs.) I have written this:
if(array_key_exists("id", $_SESSION) && $_SESSION['id']){
$uid = $_SESSION['id'];
$link = mysqli_connect("localhost:3307", "root", "Dinah123", "proficrm");
$query = "
SELECT formofadress.ID AS formofadress_ID, formofadress.formOfAdress_german, users.ID, users.user_formOfAdress
FROM `formofadress`
LEFT JOIN users
ON formofadress.formofadress_ID = users.user_formOfAdress
WHERE `users.ID` = '".$uid."'
LIMIT 1
";
$result = mysqli_query($link, $query);
$record = mysqli_fetch_assoc($result);
$user_formOfAdress = $record['formOfAdress_german'];
}
"FROM formofadress" because I want to output the Mr. or Mrs. of this table, but I have to use also the users table because of the Session ID which is also the id of the users record ...
Not every record in the users table has a value in user_formOfdAdress (value 1, 2 or NULL) but every record in the formofadress table has a fixed value.
Error is:
Undefined variable: user_formOfAdress located in the last row
It's my first time to use JOINs and I'm unfortunately not able to solve this issue even after a long time of searching.
Correct code:
if(array_key_exists("id", $_SESSION) && $_SESSION['id']){
$uid = $_SESSION['id'];
$link = mysqli_connect("localhost:3307", "root", "Dinah123", "proficrm");
$query = "
SELECT formofadress.ID, formofadress.formOfAdress_german, users.ID, users.user_formOfAdress
FROM formofadress
LEFT JOIN users
ON formofadress.ID = users.user_formOfAdress
WHERE users.ID = '".$uid."'
";
$result = mysqli_query($link, $query);
$record = mysqli_fetch_assoc($result);
$user_formOfAdress = $record['formOfAdress_german'];
}
There were problems with your SQL syntax. You used LEFT JOIN to join users to formofadress while users sometimes can't follow and you will possibly get a NULL value. I also cleaned up your other query syntax so it is more readable.
Also, check to see if the database is expecting an INT for $uid. If not then return the apostrophes ''.
if(array_key_exists("id", $_SESSION) && $_SESSION['id'])
{
$uid = $_SESSION['id'];
$link = mysqli_connect("localhost:3307", "root", "Dinah123", "proficrm");
$query = "SELECT u.ID, u.user_formOfAdress, f.ID, f.formOfAdress_german,
FROM users u LEFT JOIN formofadress f ON f.formofadress_ID = u.user_formOfAdress
WHERE u.ID = ".$uid." LIMIT 1";
// if database is not expecting `INT` for `u.ID` then return the apostrophes ' '
$result = mysqli_query($link, $query);
// mysqli_fetch_assoc returns case sensitive keys
$record = mysqli_fetch_assoc($result);
$user_formOfAdress = $record['formOfAdress_german'];
}

Advanced search requiring multiple parameters

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...

Undefined variable on empty database 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

hyperlink sort database

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']."'";
}
}

PHP Query Call Issue

I have two tables in my database:
1) blog_table
2) content
In blog_table I have values called postID that may or may not match up to values called id in the table content. I am wanting to know how I can write a while loop or foreach loop that will cycle through content table and perform one action if the id equals the value of postID in the blog_table and perform a different action if it doesn't.
Right now I can only get id = postID
$blog_table = $_REQUEST['blog_table'];
$getblogtable = mysql_query("SELECT * FROM content WHERE type = '5' AND blogID = '{$_REQUEST['id']}' ORDER BY `order` ASC");
while ($row = mysql_fetch_assoc($getblogtable))
{
$getblogposts1 = mysql_query("SELECT postID FROM `$blog_table`");
while ($row1 = mysql_fetch_assoc($getblogposts1))
{
if( $row1['postID'] == $row['id']) {
echo "do something<br>";
}else{
echo "do something else<br>";
}
} echo "<p></p>";
}
[Edit based on OP's comments and revised question]
$getblogposts = mysql_query("SELECT * FROM content WHERE type = '5' AND blogID = '{$_REQUEST['id']}' ORDER BY `order` ASC");
while ($row = mysql_fetch_assoc($getblogposts))
{
$matches = mysql_query("SELECT * FROM $blog_table WHERE postID = $row['id']");
if (mysql_num_rows($matches) > 0)
{
// do something
}
else
{
// do something else
}
}
Regarding a different design, I can't say for sure that it's necessary, but I don't like running a loop of queries like this. I think one query should be enough to get everything you need in this case. Maybe if you describe your application, we could find a better query or more appropriate design.
Just providing an easier to see solution for you to your problem.
I suggest using inner joins which will solve the issue at hand.
For example, Something like:
SELECT * FROM content AS C INNER JOIN $blog_table AS B on B.postID = C.id
Here is a great introduction to joins (inner, left, right, full):
http://www.w3schools.com/sql/sql_join.asp
$blog_table = $_REQUEST['blog_table'];
$getblogtable = mysql_query("SELECT postID FROM `$blog_table`");
while ($row = mysql_fetch_assoc($getblogtable))
{
$postID = $row['postID'];
$getblogposts1 = mysql_query("SELECT * FROM content WHERE id = '$postID' ORDER BY `order` ASC");
while ($row1 = mysql_fetch_assoc($getblogposts1))
{
// if( $row1[id] == $postId )
// do something
// else
// do something else
}
}

Categories