Get specific column of specific row without loop in php - php

$output = QuerySelect($sqlCheckSameTeamLead, $selectBindings);
function QuerySelect($query, $bindings = NULL){
global $connPDO;
$statement = $connPDO->prepare($query); //prepare statement
$statement->execute($bindings); //execute Statment
return $statement->fetchAll(PDO::FETCH_ASSOC); //return result in associative array
}
I am looking for a way to get $output second row and specific column but without loop. I can loop through $outputbut i want to avoid it.

My suggestion is that you dothat via your query
Example:
SELECT * FROM table_name LIMIT 1, 1
Gets only the second row, then you can use SELECT clause to get the desired columns.

Related

SQL | Get all results from query not just the first

Hello i am doing an request to an SQL Database (in php) witch looks like this...
SELECT firstname FROM users WHERE job = '$jobL'
Lets assume in the Database are three users with the $jobL namend: Mike, Steve & Danny.
Expected Output:
array("mike", "steve", "danny")
Given Output:
array("mike")
So mike is the first result in the users table. SQL only gets me the first result, i want to get all results matching my query, not only the first one.
Thanks
EDIT:
Its an php function...
function GetJobMembers($jobL) { //Function to get all Members of an Job in an Array
global $db;
$AllWithJobSQL = $db->query("SELECT firstname FROM users WHERE job = '$jobL'");
$AllUsersWithJob = $AllWithJobSQL->fetch_assoc();
return $AllUsersWithJob;
}
i tested it with $jobL = groove //GTA RP Server stuff
my db manual serach:
Use fetch_all() to fetch all rows as a 2-dimensional array. Then you can use array_column() to extract the firstname index from each row.
You should also use a prepared statement to prevent SQL injection.
function GetJobMembers($jobL) { //Function to get all Members of an Job in an Array
global $db;
$stmt = $db->prepare("SELECT firstname FROM users WHERE job = ?");
$stmt->bind_param("s", $jobL);
$stmt->execute();
$result = $stmt->get_result();
$AllUsersWithJob = $result->fetch_all(MYSQLI_ASSOC);
return array_column($AllUsersWithJob, 'firstname');
}
fetch() is opened as a pointer ready to step through the data one by one (usually in a while loop).
while($row= $AllWithJobSQL->fetch_assoc()) {
echo $row["job"].PHP_EOL;;
}
In your case, you should use fetchAll(). It fetches all the data at once, without opening any pointer, storing it in an array. It is recommended when you do not expect too many results that could cause memory problems when you want to store thousands or millions of rows from a SELECT into an array at once.
$AllUsersWithJob = $AllWithJobSQL-> fetch_all(MYSQLI_ASSOC);
return $AllUsersWithJob;
In this case $AllUsersWithJob is an associative array with all the query data. If you want to read the rows in it, you can implement a loop that loops the array:
$resultado= GetJobMembers("doctor");
foreach ($resultado as $row){
echo $row["job"].PHP_EOL;
}
Ok i fixxed it... was related to how php works with sql.
You just have to set fetch_all(MYSQLI_ASSOC);
Like this:
function GetJobMembers($jobL) { //Function to get all Members of an Job in an Array
global $db;
$AllWithJobSQL = $db->query("SELECT firstname FROM users WHERE job = '$jobL'");
$AllUsersWithJob = $AllWithJobSQL->fetch_all(MYSQLI_ASSOC);
return $AllUsersWithJob;
}
I think you are using wrong fetch method.Fetch, returning matched first row.
Your code should be like that:
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();
/* Fetch all of the remaining rows in the result set */
print("Fetch all of the remaining rows in the result set:\n");
$result = $sth->fetchAll();
print_r($result);
For more information you can check here
If you are using mysqli your code should be like that.
$AllWithJobSQL = $mysqli->query("SELECT firstname FROM users WHERE job = '$jobL'");
$AllUsersWithJob = $AllWithJobSQL ->fetch_all(MYSQLI_ASSOC);
return $AllUsersWithJob;

Php PDO request for data from the sum of a derived table column

Here is an SQL query that I am attempting to use in some php PDO code:
SELECT SUM(credit_hours) AS hours FROM(SELECT Course_List.credit_hours FROM Program_Courses, Course_List
WHERE program_id= :pid and concentration_id= :conid
and fulfills_major=1 and Program_Courses.course_id = Course_List.course_id ) AS major_credits
When I run this query on my database in SQL Workbench I get a derived table with a single column named
"hour" and a single row with the value 76 in it.
Here is the php code I'm using to try to get this same data stored in a variable $major_hours:
$result = $conn->prepare("SELECT * FROM students WHERE username = :un");
$result->bindParam(':un',$user);
$result->execute();
$data = $result->fetch(PDO::FETCH_ASSOC); //returns an associated array where the indices are the column names
$program = $data['program_id'];
$concentration = $data['concentration_id'];
//get the total number of credit hours in the student's major/concentration
$result = $conn->prepare("SELECT SUM(credit_hours) AS hours FROM(
SELECT Course_List.credit_hours FROM Program_Courses, Course_List
WHERE program_id= :pid and concentration_id= :conid
and fulfills_major=1 and Program_Courses.course_id = Course_List.course_id
) AS major_credits");
$result->bindParam(':pid',$program);
$result->bindParam(':conid',$concentration);
$result->execute();
$major_hours = $result->fetchColumn();
I know that the variables $user, $program, and $concentration all have legitimate values because when I echo those to the page, I get the correct result. However, echoing $major_hours gives absolutely nothing. What am I doing wrong?
Use fetch as you may guess it fetches the next row from a result set
The fetch_style parameter determines how PDO returns the row, in your case FETCH_ASSOC would be a good one since it returns an array indexed by column name as returned in your result set.
$row = $result->fetch(PDO::FETCH_ASSOC);//row is an associative array
$major_hours = $row['hours']; //access the column name hour
echo $majors_hours; //will print the hour value from db
I have not used sql workbench, but you may want to use isnull() or coalesce() on your SUM(credit_hours) expression. I think that should result in $major_hours showing 0.
Use this
$major_hours = $result->fetch(PDO::FETCH_ASSOC);
echo $majors_hours['hours'];
There is 2 way to return a data from database. fetch(PDO::FETCH_ASSOC) and fetchAll(PDO::FETCH_ASSOC). Fetch only return 1 row from database .. but fetchAll will return all row from the database query you make.
And (PDO::FETCH_ASSOC) it means will return the data with an array.

How to query all fields in a row

I know this is very simple, but I haven't used PHP/MySQL in a while and I have been reading other threads/php website and can't seem to get it.
How can I query a single row from a MySQL Table and print out all of the fields that have data in them? I need to exclude the NULL fields, and only add those that have data to an html list.
To clarify, I would like to display the field data without specifying the field names, just for the reason that I have a lot of fields and will not know which ones will be NULL or not.
What you've outlined requires 4 basic steps:
Connect to the database.
Query for a specific row.
Remove the null values from the result.
Create the html.
Step 1 is quite environment specific, so that we can safely skip here.
Step 2 - SQL
SELECT * from <tablename> WHERE <condition isolating single row>
Step 3 - PHP (assuming that $query represents the executed db query)
//convert the result to an array
$result_array = mysql_fetch_array($query);
//remove null values from the result array
$result_array = array_filter($result_array, 'strlen');
Step 4 - PHP
foreach ($result_array as $key => $value)
{
echo $value \n;
}
Just SELECT * FROM table_name WHERE.... will do the trick.
To grab data from specific fields, it would be SELECT field_1,field_2,field_3....
you have to make a string which represent mysql query. Then there is function in php named mysql_query(). Call this function with above string as parameter. It will return you all results. Here are some examples
You need to do it like this...
First connect to your sql... Reference
Now make a query and assign it to a variable...
$query = mysqli_query($connect, "SELECT column_name1, column_name2 FROM tablename");
If you want to retrieve a single row use LIMIT 1
$query = mysqli_query($connect, "SELECT column_name1, column_name2 FROM tablename LIMIT 1");
If you want to fetch all the columns just use * instead of column names and if you want to leave some rows where specific column data is blank you can do it like this
$query = mysqli_query($connect, "SELECT * FROM tablename WHERE column_name4 !=''");
Now fetch the array out of it and loop through the array like this..
while($show_rows = mysqli_fetch_array($query)) {
echo $show_rows['column_name1'];
echo $show_rows['column_name2'];
}
If you don't want to include the column names in the while loop, you could do this:
while($show_rows = mysqli_fetch_array($query)) {
foreach( $show_rows as $key => $val )
{
echo $show_rows[$key];
}
}

Checking if a value is in the db many times

I have a table A, with just two columns: 'id' and 'probably'. I need to go over a long list of ids, and determine for each one whether he is in A and has probability of '1'. What is the best way to do it?
I figured that it would be best to have 1 big query from A in the beginning of the script, and after that when I loop each id, I check the first query. but than i realized I don't know how to do that (efficiently). I mean, is there anyway to load all results from the first query to one array and than do in_array() check? I should mention that the first query should had few results, under 10 (while table A can be very large).
The other solution is doing a separate query in A for each id while I loop them. But this seems not very efficient...
Any ideas?
If you have the initial list of ids in array, you can use the php implode function like this:
$query = "select id
from A
where id in (".implode (',', $listOfIds).")
and probability = 1";
Now you pass the string as first parameter of mysql_query and receive the list of ids with probability = 1 that are within your initial list.
// $skip the amount of results you wish to skip over
// $limit the max amount of results you wish to return
function returnLimitedResultsFromTable($skip=0, $limit=10) {
// build the query
$query = "SELECT `id` FROM `A` WHERE `probability`=1 LIMIT $skip, $limit";
// store the result of the query
$result = mysql_query($query);
// if the query returned rows
if (mysql_num_rows($result) > 0) {
// while there are rows in $result
while ($row = mysql_fetch_assoc($result)) {
// populate results array with each row as an associative array
$results[] = $row;
}
return $results;
} else {
return false;
}
}
for each time you call this function you would need to increment skip by ten in order to retrieve the next ten results.
Then to use the values in the $results array (for example to print them):
foreach ($results as $key => $value) {
print "$key => $value <br/>";
}
Build a comma separated list with your ids and run a query like
SELECT id
FROM A
WHERE id IN (id1, id2, id3, ... idn)
AND probability = 1;
Your first solution proposal states that:
You will query the table A, probabyly using limit clause since A is a table with large data.
You will place the retrieved data in an array.
You will iterate through the array to look for the id's with probability of '1'.
You will repeat the first three steps several times until table A is iterated fully.
That is very inefficient!
Algorithm described above would require lots of database access and unneccessary memory (for the temporary array). Instead, just use a select statement with 'WHERE' clause and process with the data you want.
You need a query like the following I suppose:
SELECT id, probably FROM A WHERE A.probably = 1
If i understood you correctly, you should filter in the SQL query
SELECT * FROM A WHERE A.probably = 1

Read data from all rows in column PHP MySQL

I am doing some work that requires me to add the data from a specific column, say Column 1, to a PHP array. I can get the data from the first row in Column 1, but it stop there. How do I collect that columns data from every row in the table?
You have to loop over the result set in a while loop:
$result = mysql_query('SELECT...');
$data = array();
while(($row = mysql_fetch_array($result))) {
$data[] = $row['columnName'];
}
Every call to mysql_fetch_array will get the next row of the result set. If there is no row anymore, it will return null and the loop stops.
The documentation provides good examples.
Update:
Regarding duplicates: Either specify your SQL query correctly (preferred), e.g.
SELECT DISTINCT columnName FROM table
or use array_unique after you fetched all the data:
$data = array_unique($data);
//Variable declaration as a small sql query
$query = "select RowName FROM Table;";
//Execute Query
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result))
{
//Do Stuff
}

Categories