I am having a problem returning a JSON array after trying to do a query where I want the query to return the first name, last name , and email after giving it numerous ids. How would I go about returning an array with rows including the above parameters after giving it ids. here is what I have
This works :
$qry = "SELECT ALL $mysql_database.$patientsTable.Users_idUser FROM $mysql_database.$patientsTable WHERE doctorsTable_id_doctorsTable=$qr";
$res = mysql_query($qry,$connect) or die(mysql_error());
then this is what I am working on where it is not working :
$arr_length = count($arr);
for($i=1;$i<=$arr_length;$i++)
{
$integerIDs = json_decode('[' .json_encode($arr[$i]['Users_idUser']) . ']', true);
$q = "SELECT firstName,lastName,email from $mysql_database.$UsersTable WHERE idUser='$integerIDs[$i]'";
$res1 = mysql_query($q,$connect) or die(mysql_error());
}
I want to for loop to return the above question but i am having problem with this.
You may do this with one query using JOIN expression as follow:
SELECT firstName,
lastName,
email
FROM $mysql_database.$UsersTable u
INNER JOIN $mysql_database.$patientsTable p ON p.Users_idUser = u.idUser
WHERE p.doctorsTable_id_doctorsTable=$qr
However, I would suggest you using PDO abstraction over mysql_* functions and PHP variables as parameters to communicate with database as more reliable and comprehensive approach.
Related
I want my application to dynamically change which database and schema name it uses depending on whether it's running on a local machine, staging environment, or production. I thought pg_query_params would be a great choice because you can dynamically substitute things into your queries by parameterizing them. The idea is the schema name will be dynamically inserted into the query. But, pg_query_params() doesn't seem to be substituting the values in the array, causing a query syntax error.
I have verified that the query itself is valid by using pg_query and hardcoding the schema name in versus parameterizing it. When I look at the logs, I see the following error:
PHP Warning: pg_query_params(): Query failed: ERROR: syntax error at or near "$1. Line 2 FROM $1.module__c
So, clearly, pg_query_params isn't actually substituting the parameters in (at least from what I can see)
As a result, pg_query_params() returns false, and breaks the whole page.
The code first gets an array from my databaseInfo() function (it returns an array for the schema name and connection resource. I've verified that this part of my code is working and returning the expected information.
$database = databaseInfo();
if (isset($projSFID)) {
$placeholder = $projSFID;
$query = "SELECT $1.module__c.name, $1.module__c.module_title__c, $1.module__c.number_of_units__c, $1.module__c.duration_minutes__c, $1.module__c.module_bg_hex__c, $1.module__c.module_description__c, $1.lms_asset__c.lms_asset_url__c
FROM $1.module__c
INNER JOIN $1.teproject__c ON $1.module__c.associated_project__c = $1.teproject__c.sfid
INNER JOIN $1.lms_asset__c ON $1.module__c.module_image_url__c = $1.lms_asset__c.sfid
WHERE $1.teproject__c.sfid = $2 AND $1.module__c.published__c=TRUE";
} elseif (isset($trackSFID)) {
$placeholder = $trackSFID;
$query = "SELECT $1.module__c.name, $1.module__c.module_title__c, $1.module__c.number_of_units__c, $1.module__c.duration_minutes__c, $1.module__c.module_bg_hex__c, $1.module__c.module_description__c, $1.lms_asset__c.lms_asset_url__c
FROM $1.module_track_association__c
INNER JOIN $1.module__c ON $1.module_track_association__c.module__c = $1.module__c.sfid
INNER JOIN $1.track__c ON $1.module_track_association__c.track__c = $1.track__c.sfid
INNER JOIN $1.lms_asset__c ON $1.module__c.module_image_url__c = $1.lms_asset__c.sfid
WHERE $1.track__c.sfid = $2
ORDER BY $1.module_track_association__c.navigation_sequence__c";
} else {
$placeholder = '';
$query = "SELECT $1.module__c.name, $1.module__c.module_title__c, $1.module__c.number_of_units__c, $1.module__c.duration_minutes__c, $1.module__c.module_bg_hex__c, $1.module__c.module_description__c, $1.lms_asset__c.lms_asset_url__c
FROM $1.module__c
INNER JOIN $1.lms_asset__c ON $1.module__c.module_image_url__c = $1.lms_asset__c.sfid
WHERE $1.module__c.published__c=TRUE AND $1.module__c.display_on_frontend_filtered_only__c=FALSE $2";
echo $query;
}
$result = pg_query_params($database['connection'], $query, array($database['schema'],$placeholder));
The expected result is that $1 will be the name of the schema and $2 will be the value of the placeholder as determined by the conditional logic.
So I'm trying to use a "LIKE" in the SQL, basically to see if a player is in a team already. Here's the code I have:
$checkifonlytwo = "SELECT * FROM sg_turn_teams WHERE joinid = :joinid AND players LIKE '%:ownerid,%'";
$paramstwo = array(
":joinid" => $joinid,
":ownerid" => $_SESSION['user']['id']
);
try{
$stmttwo = $db->prepare($checkifonlytwo);
$resulttwo = $stmttwo->execute($paramstwo);
}
catch(PDOException $ex){
die("Failed to run query #2: " . $ex->getMessage());
}
Also as you can see I want it to be LIKE '%1,%' for example, so the comma at the end too.
My table structure looks like this.
EDIT, the players is going to be like "1,2,3" without the names because the users are able to change their name. The picture is with names, but it's supposed to be 1,2,3
Foreword. I decided to make this a community wiki. I did not want to gain anything from this, except for the OP and others visiting the question.
As I said in comments, you're going about it the wrong way with the comma in there ownerid,.
What you need to do is implode on the array and using IN().
Borrowed from https://stackoverflow.com/a/12151295/
$e = 0;
while($e<$num1){
$units = 0;
$r = 0;
$SO_Line_Item=mysql_result($result1,$e,"SO_Line_Item");
foreach ($Boxes[$e] as $a => $b)
{
$zzz[] = $Boxes[$e][$r];
$ce = count($Boxes[$e]);
$r++;
}
//end inner foreach
$products = implode(',', array_fill(0,$ce, '?'));
$db = new PDO('mysql:host=192.168.1.197 ;dbname=Tracking', $dbuser,$dbpass);
$stmt = $db->prepare("SELECT Box_Num,Timestamp,E3_SN,Assy_Status FROM Current_Box WHERE Box_Num IN( $products )");
$stmt->execute($zzz);
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
unset($zzz);
$e++;
}
and from https://stackoverflow.com/a/2814703/
$ids = array(2, 4, 6, 8);
// prepare a string that contains ":id_0,..,:id_n" and include it in the SQL
$plist = ':id_'.implode(',:id_', array_keys($ids));
$sql = "SELECT * FROM someTable WHERE someId IN ($plist)";
// prepare & execute the actual statement
$parms = array_combine(explode(",", $plist), $ids);
$stmt = $PDO->prepare($sql);
$rows = $stmt->execute($parms);
From comments:
"You might want to use association tables rather than storing the information the way you are storing it. – Maximus2012"
As mentioned in the comments, some questions/answers from SO that demonstrate the concept of Association tables along with composite primary keys:
Mysql : Association table
How to use an MySQL association table to return categories not currently assigned to an entry
If OP decides to go with this structure then the queries would need to be changed to make use of LEFT JOIN and/or use a sub-query with IN clause. There are plenty of examples of both on SO. One that I could find with a simple search (please ignore the slow query part and look at the examples to demonstrate the concept):
MySQL - SELECT WHERE field IN (subquery) - Extremely slow why?
I have three tables (questions, answers, user) and I want to query all questions and answers posted by user.
Here is my code:
$query = $this->db->select('user.*,questions.*,answers.*')
->from('user')
->join('questions','questions.user_id = user.u_id','LEFT')
->join('answers','answers.user_id = user.u_id','LEFT')
->where('user.u_id',$profile[0]['u_id'])
->group_by('user.u_id')
->get();
echo $query->num_rows();
I have 1 posted question and 1 answer in my tables, but when I am trying this code it gives me only 1 row.
Try this with method..
write your query in single line like this
$query= "select * from user where" ; as well ( this is only query example you have to write your query)
then
if ($result = mysqli_query($connection, $query )) {
/* fetch associative array */
while ($res = mysqli_fetch_assoc($result)) {
print_r($res);
}
mysqli_free_result($result);
}
in this case $connection is a your database connection
Have you tried outer join, instead left join?
Maybe even a left outer join, solves your problem, just try it.
Oh, and instead of 'num_rows()' i suppose you just want to use 'row()' to
retrieve all table´s data.
$this->db->select('user.*,questions.*,answers.*');
$this->db->join('questions','questions.user_id = user.u_id','OUTER LEFT');
$this->db->join('answers','answers.user_id = user.u_id','OUTER LEFT');
$this->db->where('user.u_id',$profile[0]['u_id']);
$this->db->group_by('user.u_id')
$query = $this->db->get('user')->row();
echo $query;
I´ve changed a little your write, just copy and test it if you´d want
This question already has answers here:
PHP - Using PDO with IN clause array
(9 answers)
Closed 9 months ago.
I want to bind a array of Strings to the WHERE IN part of a SQL command, which I want to run afterwards on a SQL Server. The problem is probably that I try to bind an array of Strings and not an array of integers.
$totalCount =
"SELECT referral, COUNT(username) AS cnt FROM accounts
WHERE referral IN ($refIdsPartial) GROUP BY referral";
$ps_totalCounts = $dbh->prepare($totalCount);
$ps_totalCounts->execute();
//loop over total counts
foreach($ps_totalCounts as $row){
echo "Test<br>";
}
I echoed $refIdsPartial for you, so you have an idea what this is:
54469c27c687b332339627,54469ba0dec3e703865612,54469c77945c7091266617
Its just an imploded array of strings/varchars.
I tested the SQL command with my Managementstudio and I can ensure that this SQL command works, as long das I use the quote signs for each String/Varchar. Example:
SELECT referral, COUNT(username) AS cnt FROM accounts
WHERE referral IN ('54469c27c687b332339627','54469ba0dec3e703865612') GROUP BY referral
My problem:
In the code above it never goes into the foreach, so the result of the Query seems to be empty. What is wrong there (Ofcourse I tested only queries which should have results)?
You could use some string manipulation.
You can count the number of ? you'd need by using str_repeat("?", count(explode(",", $refIdsPartial))). This will create your placeholders.
$totalCount =
"SELECT referral, COUNT(username) AS cnt FROM accounts
WHERE referral IN (". str_repeat("?,", count(explode(",", $refIdsPartial))-1) . "?) GROUP BY referral";
Now that the placeholders are in place, you can explode the , from the string and execute
$ps_totalCounts->execute( explode(",", $refIdsPartial) );
Here is the snippet I use when trying to achieve an IN statement with an array.
This works dynamically, so whether you have an array of 2 or 200 it should execute as expected.
$ids = array(1,2,3);
$in = str_repeat('?,', count($ids) - 1) . '?';
$sql = "SELECT * FROM table WHERE column IN ($in)";
$stm = $db->prepare($sql);
$stm->execute($ids);
$data = $stm->fetchAll();
Your code will look like so:
$refIdsPartial = array('54469c27c687b332339627','54469ba0dec3e703865612','54469c77945c7091266617');
$in = str_repeat('?,', count($refIdsPartial ) - 1) . '?';
$totalCount = "SELECT referral, COUNT(username) AS cnt FROM accounts WHERE referral IN ($in) GROUP BY referral";
$ps_totalCounts = $dbh->prepare($totalCount);
$ps_totalCounts->execute();
//loop over total counts
foreach($ps_totalCounts as $row)
{
echo "Test<br>";
}
I faced similar problem with quite a big array to bind. Instead of skipping binding and injecting whole array directly to query or making workarounds with dynamically generating multiple unique placeholders to bind each record of array, I went for using find_in_set mysql function. Read more here.
In your case it would be:
$totalCount =
"SELECT referral, COUNT(username) AS cnt FROM accounts
WHERE find_in_set(referral,$refIdsPartial) GROUP BY referral";
// make empty array
$sqlArray=array();
$jsonArray=array();
// START NEED FAST WORKING ALTERNATİVES -----------------------------------------------------
// first 20 vistors
$query = "SELECT user_id FROM vistors LIMIT 20";
$result = mysql_query ($query) or die ($query);
// make vistors user query array
while ($vstr_line = mysql_fetch_array($result)){
array_push($sqlArray, $vstr_line['user_id']);
}
// implode vistors user array
$sqlArray_impl = implode("', '", $sqlArray);
// END NEED FAST WORKING ALTERNATİVES -----------------------------------------------------
// Get vistors information
$query = "SELECT id, username, picture FROM users WHERE id IN ('$sqlArray_impl')";
$qry_result = mysql_query($query) or die($query);
while ($usr_line = mysql_fetch_array($qry_result)){
array_push($jsonArray, $usr_line['id'].' - '.$usr_line['username'].' - '.$usr_line['picture']);
}
print_r($sqlArray);
echo '<br><br>';
print_r($jsonArray);
see this my functions..
i need a replacement for fast working alternatives..
function within the range specified above, to me, running faster than the alternative.
the query will return back array ?
thx for all helpers !
Can you use a JOIN or SUB SELECT to reduce the query count from 2 to 1? Might not give much of a boost but worth a shot and a cleaner implementation.
Where is the bottleneck? Most likely the db and not the php code.
Are the tables/columns properly indexed? Run EXPLAIN on both queries.
Easiest would be to include first query as subquery eliminating one turn to the DB and a lot of code:
// Get vistors information
$query = "SELECT id, username, picture FROM users WHERE id IN (SELECT user_id FROM vistors LIMIT 20)";
$qry_result = mysql_query($query) or die($query);
Unless there is more reason to have the first one seperate, but that is not visible in your code example.
If you use PDO (recommended anyway...), you can return the result array all at once using fetchAll().
For your second query, you can use string concatenation in MySQL to directly return the result you want.