Accessing data for SQL object inner join - sql

I am trying to get this inner join to show output the the title and date. Is only returning the sql object that gives details on object. this is result. I can access num_rows but just gives me int(11) for the number of records, don't know how to access the info in the fields.
This is the result.
object(mysqli_result)#6 (5) { ["current_field"]=> int(0) ["field_count"]=> int(2) ["lengths"]=> NULL ["num_rows"]=> int(11) ["type"]=> int(0) }
Thanks for help.
$sql = "SELECT title, artist_name";
$sql .= " FROM follows";
$sql .= " INNER JOIN artworks";
$sql .= " ON follows.user_id_followed = artworks.artist_id";
$sql .= " AND follows.user_id_follower='12'";
$result_set = $database->query($sql);
echo var_dump($result_set);

you need a WHERE
$sql = "SELECT title, artist_name";
$sql .= " FROM follows";
$sql .= " INNER JOIN artworks";
$sql .= " ON follows.user_id_followed = artworks.artist_id";
$sql .= " WHERE follows.user_id_follower='12'";
You also probably want LEFT JOIN not INNER JOIN`

Related

WPDB query what is the cleanest method for a double query?

I am curious as to how best achieve this.
wpdb query 1:
$results = $wpdb->get_results(
"SELECT *
FROM $table_name
WHERE user_id = '$userid';"
);
I then want to do another wpdb query on a separate table using $results->post_id in the WHERE part of the query such as:
$results2 = $wpdb->get_results(
"SELECT *
FROM $table_name2
WHERE user_id = '$results->post_id' && type = '$type';"
);
I am conscious that $results will be an array so I don't think the above will work directly and some sort of compound "for each" seems cumbersome.
What are my options please?
Update example based on Jarlh's comment
$userid = get_current_user_id();
global $wpdb;
$table_name = $wpdb->prefix . 'postmeta';
$table2_name = $wpdb->prefix . 'posts';
$rewards_results = $wpdb->get_results(
"SELECT *
FROM $table_name
WHERE post_id in ("SELECT user_id
FROM $table2_name
WHERE user_id = '$userid';")"
);
Update 2:
$userid = get_current_user_id();
global $wpdb;
$table_name = $wpdb->prefix . 'postmeta';
$table2_name = $wpdb->prefix . 'posts';
$results = $wpdb->get_results(
"SELECT *
FROM $table_name
WHERE ID in (SELECT user_id
FROM $table2_name
WHERE user_id = '$userid')"
);
//return $results;
foreach ($results as $row) {
echo "<td class='dash-2-td'>" . esc_html($row->logo_id) . "</td>";
echo "<td class='dash-2-td'>" . esc_html($row->belongs_to) . "</td>";
echo "</tr>";
}
This is producing no output.
I need to search $table_name->post_id for rows that match $table2_name->ID where user_id = $userid
Update 3: print_r is just showing array(), seems empty
$userid = get_current_user_id();
global $wpdb;
//$table_name = $wpdb->prefix . 'postmeta';
//$table2_name = $wpdb->prefix . 'posts';
$results = $wpdb->get_results(
"SELECT $wpdb->posts.*
FROM $wpdb->posts, $wpdb->postmeta
WHERE $wpdb->posts.ID = $wpdb->postmeta.post_id
AND $wpdb->posts.post_author = $userid
AND $wpdb->postmeta.plan = 3981
");
return $results;
I ended up using wp_query which I had not even considered as an option.
As a solution, you can use INNER JOIN. Also, I'd suggest you to use $wpdb->prepare for escaping values. Here is an example:
$sql = $wpdb->prepare( "SELECT a.*, b.col1, b.col2 FROM $table1 as a INNER JOIN $table2 as b ON a.user_id = b.user_id WHERE a.user_id = %d AND b.type = %s", $user_id, $type );
$entries = $wpdb->get_results( $sql, ARRAY_A );
Hope it helps.

Laravel5.2 SQL builder test condition to where query

I do search function In raw SQL like this
//test condition variable
if ($param_type != "") {
if($param_type =='SAS'){
$str .= " AND pos.type IN('SAS1','SAS2') ";
}
else if($param_type =='SME'){
$str .= " AND pos.type IN('SME1','SME2') ";
}
else if($param_type =='PT'){
$str .= " AND pos.type IN('PT','PT0') ";
}else{
$str .= " AND pos.type ='$param_type'";
}
}
//SQL
$query =" SELECT * FROM tbl_user AS u INNER JOIN tbl_position AS pos
ON u.user_id = pos.user_id where u.levels IN ('7','8','9') .$str ;" ;
How I can write SQL like this in laravel ?
You can use raw query.
$query = DB::select(SELECT * FROM tbl_user AS u INNER JOIN tbl_position AS pos
ON u.user_id = pos.user_id where u.levels IN ('7','8','9') .$str ;");
Of course then you need to add at the top in your controller use DB;
Anyway Raw queries may be dangerous and it's better to use query builder.
Simple example:
$query = DB::table('tbl_user')
->join('tbl_position','tbl_user.user_id','=','tbl_position.user_id')
->where('something','=','something')
->get();
Query builder: query builder
Reply to my question for who meet problem like me:
Example like this
$query = DB::table('user');
if ($param_type =='PT')
$query->where('pos.type', '=', 1);
}
$result = $query->get();

same table same field with same field conditions - Possible? in one sql

here is my query i want to execute it as
$query="select * from $post INNER JOIN $postmeta on $postmeta.post_id= $post.ID
where $post .post_status='publish'
and $post .post_type ='task
and $post .post_type='service'
ORDER BY $post .post_date DESC ";
how to execute
Previous a proper sanitize of the var $postmeta and $post you can do this way
Building dinamic query by string concantenation (because var in tabel and column name are not allowed in sql)
$query="select * from " . $post . " INNER JOIN " .
$postmeta . " on " . $postmeta . ".post_id= " . $post .".ID where " .
$post . ".post_status='publish' and " . $post .".post_type ='task' and " .
$post . "post_type='service' ORDER BY " . $post .".post_date DESC ";

What is wrong here? Sql query give me an error 1146 [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I am trying to use all columns for each row from one table (party), and some columns from another (customer).
Ok, here is my code
public function getParty($data = array()) {
$sql = "SELECT party.* , customer.customer_id AS customerID, customer.firstname AS customerFN, customer.lastname AS customerLN, customer.email AS customerEMAIL, customer.ip AS cutomerIP
FROM `" . DB_PREFIX . "party`
JOIN `" . DB_PREFIX . "cutomer`
ON party.cutomer_id = customer.customer_id
WHERE status=3";
$sort_data = array(
'date_added',
'order_id',
'customer_id',
'customerFN',
'customerLN',
'customerEMAIL',
'customerIP',
'description',
'status',
'amount'
);
if (isset($data['sort']) && in_array($data['sort'], $sort_data)) {
$sql .= " ORDER BY " . $data['sort'];
} else {
$sql .= " ORDER BY date_added";
}
if (isset($data['order']) && ($data['order'] == 'DESC')) {
$sql .= " DESC";
} else {
$sql .= " ASC";
}
if (isset($data['start']) || isset($data['limit'])) {
if ($data['start'] < 0) {
$data['start'] = 0;
}
if ($data['limit'] < 1) {
$data['limit'] = 20;
}
$sql .= " LIMIT " . (int)$data['start'] . "," . (int)$data['limit'];
}
$query = $this->db->query($sql);
return $query->rows;
}
And here is the error
Notice: Error: Table 'XXX.cutomer' doesn't exist
Error No: 1146
SELECT party.* , customer.customer_id AS customerID, customer.firstname AS customerFN, customer.lastname AS customerLN, customer.email AS customerEMAIL, customer.ip AS cutomerIP FROM `party` JOIN `cutomer` ON party.cutomer_id = customer.customer_id WHERE status=3 ORDER BY date_added ASC LIMIT 0,10 in /srv/www/htdocs/XXX/system/database/mysql.php on line 49
Maybe I am wrong somewhere, but do not see it
Greetings
Petar Stoyanov
JOIN `" . DB_PREFIX . "cutomer`
Should be
JOIN `" . DB_PREFIX . "customer`
?
Also...
ON party.cutomer_id = customer.customer_id
Should be
ON party.customer_id = customer.customer_id
?
I would search for all instances of cutomer and replace them with customer.
I think it should be
ON party.customer_id = customer.customer_id
instead of
ON party.cutomer_id = customer.customer_id
Please change from
JOIN `" . DB_PREFIX . "cutomer`
To
JOIN `" . DB_PREFIX . "customer`
Ex:
FROM `" . DB_PREFIX . "party`
JOIN `" . DB_PREFIX . "customer`
ON party.cutomer_id = customer.customer_id
WHERE status=3";
Change your SQL stmt to this:
$sql = "SELECT party.* , customer.customer_id AS customerID, customer.firstname AS customerFN, customer.lastname AS customerLN, customer.email AS customerEMAIL, customer.ip AS customerIP
FROM `" . DB_PREFIX . "party`
JOIN `" . DB_PREFIX . "customer`
ON party.customer_id = customer.customer_id
WHERE status=3";

SQL query with AND/OR logical operators

fI have what seems to be a relatively simple AND/OR clause that is giving me a bit of a headache.
$query = "SELECT stv.name,stc.tmplvarid,stc.contentid,stv.type,stv.display,stv.display_params,stc.value";
$query .= " FROM ".$tb1." stc LEFT JOIN ".$tb2." stv ON stv.id=stc.tmplvarid ";
$query .= " LEFT JOIN $tb_content tb_content ON stc.contentid=tb_content.id ";
$query .= " WHERE stv.name='".$region."' AND stc.contentid IN (".implode($cIDs,",").") ";
$query .= " OR stv.name='".$countries."' AND stc.contentid IN (".implode($cIDs,",").") ";
$query .= " AND tb_content.pub_date >= '$pub_date' ";
$query .= " AND tb_content.published = 1 ";
$query .= " ORDER BY stc.contentid ASC;";
I need it to retrieve the values from both $region and $countries. However, the way it is it only returns the value of $countries. If I remove the line with the OR it returns the value of $region, but it won't return both. What am I doing incorrectly?
Try putting brackets around the clauses on either side of the OR. See below:
$query = "SELECT stv.name,stc.tmplvarid,stc.contentid,stv.type,stv.display,stv.display_params,stc.value";
$query .= " FROM ".$tb1." stc LEFT JOIN ".$tb2." stv ON stv.id=stc.tmplvarid ";
$query .= " LEFT JOIN $tb_content tb_content ON stc.contentid=tb_content.id ";
$query .= " WHERE (stv.name='".$region."' AND stc.contentid IN (".implode($cIDs,",").")) ";
$query .= " OR (stv.name='".$countries."' AND stc.contentid IN (".implode($cIDs,",").")) ";
$query .= " AND tb_content.pub_date >= '$pub_date' ";
$query .= " AND tb_content.published = 1 ";
$query .= " ORDER BY stc.contentid ASC;";
Looks like you are missing parentheses, no?
A or B and C or D is ambiguous, you need to use parentheses to make it clear you mean (A or B) and (C or D)