Right now I'm trying to set a variable from an SQL response without doing it more than necessary.
The situation is I have a SQL result from a SELECT + JOIN query with a user_id column that has only a single value. The other columns are different per row and I need to loop through them for that data. I was wondering if there was a way to extract the homogeneous value from the user_id column without setting it over and over again to a variable in my while loop.
Code:
#where I would like the $user_id to be set
while($responseArray = $response->fetch_assoc()){
$userId = $responseArray["user_id"]; #what I don't want to do
#other fetching stuff
}
SQL:
SELECT users.username, users.user_id, posts.post_id, posts.post_content, posts.number_comments, comments.comment_id, comments.comment_post_id
FROM users
JOIN posts
JOIN comments
WHERE delete_bit = 0 AND username = "john";
You cannot get away from fetching at least one result row. Even the fetchOne()-type functions do this. But if you only want a single row, why even bother using a loop in the first place?
$result = $db->query(...);
$row = $result->fetchRow();
$value = $row['somefield'];
would be far better than something silly like
$result = $db->query(...);
while($row = $result->fetchRow()) {
$value = $row['somefield'];
break;
}
Related
I've two tables, users and coach_to_trainee. User can have multiple coaches, and the data is stored in coach_to_trainee columns coach_id and trainee_id.
I'm using coach_to_trainee table to print out data for the user, so he/she can simply see who is his/her coach.
<?php
$user = $_SESSION['login']['id'];
$q = "SELECT * FROM coach_to_trainee WHERE trainee_id='$user'";
$coachid = $db->prepare($q);
$coachid->execute();
while($row = $coach->fetchObject()){
$coachid = $row->coach_id;
echo '<li>'.INSERT_COACH_NAME.'</li>';
}
?>
However, this will only return the ID of the coach, and I need to return the name also, from table users.
How I'm supposed to do another query inside while() and use $coachid to find the correct user?
You have to use JOIN mysql clause, like this one:
SELECT u.name, u.id
FROM users u
LEFT JOIN coach_to_trainee ctt
ON u.id = ctt.coach_id
WHERE ctt.trainee_id = {$user}
You should be done with this one ;-)
Then in Your PHP use the selected values:
while($row = $coach->fetchObject()){
echo '<li>'.$row->name.'</li>';
}
I have a table (wp_postmeta), which contains four columns (meta_id, post_id, meta_key, meta_value). meta_key contains a field called neighborhood_value and the values for neighborhood_value are stored under the meta_value column. How do I retrieve the contents of neighborhood_value from my table and use them as a variable? Any support is appreciated
Ok, as everything is meta, thecode will also be "meta" :)
UPDATE - now when I know what you use to connect to DB I can change my answer to be more specific.
global $wpdb;
$sql = "SELECT meta_key, meta_value FROM $wpdb->postmeta WHERE post_id=XXX";
$retMeta = array();
$results = $wpdb->get_results($sql);
foreach ($results as $resultRow)
{
if (!isset($retMeta[$resultRow['meta_key']]))
{
$retMeta[$resultRow['meta_key']] = array();
}
$retMeta[$resultRow['meta_key']][] = $resultRow['meta_value'];
}
The resulting $retMeta will be two dimensional array, and then you will be able to access your neighbourhood value by using $retMeta['neighbourhood_value'][0] (of course first you have to check if this is set - isset($retMeta['neighbourhood_value'])).
UPDATE2
For script imporing data, it'll look like that:
$sql = "SELECT meta_key, meta_value FROM wp_postmeta WHERE post_id=XXX";
$retMeta = array();
$result = mysql_query($sql);
while ($resultRow= mysql_fetch_assoc($result))
{
if (!isset($retMeta[$resultRow['meta_key']]))
{
$retMeta[$resultRow['meta_key']] = array();
}
$retMeta[$resultRow['meta_key']][] = $resultRow['meta_value'];
}
mysql_free_result($result);
But you should use WP_Query anyway, to maintain portability (the wp_postmeta doesn't have to be named that way, it can be wp2_postmeta etc).
If I understand correctly, you want to key a list of keys from meta_value?
I would do this in php: (assuming you are using some sort of framework that supports this construct. This example works with the codeigniter framework))
$sql = "SELECT distinct meta_value FROM wp_postmeta"
$result = $db->query($sql)
foreach ($result->reult() as $row) {
$mydata[] = $row->meta_value;
}
$mydata is now array containing all of your meta_value values.
I was doing same as the following.
<?php foreach($values as $value)
{
$myVarname[$value[valuefield]]=$value[valuefield];
}
$myVarname[field1]="Cow";
$myVarname[field2]="dog";
?>
If you're working with Wordpress template files such as loop.php etc., just use the handy get_post_meta() function.
You don't specify what language you want to use for your variables - but if it happens to be SQL in MySQL, here's how you "Retrieve Value From MySQL Table and Save in Variable":
select #var_name := column_name from table_name where other_column = 5;
This does the select, and as a side-effect assigns the value of the user variable #var_name to the value of column_name.
or
select #var_name := count(*) from other_table where other_column > 5;
which sets #var_name to the number of records that matched the condition.
I have the following 3 tables in the database.
Programs_Table
Program_ID (Primary Key)
Start_Date
End_Date
IsCompleted
IsGoalsMet
Program_type_ID
Programs_Type_Table(different types of programs, supports a dropdown list in the form)
Program_type_ID (Primary Key)
Program_name
Program_description
Client_Program_Table
Client_ID (primary key)
Program_ID (primary key)
What is the best way to find out how many clients are in a specific program (program type)?
Would the following SQL statement be the best way, or even plausible?
SELECT Client_ID FROM Client_Program_Table
INNER JOIN Programs_Table
ON Client_Program_Table.Program_ID = Programs_Table.Program_ID
WHERE Programs_Table.Program_type_ID = "x"
where "x" is the Program_type_ID of the specific program we're interested in.
OR is the following a better way?
$result = mysql_query("SELECT Program_ID FROM Programs_Table
WHERE Program_type_ID = 'x'");
$row = mysql_fetch_assoc($result);
$ProgramID = $row['Program_ID'];
$result = mysql_query("SELECT * FROM Client_Program_Table
WHERE Program_ID = '$ProgramID'");
mysql_num_rows($result) // returns how many rows of clients we pulled.
Thank you in advance, please excuse my inexperience and any mistakes that I've made.
Here is how you can do it:
<?php
// always initialize a variable
$number_of_clients = 0;
// escape the string which will go in an SQL query
// to protect yourself from SQL injection
$program_type_id = mysql_real_escape_string('x');
// build a query, which will count how many clients
// belong to that program and put the value on the temporary colum "num_clients"
$query = "SELECT COUNT(*) `num_clients` FROM `Client_Program_Table` `cpt`
INNER JOIN `Programs_Table` `pt`
ON `cpt`.`Program_ID` = `pt`.`Program_ID`
AND `pt`.`Program_type_ID` = '$program_type_id'";
// execute the query
$result = mysql_query($query);
// check if the query executed correctly
// and returned at least a record
if(is_resource($result) && mysql_num_rows($result) > 0){
// turn the query result into an associative array
$row = mysql_fetch_assoc($result);
// get the value of the "num_clients" temporary created column
// and typecast it to an intiger so you can always be safe to use it later on
$number_of_clients = (int) $row['num_clients'];
} else{
// query did not return a record, so we have no clients on that program
$number_of_clients = 0;
}
?>
If you want to know how many clients are involved in a program, you'd rather want to use COUNT( * ). MySQL (with MyISAM) and SQL Server have a fast way to retrieve the total number of lines. Using a SELECT(*), then mysql_num_rows leads to unnecessary memory ressources and computing time. To me, this is the fastest, though not the "cleanest" way to write the query you want:
SELECT
COUNT(*)
FROM
Client_Program_Table
WHERE
Program_ID IN
(
SELECT
Program_ID
FROM
Programs_Table
WHERE
Program_type_ID = 'azerty'
)
Why is that?
Using JOIN make queries more readable, but subqueries often prove to be computed faster.
This returns a count of the clients in a specific program type (x):
SELECT COUNT(cpt.Client_ID), cpt.Program_ID
FROM Client_Program_Table cpt
INNER JOIN Programs_Table pt ON cpt.Program_ID=pt.Program_ID
WHERE pt.Program_type_ID = "x"
GROUP BY cpt.Program_ID
I need to select category ids from my sql database.
I have a variable $product_id and for each product id there are three rows in a table that i need to select using PHP.
If I do "SELECT * FROM table_name WHERE product_id='$prodid'"; I only get the one on the top.
How can I select all three category_ids which contain the same product_id?
I suppose you are using PHP's mysql functions, is this correct? I am figuring that your query is actually returning all three rows but you aren't fetching all of them.
$sql = "SELECT * FROM table_name WHERE product_id='$prodid'";
$r = mysql_query($sql, $conn); //where $conn is your connection
$x = mysql_fetch_SOMETHING($r); //where something is array, assoc, object, etc.
The fetch function gives only one row at a time. You say you need three so it needs to be executed three times.
$x[0] = mysql_fetch_assoc($r);
$x[1] = mysql_fetch_assoc($r);
$x[2] = mysql_fetch_assoc($r);
OR this would be better
while($curRow = mysql_fetch_assoc($r)) //this returns false when its out of rows, returns false
{
$categoryIds[] = $curRow['category_id'];
}
If this doesn't do it then your query is actually returning only one row and we need to see your tables/fields and maybe sample data.
SQL seems to be correct, but Why do you store product_id in categories table? if it's one-to-many relation it would be better to store only category_id in products table.
The SQL query is correct for what you want to do. It will select all the records in table_name with the field product_id = $prodid (not only 1 or 3 but any that matches the variable)
To select a few records you should use the LIMIT keyword
You should look inside your table structure and the variable $prodid to find problems.
I have a while loop of a mysql call but I also am trying to run another mysql query inside of the while loop but it is only doing it once. I can not figure it out.
Here is my code:
$sql = "SELECT * FROM widget_layout WHERE module_id=".mysql_real_escape_string($id)." AND state='".mysql_real_escape_string($page)."' AND position=".mysql_real_escape_string($position);
$query = mysql_query($sql);
while ($row = mysql_fetch_assoc($query)) {
$layout .= $row['widget_id'].'<br/>'; //test if it is looping through all rows
$sql2 = "SELECT title FROM widgets WHERE id=".$row['widget_id'];
$query2 = mysql_query($sql2);
$result2 = mysql_fetch_array($query2);
$layout .= $result2[0]; // test the title output
}
It is looping through the first query no problem but the second query is only load the title of the first widget, return null for the rest. Any idea of why this is doing this?
You don't have to use a WHILE loop -- this can be done in a single SQL statement:
SELECT wl.widget_id,
w.title
FROM WIDGET_LAYOUT wl
JOIN WIDGETS w ON w.id = wl.widget_id
WHERE wl.module_id = mysql_real_escape_string($id)
AND wl.state = mysql_real_escape_string($page)
AND wl.position = mysql_real_escape_string($position);
The issue with NULL title values depends on if the WIDGET.title column is NULLable, or there isn't a record in the WIDGETS table for the id value. You need to check the values coming back from the first query, confirm they have supporting records in the WIDGETS table first, then look at the title value...
Directly from the mysql_query() docs: multiple queries are not supported. Your innery query is killing the outer one.