I have a array with this var_dump value:
$query = $wpdb->get_results("SELECT COUNT(*) FROM `$table` WHERE my mysql conditions");
var_dump($query); is this:
array(1) { [0]=> object(stdClass)#414 (1) { ["COUNT(*)"]=> string(3) "494" } }
How can I get the number 494 inside a variable?
$number = $query[0];
It'd be cleaner if you aliased your count so:
SELECT COUNT(*) AS `count`
then
$number = $query[0]->count;
If you only need to retrieve a single value, use $wpdb->get_var() instead of get_results(). This method exists specifically for situations like yours.
$number = $wpdb->get_var("SELECT COUNT(*) FROM `$table` WHERE my mysql conditions");
Related
I am using this command to get if the record already exist in the database;
$query = Yii::$app->db->createCommand("SELECT IF(EXISTS(SELECT * FROM `order_item`
WHERE `date` = '$date' AND `start_time` = '$starttime'), 1, 0)");
$result=$query->queryAll();
var_dump($result);exit;
Now the result I am getting for dump is like:
array(1) { [0]=> array(1) { ["IF(EXISTS(SELECT * FROM `order_item`
WHERE `date` = '2018-12-03' AND `start_time` = '10:15:00'), 1, 0)"]=> string(1) "0" } }
whereas I want the result as just 1 or 0
like
if ($result==1){
//do something;
}
as if I am running the same query in phpmyadmin - I am getting the result as 0 or 1
How I can achieve the same from the Query in Yii2.
queryAll() returns all fields from all rows as arrays. If you want to get single value from first field of first row, you need to use queryScalar().
$result = $query->queryScalar();
Before creating new post programmatically I want to check if there is a post with the same headline in my database.
I am checking that like this:
$results = $wpdb->get_results("SELECT COUNT(*) FROM $wpdb->posts WHERE post_type = 'candidates' AND post_title = '$name'");
Example of value I get when I var_dump($results):
array(1) { [0]=> object(stdClass)#85 (1) { ["COUNT(*)"]=> string(1) "8" } }
Now I want to get that string(1) "8", add it to variable and convert it to number, but I am not sure how to get it.
I tried something like
$number = (int)$results[0]->COUNT(*)
but that isn't right. I also tried some other combinations but couldn't figure it out
Your very problem is the (*) in $number = (int)$results[0]->COUNT(*). You cannot use these special characters simply as 'variable'. You're better off using a column alias using AS your_column_alias.
So you want to use
SELECT COUNT(*) as post_count FROM $wpdb->posts WHERE post_type = 'candidates' AND post_title = '$name'
as query and
$number = (int) $results[0]->post_count;
to fetch the aliased column from your resultset.
I have very limited to zero knowledge about SQL or DBs, so apologies in advance.
I am attempting to make a table like structure within a webpage, a column for meal name, and a column for ingredients - it is also searchable via a button.
EDIT:
Thanks for all the replies, they have been most helpful.
The error no longer happens, however now I get no results from the database, but no error.
include("inc/dbConn.php"); /////$db_conx
if(isset($_POST["search"])){
$searchq = $_POST["search"];
$sql ="
SELECT main_meal.name, ingred.name
FROM main_meal
JOIN meal_ingred on meal_ingred.meal_id = main_meal.id
JOIN ingred ON ingred.id = meal_ingred.ingred_id
WHERE ingred.name LIKE '%$searchq%'";
$results = $db_conx->query($sql);
var_dump($results);
if($results->num_rows){
while ($row =$results->fetch_object()){
echo "{$row->name} ({$row->name})<br>";
}
}
}
For clarification here is my structure:
(Sorry for external link, I dont have enough reputation to post images.)
http://i30.photobucket.com/albums/c340/Tyrage/Untitled-2_zpsc48126b3.png
The $results dumps:
object(mysqli_result)#2 (5) { ["current_field"]=> int(0) ["field_count"]=> int(2) ["lengths"]=> NULL ["num_rows"]=> int(0) ["type"]=> int(0) }
It is quite obvious I don't have a clue what I am doing, so any help is appreciated.
Thanks.
you're lacking a relation table here, which will store connection between meals and ingredients.
also you had error in your query because at first you've tried to use a/b naming correctly, to name a column, and then you user it to name a table.
IMHO you should do something like this (with relation table added):
if(isset($_POST["search"])){
$searchq = $_POST["search"];
$sql ="
SELECT main_meal.name AS a, ingred.name as b
FROM main_meal
JOIN rel_meal_ingred on rel_meal_ingred.meal_id = main_meal.id
JOIN ingred ON ingred.id = rel_meal_ingred.ingred_id
where ingred.name LIKE '%$searchq%'";
$results = $db_conx->query($sql);
if($results->num_rows){ //////line 15
while ($row =$results->fetch_object()){
echo "{$row->a} ({$row->b})<br>";
}
}
}
You could try this?
SELECT *
FROM main_meal
JOIN meal_ingred ON meal_ingred.meal_id = main_meal.id
JOIN ingred ON meal_ingred.meal_id = main_meal.id
WHERE ingred.ingredName LIKE '%bread%'
LIMIT 0 , 30
with the php as follow:
<?php
if(isset($_POST["search"])){
$searchq = $_POST["search"];
$sql ="
SELECT *
FROM main_meal
JOIN meal_ingred ON meal_ingred.meal_id = main_meal.id
JOIN ingred ON meal_ingred.meal_id = main_meal.id
WHERE ingred.ingredName LIKE '%$searchq%'
LIMIT 0 , 30
";
//$results = $db_conx->query($sql);
if (!$results = $db_conx->query($sql)) {
printf("Error: %s\n", $db_conx->error);
}
$count = $results->num_rows;
if($count > 0){
while($row=$results->fetch_assoc()){
echo $row['ingredName'];
echo $row['name'] . "<br />";
$output="ff";
}
}
}
?>
Line numbers would help, to see if line 15 is the assignment to $results, or if line 15 is the $results->num_rows
I'm also assuming you have a $db_conx->connect command somewhere in your code, to open the database connection before running the query?
Your SQL query is invalid: there is no such column as ingred.name available in the WHERE clause, because you have renamed that table as b.
There is no reason to rename your tables (using AS ...) in this query. Leave that clause out. Then add a join condition (e.g, ... JOIN ingred ON (...) — omitting this will make the query return every row from main_meal.
Additionally, there is probably a SQL injection vulnerability in your code, because you are interpolating the contents of the (likely unfiltered) $searchq variable into the query. Use a query placeholder for the argument to LIKE.
How can I get this value from DB as string or int?
PHPMyAdmin http://img200.imageshack.us/img200/6388/gr55.jpg
I've tried this:
$var = $this->db->query("SELECT SUBSTRING(`category_id`, 1, 3)
AS `category_id` FROM " . DB_PREFIX . "category
WHERE merlion_id = 'Q1'
ORDER BY category_id ASC");
And then I've checked it with var_dump and receive this:
var_dump($var);
object(stdClass)#26 (3) { ["row"]=> array(1) { ["category_id"]=> string(3) "859" } ["rows"]=> array(1) { [0]=> array(1) { ["category_id"]=> string(3) "859" } } ["num_rows"]=> int(1) }
No need to do SUBSTRING:
$var = $this->db->query("`category_id`FROM " . DB_PREFIX . "category
WHERE merlion_id = 'Q1'
ORDER BY category_id ASC");
Then, you have it, you don't "convert" the object, you take what you need from it:
$category_id = $var->row["category_id"];
I suggest you dive into basic PHP before you continue with your database-driven application. This is all trivial stuff. There are many good tutorials out there, also about PHP object oriented programming. Most notably the PHP documentation site.
How about this:
echo $var->row['category_id'];
You can also simplify your query:
$var = $this->db->query("SELECT `category_id`
AS `category_id` FROM `" . DB_PREFIX . "category`
WHERE merlion_id = 'Q1'
LIMIT 1");
Added backticks around the table name
Removed your ORDER clause. You do not need it if you only have one dataset whose *merlion_id* is Q1.
Added LIMIT clause since you only want one dataset.
Am try to looping through a database result set, the problem is that i know i have only one row of data, yet the loop returns 5 rows
This is my method from my model
function get_latest_pheeds() {
$data = $this->user_keywords($this->ion_auth->user_id);
$keyword = $data;
$user_id = $this->ion_auth->user_id;
foreach($keyword as $key => $word) {
$q = "SELECT *,COUNT(pheed_comments.comment_id) as comments
FROM pheeds
LEFT JOIN pheed_comments ON pheed_comments.P_id=pheeds.pheed_id
WHERE pheed LIKE '%$word%' OR user_id='$user_id'
GROUP BY pheeds.pheed_id
ORDER BY datetime DESC";
$result = $this->db->query($q);
$rows[] = $result->result();
}
return $rows;
}
What am i doing wroing
This is because your query has an OR where it should probably have an AND - each query always matches the user_id='$user_id'.
This loop is quite inefficient anyway, I think you want to do something more like this:
function get_latest_pheeds() {
$keywords = $this->user_keywords($this->ion_auth->user_id);
$q = "SELECT *,COUNT(pheed_comments.comment_id) as comments
FROM pheeds
LEFT JOIN pheed_comments ON pheed_comments.P_id=pheeds.pheed_id
WHERE (pheed LIKE '%".implode("%' OR pheed LIKE '%",$keywords)."%') AND user_id='".$this->ion_auth->user_id."'
GROUP BY pheeds.pheed_id
ORDER BY datetime DESC";
return $this->db->query($q);
}
If you want your results returned as an array like they were previously, you'll need to loop over results and fetch each of them into an array key of another array. I can't do it here because I can't see your db class...
EDIT: Slight fix in the above code...
ANOTHER EDIT: another fix...