I have something like that in my mySQL database:
(User 734 have many informations : biography, name, phone, mail ...)
I want to get an array (in PHP) with grouped datas :
array(
[734]=>
object {
[155] => string "Dominique",
[4] => int(047682037),
[1] => string "Dominique B"
},
[735]=>
object {
[155] => string "Other",
[4] => int(0123456789),
[1] => string "Other B"
}
)
not only for 734 user but for each user. With a simple query I get everything but not in the good order. Can I make it in SQL or I maybe need to rearrange datas in PHP next ?
What is the sql query to get, for each user_id, all the related datas ?
I can't change the database structure (WP and buddypress)
I can't use native WP functions (because getting datas from another site)
SELECT * FROM (whatever your table name is)
WHERE user_id = (whatever user id you're interested in getting data for)
Solution using ORDER BY :
$users = array();
$current_user = null;
$result = $mysqli->query("SELECT user_id, field_id, value FROM `TABLE_NAME` ORDER BY user_id, field_id");
while ($result && $row = $mysqli->fetch_assoc($result)) {
if ($current_user != $row['user_id']) {
$current_user = $row['user_id'];
$users[$row['user_id']] = array();
}
$users[$row['user_id']][$row['field_id']] = $row['value'];
}
EDIT :
There is another solution using GROUP BY and GROUP_CONCAT :
$users = array();
$result = $mysqli->query("SELECT user_id, GROUP_CONCAT(field_id SEPARATOR '|') as fields, GROUP_CONCAT(value SEPARATOR '|') as values FROM `TABLE_NAME` GROUP BY user_id");
while ($result && $row = $mysqli->fetch_assoc($result)) {
$fields = explode('|', $row['fields']);
$values = explode('|', $row['values']);
$users[$row['user_id']] = array();
// Problem id you have your field ids and your values in separate arrays, not sure what you want to do with them
}
$result = mysqli_query($con, "SELECT * FROM table_name WHERE user_id = 734");
Or if you arent using mysqli:
$result = mysql_query("SELECT * FROM table_name WHERE user_id = 734");
If you are using the PDO library you could check the PDO::FETCH_GROUP attribute.
http://php.net/manual/en/pdostatement.fetchall.php
fetch_style:
To return an associative array grouped by the values of a specified column, bitwise-OR PDO::FETCH_COLUMN with PDO::FETCH_GROUP.
$stmt = $this->_mysqli->prepare('SELECT user_id,field_id,value FROM WHERE user_id = ?');
$stmt->bind_param('i', $user_id );
$stmt->execute();
$stmt->bind_result($user_id, $field_id, $value);
while($stmt->fetch())
{
$data[$user_id][$field_id] = $value;
}
Related
I'm trying to create an array from the results of 2 queries, and send it all together to front-end, but I'm stuck to the point where I need to push the results of the second query to the array, I tried to do it using array_push but doesn't work.
Let's say we have this example, and I need to include the results of $query2 to $return_arr
Any ideas?
<?php
header('Access-Control-Allow-Origin: *');
include "config.php";
$return_arr = array();
$query1 = "SELECT * FROM balance WHERE class='income' ORDER BY id DESC";
$query2 = "SELECT * FROM balance WHERE class='expense' ORDER BY id DESC";
$result1 = mysqli_query($conn,$query1);
while($row = mysqli_fetch_array($result1)){
$id = $row['id'];
$description = $row['description'];
$date = $row['date'];
$euro = $row['euro'];
$who = $row['who'];
$class = $row['class'];
$return_arr[] = array("id_income" => $id,
"description_income" => $description,
"date_income" => $date,
"euro_income" => $euro,
"who_income" => $who,
"class_income" => $class
);
}
// Encoding array in JSON format
echo json_encode($return_arr);
Here's a different query:
SELECT *
FROM balance
WHERE class IN('income','expense')
ORDER
BY class
, id DESC
Like JS Bach answer. But maybe you could speed up performance by mention the column's name.
SELECT column1, column2, column3 FROM balance WHERE class IN ('income','expense') ORDER BY class, id DESC;
You can also make use of OR operator
$query = SELECT * FROM balance WHERE class = "income" OR class = "expense" ORDER BY class, id DESC;
$result = mysqli_query($conn,$query);
$array = mysqli_fetch_array($result,MYSQLI_ASSOC);
Your fetched records will already be in an array format in $array
This can be more effective when dealing with tables having records in 1000s of rows
I want to select records from two tables. These two tables have the prefix "shop_".
How do I select the records for both shops in a sql statement?
My current statement:
// Select
$stmt = $mysqli->prepare("SELECT name, html_id, price FROM database_name WHERE TABLE_NAME LIKE 'shop%'");
$stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_assoc())
{
$arr[] = $row;
}
$name = [];
foreach($arr as $arrs)
{
$name[] = array(0 => $arrs['name'], 1 => $arrs['html_id'], 2 => $arrs['price']); //here
}
$stmt->close();
print_r($name);
The mysql php current error is:
Fatal error: Uncaught Error: Call to a member function execute() on boolean in C:\wamp642\www\webcart\search.php on line 17 and line 17 is: $stmt->execute();
I can get the tables to "show" with this command:
$stmt = $mysqli->prepare("show tables like '%shop%'");
But it doesn't get the records, just an object I think.
The output of "show tables like '%shop%'" prints 2 arrays just like it should, but the arrays are empty with no data/records.
I'm thinking it's the sql statement that needs work. Thanks.
EDIT:
I've also tried:
$stmt = $mysqli->prepare("SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA='feeds' AND TABLE_NAME LIKE 'shop%'");
EDIT: The contents of search.php
<?php
include 'define.php';
$mysqli = new mysqli($host, $db_user, $db_password, $db_database);
if($mysqli->connect_error)
{
?><script>var profiles_delete_modal_1 = ' Error 3: Problem deleteing profile. Make sure database login credentials are correct.';</script>
<script>$(".modal").css({"opacity":"1", "z-index":"100"});$(".modal_mid").html("<pre>" + profiles_delete_modal_1 + "</pre>");setTimeout(function(){$(".modal").css({"opacity":"0", "z-index":"-100"});},5000);</script><?php
exit;
}
$shop = 'shop';
// Select
//$stmt = $mysqli->prepare("show tables like '%shop%'");
//$stmt = $mysqli->prepare("SELECT * FROM feeds WHERE TABLE_NAME LIKE 'shop%'");
$stmt = $mysqli->prepare("SELECT name, html_id, price FROM database_name WHERE TABLE_NAME LIKE 'shop%'");
$stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_assoc())
{
$arr[] = $row;
}
$n=0;
$name = [];
foreach($arr as $arrs)
{
$name[] = array(0 => $arrs['name'], 1 => $arrs['html_id'], 2 => $arrs['price']); //here
$n++;
}
$stmt->close();
print_r($name);
and the contents of define.php:
$www_dir = 'webcart';
$url_root = 'http://localhost/' . $www_dir . '';
$www_dir_slash = $_SERVER['DOCUMENT_ROOT'] . '' . $www_dir . '/';
$host = 'localhost';
$db_user = 'webcart_admin';
$db_password = 'asd123';
$db_database = 'shop';
$_SESSION['host'] = $host;
$_SESSION['db_user'] = $db_user;
$_SESSION['db_password'] = $db_password;
$_SESSION['db_database'] = $db_database;
EDIT
From going on the answer stated below I've been able to create a string like this:
SELECT name, html_id, price FROM shop_a UNION shop_b
however it won't execute properly.
This is my code:
$stmt = $mysqli->prepare("SELECT name, html_id, price FROM shop_a UNION shop_b");
$result = $stmt->execute();
It gives the following error:
Fatal error: Uncaught Error: Call to a member function execute() on boolean in C:\wamp642\www\webcart\search.php on line 43
EDIT Got it.
I'll post the answer up soon. The statement goes like this:
"SELECT name, html_id, price FROM shop_a UNION SELECT name, html_id, price from shop_b"
I got the answer pretty much from musafar, although I needed to get to the objects in the array. So I used some foreach loops to do this seeing as I don't know any other way. If there's another way to get to mysqli_object data, please let me know.
$stmt = $mysqli->prepare("SELECT TABLE_NAME FROM information_schema.tables WHERE table_schema = 'shop' AND table_name LIKE 'shop%'");
//table_schema is the database name and 'shop%' is the search string
$stmt->execute();
$tables = $stmt->get_result();
$stmt->close();
$arr = [];
foreach($tables as $tabless)
{
$arr[] = $tabless;
}
foreach($arr as $arrs)
{
$toby[] = implode(',',$arrs);
}
$tobyy = implode(' UNION SELECT name, html_id, price from ',$toby);
//$tobyy = "shop_a UNION SELECT name, html_id, price from shop_b"
$arr = [];
$stmt = $mysqli->prepare("SELECT name, html_id, price FROM " . $tobyy);
$result = $stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_assoc())
{
$arr[] = $row;
}
$n=0;
$name = [];
foreach($arr as $arrs)
{
$name[$n] = array(0 => $arrs['name'], 1 => $arrs['html_id'], 2 => $arrs['price']); //here
$n++;
}
$stmt->close();
print_r($name);
//$name = "Array ( [0] => Array ( [0] => Chromecast [1] => chromecast [2] => 59 ) [1] => Array ( [0] => EZCast [1] => ezcast [2] => 49 ) )"
SELECT query is used to fetch data from DB tables, not DB itself. So you need to provide a table name in the FROM part of your query.
Considering you're trying to fetch data from similar tables (same fields)...
$stmt = $mysqli->prepare("SELECT table_name FROM information_schema.tables WHERE table_schema = 'wp_105424' AND table_name LIKE 'shop%'");
$stmt->execute();
$tables = $stmt->get_result();
$dataStmt = $mysqli->prepare("SELECT name, html_id, price FROM " . implode(',', $tables)); // name, html_id, price should be in all tables that starts with *shop*
$dataStmt->execute();
$data = $dataStmt->get_result();
And you may need to add conditions to handle all scenarios.
lets say I have the following query in a variable:
$sql = "select id, salary, fname, lname from users where id = ? and salary > ?";
and an array like this:
$params = array (
0 => '38765',
1 => '4000');
I was wondering if there is a simple of built in PHP to do this to replace the "?" in the query to get the following result:
"select id, salary, fname, lname from users where id = '38765' and salary > '4000' ";
the query won't be executed by the way, this more of a sting manipulation question than a sql one.
this is as close as I got but it looks like PHP might have something built it for it:
foreach ($params as $param){
$pos = strpos($sql, '?');
$sql = substr_replace($sql, "'".$param."'", $pos, 1);
}
Yes, there is.
See this code example from php.net
$stmt = $dbh->prepare("SELECT * FROM REGISTRY where name = ?");
if ($stmt->execute(array($_GET['name']))) {
while ($row = $stmt->fetch()) {
print_r($row);
}
}
http://php.net/manual/en/pdo.prepared-statements.php#example-1016
But this variant requires that you work with PDO.
See this link for more details:
http://php.net/manual/en/book.pdo.php
I have this query:
SELECT id, result, ip_address, added_date
FROM results
WHERE course_id = (
SELECT id
FROM courses
WHERE course = 'informatica'
AND macro_course_id = (
SELECT id
FROM macro_courses
WHERE macro_course = 'scienze-matematiche-fisiche-e-naturali'
AND organization_id = (
SELECT id
FROM organizations
WHERE organization = 'universita-degli-studi-di-torino'
AND city_id = (
SELECT id
FROM cities
WHERE city = 'torino'
AND region_id = (
SELECT id
FROM regions
WHERE region = 'piemonte' ))))) ORDER BY id DESC
And i'm using this code to do it with a preparedstatement
public function getResults($region, $city, $organization, $macro_course, $course) { //works
//added_date=datetime : YYYY-MM-DD HH:mm:ss
echo "SELECT id, result, ip_address, added_date
FROM results
WHERE course_id = (
SELECT id
FROM courses
WHERE course = '$course'
AND macro_course_id = (
SELECT id
FROM macro_courses
WHERE macro_course = '$macro_course'
AND organization_id = (
SELECT id
FROM organizations
WHERE organization = '$organization'
AND city_id = (
SELECT id
FROM cities
WHERE city = '$city'
AND region_id = (
SELECT id
FROM regions
WHERE region = '$region' ))))) ORDER BY id DESC"; //just for me to know what query is being executed
if ($stmt = $this->mysqli->prepare(("
SELECT id, result, ip_address, added_date
FROM results
WHERE course_id = (
SELECT id
FROM courses
WHERE course = ?
AND macro_course_id = (
SELECT id
FROM macro_courses
WHERE macro_course = ?
AND organization_id = (
SELECT id
FROM organizations
WHERE organization = ?
AND city_id = (
SELECT id
FROM cities
WHERE city = ?
AND region_id = (
SELECT id
FROM regions
WHERE region = ? ))))) ORDER BY id DESC
"))) {
$return = array();
$stmt->bind_param('sssss', $course, $macro_course, $organization, $city, $region);
$stmt->execute();
if ($stmt->fetch()) {
$i = 0;
while ($row = $stmt->fetch()) {
print_r($row);//this is never reached
continue;
$s = new Result($row['result'], $row['added_date'], $row['id']);
$return[$i] = $s;
$i+=1;
}
}
}
return $return;
}
The problem is that this function returns 0 rows and 0 errors (checked with $this->mysqli->error), it seems that $row = $stmt->fetch() is always false.
However, if i copy and execute on PHPMyAdmin the output i get at the function top, i see
Showing lines 0 - 0 ( 1 total, Query time 0.0003 sec)
So the query returns a line but it is not catched by php. What am i missing? How can i fix this?
Because you used $stmt-fetch() two times here
if ($stmt->fetch()) {
$i = 0;
while ($row = $stmt->fetch()) {
Remove the if ($stmt->fetch()) condition, it will work as expected.
EDIT
from docs
Note that all columns must be bound by the application before calling $stmt->fetch().
You have to bind the result before calling $stmt->fetch() like this
/* bind result variables */
$stmt->bind_result($name, $code);
I need to select a whole column.
So my question is how do i get a whole column ?
$query = "SELECT * ";
$query .= "FROM employees ";
$query .= "WHERE id=*";
$query .= "ORDER BY id ASC ";
I tried id=* but no luck ...
My goal is to cycle through all IDs but some may be missing so i figured i put them in a numeric or associative array and use foreach. If there is a better way , please do share.
EDIT:
function get_all_ids()
{
global $connection;
$query = "SELECT * ";
$query .= "FROM employees ";
$query_result = mysql_query ( $query , $connection );
confirm_query($query_result);
$query_result_array = mysql_fetch_assoc($query_result);
return $query_result_array;
}
i use this to print the array
$all_id = get_all_ids();
// preparing the table;
echo "<pre>";
print_r($table);
print_r($all_id);
echo "</pre>";
and this is the array
Array
(
[id] => 1
[department_id] => 1
[name] => jordan
[EGN] => 9108121544
[email] => testEmail
[address] => testAddress
[country] => testCounty
)
If there's more than one row in your result set, you need to keep fetching until all results are retrieved:
$q = mysql_query('SELECT * FROM `table`');
while (($row = mysql_fetch_assoc($q)) != FALSE)
{
// Do something with *one* result
}
mysql_free_result($q);
If you'd like to retrieve all ids in a single fetch, you could do:
$q = mysql_query('SELECT GROUP_CONCAT(`id`) AS `id_list` FROM `table`');
$row = mysql_fetch_assoc($q);
mysql_free_result($q);
$list_of_ids = explode(',', $row['id_list']);
WARNING: GROUP_CONCAT() usually has a result limit of 1024 bytes; meaning your results will be truncated for large tables. You could either resort to the first solution, or increase group_concat_max_len for the current connection.
If you want ALL the records then you dont need a WHERE condition at all.
Perhaps you mean the simple:
SELECT id
FROM employees
ORDER BY id ASC
If this gives you only one row, then either you have only one row or you are adding a LIMIT 1 or your PHP code does not loop through all the results but just shows the first one of them. Please add the PHP code.
If you want to select a single column. Then do not use "*", give the name of the columns name separated by comma and quoted with "`" (tick) for safety.
$query = "SELECT `id` "; //if you only want to get ids from the table
$query .= "FROM employees ";
$query .= "WHERE id=*";
$query .= "ORDER BY id ASC ";