Loop a variable inside an sql query - php

I'm trying to work out the following,
I am querying a Salesforce db with PHP, an seems that they don't really allow relationship queries, which is my whole problem, so need to run 2 queries, a query first to populate a variable that is used into a second query right after.
That variable will hold a string with usernames, just plain text usernames, that I need to match with an Id that will match a OwnerId after,
something like this,
<?php
$query = "SELECT FirstName FROM User WHERE Id in (SELECT OwnerId from Case WHERE Region__c = 'WORLD' and CaseOwnerManager__c = 'some_guy' AND Status = 'Open')";
$response = $mySforceConnection->query($query);
$queryResult = new QueryResult($response);
for ($queryResult->rewind(); $queryResult->pointer < $queryResult->size; $queryResult->next()) {
$record = $queryResult->current();
$firstName = $record->fields->FirstName;
echo $firstName."<br>\n";
}
$query = "SELECT CaseNumber, Status FROM Case where Status = 'Open' and OwnerId in (SELECT Id FROM User where FirstName = '{$firstName}')";
$response = $mySforceConnection->query($query);
$queryResult = new QueryResult($response);
for($queryResult->rewind(); $queryResult->pointer < $queryResult->size; $queryResult->next()) {
$record = $queryResult->current();
$caseNumber = $record->fields->CaseNumber;
$status = $record->fields->Status;
echo $caseNumber."<br>\n";
echo $status."<br>\n";
}?>
Of course, in the above, the second query, the one with the $firstName variable, it picks up the last value of the string and then the loop gives the CaseNumber and Status of that single user.
So what i need to do is get that second query in some sort of loop and while it is looping, get the $firstName variable to loop as well.
So at the end, $firstName should populate the th of a table and $caseNumber and $status its tds
Any ideas on how to do it, or if it even can be done?
Cheers.

Related

How to filter json encode array count?

In my example I have a PHP script that, from AJAX, does a tally of everyone named 'Richard.' I would like to further modify this by counting the people named Richard, that match the age of some input value, as shown in $theirage.
Specifically, I would like to sum up the two ages, and only show the ones that equal 20 in my array. $row[age] corresponds to the value age in my DB, while $theirage is a user input.
At the end I want to only tally the summed ages that equal to 20, in this case.
$theirage = $_GET['theirage'];
$query = mysqli_query($con, "SELECT count(*) as cnt FROM members WHERE
name = 'Richard'
");
$row = mysqli_fetch_assoc($query);
$bow = $row['age'] + $theirage;
$if ($bow = 20){
$person = $row['cnt'];}
echo json_encode( array(
'person' => $person
) );
How might I go about this?
I suggest you query members table to count all who are matching your criteria: specific name 'Richard' and specific age $_GET['theirage']:
<?php
$theirAge = $_GET['theirage'];
// This is important: since we're using $theirAge in query string, we need to escape it
$theirAge = mysqli_escape_string($theirAge);
// Let's query all members whose name is Richard and age is equal to $_GET['theirage']
$query = mysqli_query($con, "SELECT count(*) FROM members WHERE name = 'Richard' AND age + $theirAge = 20");
$row = $query->fetch_row();
$totalRichardsOfGivenAge = $row[0]; // here is your result.
// And now let's return JSON
echo json_encode($totalRichardsOfGivenAge)

SELECT statement returns first row instead of record that is looked up

I am trying to select a record from my database, and I am return instead the first one in the table. No matter what I try, the first one gets returned.
Here's the query:
$query_task_owner = "select user_id from users where full_name = '$c_task_owner_name'";
$response = #mysqli_query($dbc, $query_task_owner);
Then I try a test to see the value that is returned as such:
echo $response or die(mysql_error());
This is where I see the user_id of the first row.
Even if I try to put a specific value in the query, as follow, I am getting the same result:
$query_task_owner = "select user_id from users where full_name = 'LeBron James'";
I do not understand because when I trying this query directly in PHPMyAdmin, I am getting the right result. So the query itself is correct.
Any idea?
Fetch $response using mysqli_fetch_array().
<?php
$query_task_owner = "select user_id from users where full_name = '$c_task_owner_name'";
$response = #mysqli_query($dbc, $query_task_owner);
$row = mysqli_fetch_array($response,MYSQLI_ASSOC);
echo $row['user_id'];
?>
If, users are more related to that full name. Then, use while loop to fetch all record.
<?php
$query_task_owner = "select user_id from users where full_name = '$c_task_owner_name'";
$response = #mysqli_query($dbc, $query_task_owner);
while($row = mysqli_fetch_array($response,MYSQLI_ASSOC))
{
echo $row['user_id']."<br>";
}
?>

Using MAX() in mySQL query is giving problematic results

I'm trying to make multiple queries in order to find the most recent entry in a database by username.
Here's my code:
<?php
require_once("../includes/db_connection.php");
$userID = $_POST["userID"];
$returnString = array();
// Query the max id value of a given key_id (find the most recent upload)
$query = "SELECT MAX(id) FROM photos WHERE key_id = {$userID}";
$result = mysqli_query($connection, $query);
//additional while loop could go here
//now get the url where from the max id value that we just queried
$query = "SELECT url FROM photos WHERE id = {$urlID}";
$result = mysqli_query($connection, $query);
$returnString['url'] = $urlID;
mysqli_free_result($result);
echo json_encode($returnString);
?>
I think the problem lies in the first query. When I return the result from that, I get:
{"maxID": "current_field":null,"field_count":null,"lengths":null,"num_rows":null,"type":null}
When I create a while loop to capture the array (why I need to do this is beyond me because it will only ever return 1 value):
while($row = mysqli_fetch_assoc($result)) {$returnString[] = $row;}
Then I get this funky result:
[{"MAX(id)":"30"}]
30 is the correct value, but then I don't know how to use that result in my next mySQL query.
**********UPDATE*************
The query :
SELECT url FROM photos WHERE id = (SELECT MAX(id) FROM photos WHERE key_id = {$userID});
Works perfectly when making the query from within mySQL, but doesn't work from my php script. It returns this weird string:
{"url":{"current_field":null,"field_count":null,"lengths":null,"num_rows":null,"type":null}}
Here's the updated script:
require_once("../includes/db_connection.php");
$userID = $_POST["userID"];
$returnString = array();
$query = "SELECT url FROM photos WHERE id = (SELECT MAX(id) FROM photos WHERE key_id = {$userID})";
$result = mysqli_query($connection, $query);
mysqli_free_result($result);
$returnString['url'] = $result;
echo json_encode($returnString);
Unless I'm missing something in the schema that's not apparent from code and comments, you can save yourself a roundtrip by combining your SQL commands.
$query = "SELECT id AS urlID, url FROM photos WHERE id = (SELECT MAX(id) FROM photos WHERE key_id = {$userID})";
Then interface with your results like you normally would.
Updated answer:
$query = "SELECT url FROM photos WHERE id = (SELECT MAX(id) FROM photos WHERE key_id = {$userID})";
$result = mysqli_query($connection, $query);
$row = mysqli_fetch_array($result):
$url = $row['url'];
echo json_encode($url);
mysqli_free_result($result);
I think the real problem is in the loop and use of an array for the results.
You should change to a single query like:
SELECT url, MAX(id) as id FROM photos WHERE key_id = {$userID}
MAX(id) as id returns the aggregate column name as id
You don't need to loop with a while if you are only expecting one row. Just change the while to if to test if any row is returned, and assign the values to single variables:
$id = {$row['id']};
$url = {$row['url']};
The "funky" result is from trying to print the array which is not needed and has stored the column name and value.

MySQL Query not calling data based on variable

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 ;

Simple way to read single record from MySQL

What's the best way with PHP to read a single record from a MySQL database? E.g.:
SELECT id FROM games
I was trying to find an answer in the old questions, but had no luck.
This post is marked obsolete because the content is out of date. It is not currently accepting new interactions.
$id = mysql_result(mysql_query("SELECT id FROM games LIMIT 1"),0);
$link = mysql_connect('localhost','root','yourPassword')
mysql_select_db('database_name', $link);
$sql = 'SELECT id FROM games LIMIT 1';
$result = mysql_query($sql, $link) or die(mysql_error());
$row = mysql_fetch_assoc($result);
print_r($row);
There were few things missing in ChrisAD answer. After connecting to mysql it's crucial to select database and also die() statement allows you to see errors if they occur.
Be carefull it works only if you have 1 record in the database, because otherwise you need to add WHERE id=xx or something similar to get only one row and not more. Also you can access your id like $row['id']
Using PDO you could do something like this:
$db = new PDO('mysql:host=hostname;dbname=dbname', 'username', 'password');
$stmt = $db->query('select id from games where ...');
$id = $stmt->fetchColumn(0);
if ($id !== false) {
echo $id;
}
You obviously should also check whether PDO::query() executes the query OK (either by checking the result or telling PDO to throw exceptions instead)
Assuming you are using an auto-incrementing primary key, which is the normal way to do things, then you can access the key value of the last row you put into the database with:
$userID = mysqli_insert_id($link);
otherwise, you'll have to know more specifics about the row you are trying to find, such as email address. Without knowing your table structure, we can't be more specific.
Either way, to limit your SELECT query, use a WHERE statement like this:
(Generic Example)
$getID = mysqli_fetch_assoc(mysqli_query($link, "SELECT userID FROM users WHERE something = 'unique'"));
$userID = $getID['userID'];
(Specific example)
Or a more specific example:
$getID = mysqli_fetch_assoc(mysqli_query($link, "SELECT userID FROM users WHERE userID = 1"));
$userID = $getID['userID'];
Warning! Your SQL isn't a good idea, because it will select all rows (no WHERE clause assumes "WHERE 1"!) and clog your application if you have a large number of rows. (What's the point of selecting 1,000 rows when 1 will do?) So instead, when selecting only one row, make sure you specify the LIMIT clause:
$sql = "SELECT id FROM games LIMIT 1"; // Select ONLY one, instead of all
$result = $db->query($sql);
$row = $result->fetch_assoc();
echo 'Game ID: '.$row['id'];
This difference requires MySQL to select only the first matching record, so ordering the table is important or you ought to use a WHERE clause. However, it's a whole lot less memory and time to find that one record, than to get every record and output row number one.
One more answer for object oriented style. Found this solution for me:
$id = $dbh->query("SELECT id FROM mytable WHERE mycolumn = 'foo'")->fetch_object()->id;
gives back just one id. Verify that your design ensures you got the right one.
First you connect to your database. Then you build the query string. Then you launch the query and store the result, and finally you fetch what rows you want from the result by using one of the fetch methods.
$link = mysql_connect('localhost','root','yourPassword')
mysql_select_db('database',$link);
$sql = 'SELECT id FROM games'
$result = mysql_query($sql,$link);
$singleRow = mysql_fetch_array($result)
echo $singleRow;
Edit: So sorry, forgot the database connection. Added it now
'Best way' aside some usual ways of retrieving a single record from the database with PHP go like that:
with mysqli
$sql = "SELECT id, name, producer FROM games WHERE user_id = 1";
$result = $db->query($sql);
$row = $result->fetch_row();
with Zend Framework
//Inside the table class
$select = $this->select()->where('user_id = ?', 1);
$row = $this->fetchRow($select);
The easiest way is to use mysql_result.
I copied some of the code below from other answers to save time.
$link = mysql_connect('localhost','root','yourPassword')
mysql_select_db('database',$link);
$sql = 'SELECT id FROM games'
$result = mysql_query($sql,$link);
$num_rows = mysql_num_rows($result);
// i is the row number and will be 0 through $num_rows-1
for ($i = 0; $i < $num_rows; $i++) {
$value = mysql_result($result, i, 'id');
echo 'Row ', i, ': ', $value, "\n";
}
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$db = new mysqli('localhost', 'tmp', 'tmp', 'your_db');
$db->set_charset('utf8mb4');
if($row = $db->query("SELECT id FROM games LIMIT 1")->fetch_row()) { //NULL or array
$id = $row[0];
}
I agree that mysql_result is the easy way to retrieve contents of one cell from a MySQL result set. Tiny code:
$r = mysql_query('SELECT id FROM table') or die(mysql_error());
if (mysql_num_rows($r) > 0) {
echo mysql_result($r); // will output first ID
echo mysql_result($r, 1); // will ouput second ID
}
Easy way to Fetch Single Record from MySQL Database by using PHP List
The SQL Query is SELECT user_name from user_table WHERE user_id = 6
The PHP Code for the above Query is
$sql_select = "";
$sql_select .= "SELECT ";
$sql_select .= " user_name ";
$sql_select .= "FROM user_table ";
$sql_select .= "WHERE user_id = 6" ;
$rs_id = mysql_query($sql_select, $link) or die(mysql_error());
list($userName) = mysql_fetch_row($rs_id);
Note: The List Concept should be applicable for Single Row Fetching not for Multiple Rows
Better if SQL will be optimized with addion of LIMIT 1 in the end:
$query = "select id from games LIMIT 1";
SO ANSWER IS (works on php 5.6.3):
If you want to get first item of first row(even if it is not ID column):
queryExec($query) -> fetch_array()[0];
If you want to get first row(single item from DB)
queryExec($query) -> fetch_assoc();
If you want to some exact column from first row
queryExec($query) -> fetch_assoc()['columnName'];
or need to fix query and use first written way :)

Categories