I'm trying to get all tables from a certain database inside an array, so I can compare it to another database.
//Get a list of all tables
$sql = "SHOW TABLES FROM Data;";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck == 0)
{
exit("NO SQL RESULTS");
}
$array = mysqli_fetch_all($result);
print_r($array);
However, when I do this, it results in me getting an array with the results nested inside another array.
Array
(
[0] => Array
(
[0] => table1
)
[1] => Array
(
[0] => table2
)
[2] => Array
(
[0] => table3
)
[3] => Array
(
[0] => table4
)
)
Is there a way of doing this, without using a while loop in combination with mysqli_fetch_assoc?
You could try something like this:
SELECT group_concat(table_name) as tables FROM information_schema.tables where table_schema='Data'
This will return a single field tables which contains a comma separated list of all table names.
You can then use:
$array = mysqli_fetch_array($result);
$tables = explode(",", $array['tables']);
print_r($tables);
To split the table names into an array
Related
I am using MYSQLI query to extract data into an array. But when printing the array content, it looks that data is being populated into sub array. This is my code:
<?php
require_once 'database.php';
// Choose the y-axis
$sql = "SELECT `O3` FROM giordan_mod ORDER BY id DESC LIMIT 4";
$resulty = mysqli_query($conn, $sql);
$datay = [];
while($row = mysqli_fetch_array($resulty, MYSQLI_NUM))
{
$datay[] = $row;
}
echo '<pre>'; print_r($datay);'</pre>';
?>
<?php
$test = array(4, 6, 9, 15);
echo '<pre>'; print_r($test);'</pre>';
?>
But when printing the array, the result are as follows:
Array
(
[0] => Array
(
[0] => 40.25
)
[1] => Array
(
[0] => 39.64
)
[2] => Array
(
[0] => 40.13
)
[3] => Array
(
[0] => 40.28
)
)
Array
(
[0] => 4
[1] => 6
[2] => 9
[3] => 15
)
But I would like that MYSQLI query input data into an array and not sub array. That is I need $datay array looks as $test array.
mysqli_fetch_array() returns an array representing a row of data from your SQL command. Even if you only fetch a single command, it will always be an array. To fetch fetch a single column you need to use mysqli_fetch_column().
You can use PDO instead. It is easier and offers more functionality including a method to fetch a single function.
If you are stuck with mysqli, then you can use a loop and fetch the single column yourself.
$sql = "SELECT `O3` FROM giordan_mod ORDER BY id DESC LIMIT 4";
$resulty = mysqli_query($conn, $sql);
$datay = [];
foreach($resulty as $row) {
$datay[] = $row['O3'];
}
or even simpler:
$sql = "SELECT `O3` FROM giordan_mod ORDER BY id DESC LIMIT 4";
$resulty = mysqli_query($conn, $sql);
$datay = array_column($resulty->fetch_all(MYSQLI_ASSOC), 'O3');
I have create simple function to check if table exists in the database or not ..
I want fetch all table in the database and i use like
$sql = "SHOW TABLES FROM plus LIKE '%group%'";
$do = mysqli_query($db,$sql);
$table = array();
while ($row = mysqli_fetch_row($do)) {
$table[] = $row ;
}
print_r($table);
}
the output
Array ( [0] => Array ( [0] => group_1 ) [1] => Array ( [0] => group_2 ) [2] => Array ( [0] => group_3 ) [3] => Array ( [0] => group_4 ) )
I want all table in one array to encode with Json ,
and use the array to check in_array by PHP ..
==Edited==
I'm getting JSON as
[["group_1"],["group_2"],["group_3"],["group_4"]]
But, I'm expecting
["group_1","group_2","group_3","group_4"]
You could use json_encode, to get your resultset as json
echo json_encode($table);
Since, you are getting sub-array with your $table array, you need to merge them into single array to get your expected output.
You could make changes to your loop.
while ($row = mysqli_fetch_row($do)) {
array_merge($table,$row);
}
echo json_encode($table);
or, to print array
var_dump($table);
I have a table named as 'files' with fields id, formID ,filename, date_modified.
Now i want to fetch list of filenames from this table to an array with index of array from each row with same formID in that array for example:
(In core php)
Instead of this
Array
(
[0] => Array
(
[file_name] => filename1.jpg
)
[1] => Array
(
[file_name] => filename2.jpg
)
)
I want result in this format:
Array
(
[0] => filename1.jpg
[1] => filename2.jpg
)
Use a select query, then do a while loop to loop through each row. During that loop, assign the filename to each position of $array, be it what you name it.
$conn = $mysqli_connect(.....);
$query = "SELECT id,formID,filename,date_modified FROM files";
$result = $conn->query($query);
while($row = $result->fetch_assoc()){
$array[] = $row['filename'];
}
$result->close();
$conn->close();
print_r($array);
You should use this
$sth = $dbh->prepare("SELECT filenames FROM tablename");
$sth->execute();
$result = $sth->fetchAll(PDO::FETCH_COLUMN, 0);
print_r($result);
Result
Array
(
[0] => filename1.jpg
[1] => filename2.jpg
)
The array_column() function returns the values from a single column in the input array.
$result = array_column($yourArray, 'file_name');
Need to find if two arrays match, and then where they match pull data from the mysql row in which they match. Should I use
$sql = "SELECT * FROM around";
$resultsd = $conn->query($sql);
foreach($resultsd as $rowd) {}
if (array_intersect($ar1, $ar2)) {
$sword[] = $rowd['TIM'];
}
or should I use
if (in_array($ar1, $ar2)) {
$sword[] = $rowd['TIM'];
}
Getting the arrays like:
$ar1[] = $rowd['nim'];
$ar2[] = $rowd['nim'];
Then how does one go about pulling the specific row that they match at?
I am seeing that they match, and printing out the array's okay:
Array ( [0] => dcbabcbded ) Array ( [0] => fafeafaebee [1] => afabfdefcbb [2] => dcbabcbded
But when I trying a echo the mysql data where they match I fail:
Array ( )
i would go with sql IN clause.
You have an array of customer names: $a = array('john','rob','paul');
implode array $nms = join(',',$a);
Make sql: 'SELECT * FROM tabl WHERE name IN ('.$nms.')';
do the array intersection first (or what you just have to..) to have an array of needed names.
use $new = array_intersect(Array ( [0] => dcbabcbded ), Array ( [0] => fafeafaebee [1] => afabfdefcbb [2] => dcbabcbded)) : then make valid sql as stated in my answer above.
If u are sure you've allways have array intersenct with one or none values, then make sql just with first array element: $ar[0] using sql WHERE clause.
I'm having a hard time figuring this out...
I have two tables... ticket_winners, and tickets
in the ticket_winners table, usernames / profile information...
the tickets table is all of the tickets these users have for one userID, there could be 10+ tickets for each user in this table.
Question: How can I loop through the second iteration of data when the table tickets has more than 1 row for each user
function pullTickets() {
$sql = $this->mysql->retrieve("SELECT * FROM ticket_winners ORDER BY id DESC LIMIT 5");
$sql2 = $this->mysql->retrieve("SELECT id, userId, ticketId FROM tickets ORDER BY id ASC LIMIT 5");
while($row = mysql_fetch_array($sql)) {
$results[$row['id']]['user'] = $row['userId'];
while($row2 = mysql_fetch_array($sql2)) {
if($results[$row['id']]['user'] == $row2['userId']) {
$results[$row['id']]['tickets'][$row2['id']] = $row2['ticketId'];
} else {
}
}
}
return $results;
}
PHP page example: works fine
$data = $obj->pullTickets();
foreach($data as $user) {
echo $user['username'];
foreach($data['ticket'] as $ticket) {
echo $ticket['ticketId'];
}
}
What the array looks like now:
[1] => Array
(
[batch] => 1
[userId] => 200
[userName] => Craig
[tickets] => Array
(
[1] => GH7JNm72hN
[2] => JudM3rT3is
[3] => KiLPoXCmDF
)
)
[2] => Array
(
[batch] => 1
[userId] => 100
[userName] => Hewbie
needs to continue looping
)
the tickets table isn't being looped through each user like in the [1] array. It skips all the other users' tickets.
Try a left join on the ticket_winners table, don't use SELECT *, it is bad practice to do so and when using joins you should append each column with the table name.
SELECT tw.id,tw.userid,t,userName,t.id AS tick_id, t.ticketId
FROM `ticket_winners` AS tw
LEFT JOIN `tickets` AS t
ON tw.userid = t.userid
ORDER BY tw.id DESC LIMIT 5
The left join preserves the table format of your ticket winners table and will append t.id (in the output as tick_id),ticketId and userName.
This will give you an array consisting of multiple users, sorting them in one while loop will not be difficult as you simply create a winners array with the key of the usersid, within that array append the winning ticket id.
$results = array();
while ($sql = mysql_fetch_array($query, MYSQL_ASSOC) {
$results[$sql['userid']]['userName'] = $sql['user'];
$results[$sql['userid']]['tickets'][] = $sql['tick_id'];
}
The resulting array:
[1] => array
(
['userName'] => 'Craig',
['tickets'] => array
(
[0] => 'GH7JNm72hN',
[1] => 'JudM3rT3is'
)
)
[2] => array
(
['userName'] => 'Adam',
['tickets'] => array
(
[0] => 'GfdT24sDgC'
)
)
This eliminates the need to a) run two seperate queries, and b) avoid creating an uneccesary while loop within a while loop speeding this process up.
A good practice to follow when doing this is:
Get as much data in one query as possible.
Loop through once and sort data into one or multiple arrays eliminating duplications due to joins.
Your data is, as I see, applied to the $result array - both the tickets-data and the tickets_winner-data. What is your question then? Maybe I have totally misunderstood it.