convert mysql query in to an array format - php

can any one know the, convert mysql query in to an php array:
this is mysql query :
SELECT SUM(time_spent) AS sumtime, title, url
FROM library
WHERE delete_status = 0
GROUP BY url_id
ORDER BY sumtime DESC
I want to convert this query in to simple php array .

So, you need to get data out of MySQL. The best way, hands down, to fetch data from MySQL using PHP is PDO, a cross-database access interface.
So, first let's connect.
// Let's make sure that any errors cause an Exception.
// <http://www.php.net/manual/en/pdo.error-handling.php>
PDO::setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// We need some credentials...
$user = 'username';
$pass = 'password';
$host = 'hostname';
$dbname = 'database';
// PDO wants a "data source name," made up of those credentials.
// <http://www.php.net/manual/en/ref.pdo-mysql.connection.php>
$dsn = "mysql:host={$host};dbname={$dbname}";
$pdo = new PDO($dsn, $user, $pass);
There, we've connected. Let's pretend that $sql has the SQL you provided in your question. Let's run the SQL:
$statement = $pdo->prepare($sql);
$statement->execute();
There, it's been executed. Let's talk about results. You steadfastly refuse to tell us how you want your data structured, so let's go through four ways that you could get your data.
Let's first assume that the query returns a single row. If you want a numerically indexed array, you would do this:
// <http://www.php.net/manual/en/pdostatement.fetch.php>
$array = $statement->fetch(PDO::FETCH_NUM);
unset($statement);
If you want an associative array with the column names as the keys, you would do this:
$array = $statement->fetch(PDO::FETCH_ASSOC);
unset($statement);
Now, what if the query returns more than one record? If we want each row in a numerically indexed array, with each row as an associative array, we would do this:
// <http://www.php.net/manual/en/pdostatement.fetchall.php>
$array = $statement->fetchAll(PDO::FETCH_ASSOC);
unset($statement);
What if we want each row as a numerically indexed array instead? Can you guess?
$array = $statement->fetchAll(PDO::FETCH_NUM);
unset($statement);
Tada. You now know how to query MySQL using the modern PDO interface and get your results as no less than four types of array. There's a tremendous number of other cool things that you can do in PDO with very minimal effort. Just follow the links to the manual pages, which I have quite intentionally not linked for you.
This over-the-top post has been brought to you by the letters T, F and W, and the number PHP_MAX_INT + 1.

i don't get you clearly, but
mysql_fetch_array and mysql_fetch_assoc
both returns only array
please refer:-
http://php.net/manual/en/function.mysql-fetch-array.php
http://php.net/manual/en/function.mysql-fetch-assoc.php

If you just need a simple array...
while ($row = mysql_fetch_array($query)) { //you can assume rest of the code, right?
$result[$row['url_id']] = array($row['sumtime']);
}

For a simple array
$sql = mysql_query("SELECT SUM(time_spent) AS sumtime, title, url
FROM library
WHERE delete_status = 0
GROUP BY url_id
ORDER BY sumtime DESC");
while($row = mysql_fetch_array($sql)){
$array1 = $row['sumtime'];
$array2 = $row['title'];
$array3 = $row['url'];
}
Hope this is one you wanted

Dude the fastest way is probably the following
$data = array();
while($row = mysql_fetch_array($result))
{
$data[] = $row;
}
print_r($data);

Related

Mysql results as PHP named variables

I have a table in mysql called site_settings that looks like this
Table in PHPMyAdmin
I am trying to store all of my website settings in mysql and want to pull them into PHP as variables.
I want to pull all values from the variable_name column as the $variable names in PHP and have their values set to whats in the variable_type column.
$site_name = Vexed
$registration_enabled = False
here is my code:
$sql = connect($database_address, $database_username, $database_password, $database);
$query = "SELECT * FROM site_settings";
$result = $sql->query($query);
//$row = $result->fetch_all(MYSQLI_ASSOC);
while($row = $result->fetch_assoc())
{
$$row['variable_name'] = $row["variable_type"];
}
$arr = get_defined_vars();
print_r($arr);
the last two lines i am using to see if the variable have been created but i cant get it to work. the best result i have got so far is
[Array] => Array
(
[variable_name] => Vexed
)
Can anyone tell me where i am going wrong?
Thanks in advance to anyone who can help.
What you're trying to duplicate is PHP's extract() builtin function.
It's generally considered a bad practice, because it will make your code harder for readers to understand or debug.
What is so wrong with extract()?
How to demonstrate an exploit of extract($_POST)?
https://dzone.com/articles/php-bad-practice-use-extract
https://blog.josephscott.org/2009/02/05/i-dont-like-phps-extract-function/
What I think is happening is that when you call $$arr['variable_name'] it's actually doing $$arr first (which evaluates to $Array after the string conversion), and then trying to assign into assign the ['variable_name'] key into $Array.
I would expect this minor modification to work:
$sql = connect($database_address, $database_username, $database_password, $database);
$query = "SELECT * FROM site_settings";
$result = $sql->query($query);
//$row = $result->fetch_all(MYSQLI_ASSOC);
while($row = $result->fetch_assoc())
{
$name = $row['variable_name'];
$$name = $row["variable_type"];
}
$arr = get_defined_vars();
print_r($arr);
Edit: I'll also echo, that it's a little bit weird to dynamically create variables in this way and it will make your code hard to follow.

How to add element to php array without it showing as a new array

The intention with the below code is to extract messages from a mysql table, and put each of them inside ONE array with {} around each output. Each output consists of various parameters as you can see, and is an array in itself.
What the code does is that each time the loop is processed, in the JSON array that this later is converted into, it wraps the output in []´s, hence it´s now a new array which is created.
What I get is:
[{"sender":"ll","message":"blah","timestamp":"2016-12-21 14:43:04","username":"","msgtype":"","threadid":"32629016712222016034323"},{"sender":"kk","message":"blahblah","timestamp":"2016-12-21 14:43:23","username":"","msgtype":"","threadid":"32629016712222016034323"},{"sender":"ll","message":"blahblahblah","timestamp":"2016-12-21 14:43:47","username":"","msgtype":"","threadid":"32629016712222016034323"}],[{"sender":"ll","message":"blahblahblahblah","timestamp":"2016-12-21 14:43:04","username":"","msgtype":"","threadid":"92337321312222016034304"},{"sender":"kk","message":"blahblahblahblahblah","timestamp":"2016-12-21 14:44:05","username":"","msgtype":"","threadid":"92337321312222016034304"}]]
And what I want is:
[{"sender":"ll","message":"blah","timestamp":"2016-12-21 14:43:04","username":"","msgtype":"","threadid":"32629016712222016034323"},{"sender":"kk","message":"blahblah","timestamp":"2016-12-21 14:43:23","username":"","msgtype":"","threadid":"32629016712222016034323"},{"sender":"ll","message":"blahblahblah","timestamp":"2016-12-21 14:43:47","username":"","msgtype":"","threadid":"32629016712222016034323"}],{"sender":"ll","message":"blahblahblahblah","timestamp":"2016-12-21 14:43:04","username":"","msgtype":"","threadid":"92337321312222016034304"},{"sender":"kk","message":"blahblahblahblahblah","timestamp":"2016-12-21 14:44:05","username":"","msgtype":"","threadid":"92337321312222016034304"}]
How do I proceed to get the right result here?
$data = array ();
foreach($threads as $threadid){
$sql = ("SELECT sender,message,timestamp,username,msgtype,threadid FROM Messages WHERE threadid = '$threadid' AND subject = '' AND timestamp > '$newtimestamp' ORDER BY timestamp");
$arrayOfObjects = $conn->query($sql)->fetchAll(PDO::FETCH_OBJ);
$data[] = $$arrayOfObjects;
}
And FYI, $threadid is another array containing... threadids, and the loop correctly fetches these one by one, that´s not where the problem is.
Thanks in advance!!
You are doing O(N) database queries, consider doing just O(1) using an IN expression in your where clause. No need for a foreach loop and you'll get all your data in one array.
SELECT ... FROM Messages WHERE threadid IN (1, 2, 3, ...) AND ...
You might have to use a prepared statement for that.
I think you are searching for PDO::FETCH_OBJ.
You had FETCH_ASSOC, which will return an array of associative arrays.
FETCH_OBJwill return an array ob stdObjects.
Also you reassigned $array to itself when doing $array[] = $array;..
$data = array();
foreach($threads as $threadid){
$sql = ("SELECT sender,message,timestamp,username,msgtype,threadid FROM Messages WHERE threadid = '$threadid' AND subject = '' AND timestamp > '$newtimestamp' ORDER BY timestamp");
// here it is:
$arrayOfObjects = $conn->query($sql)->fetchAll(PDO::FETCH_OBJ);
$data[] = $arrayOfObjects;
}
// now you can encode that as json and show it:
echo json_encode($data);
#akuhn
Well, I decided to give your suggestion one more try, and managed to do it in a none prepared way. I´m aware that this is supposed to be risky, but so far this project just needs to work, then have the php codes updated to safer versions, and then go live. It works, so thanks a bunch!
$sql = ("SELECT sender,message,timestamp,username,msgtype,threadid FROM Messages WHERE threadid IN ('" . implode("','",$threadid) . "') AND subject = '' AND timestamp > '$newtimestamp' ORDER BY timestamp");
$data = $conn->query($sql)->fetchAll(PDO::FETCH_OBJ);

Php array from mysql column

I looked at this question:
Create PHP array from MySQL column
and what seems to work for everyone is this:
$array= array();
while ($row = mysql_fetch_array(mysql_query("SELECT Username FROM inloggen"))) {
$array[] = $row['Username'];
}
But when I run this code it infinitely adds the first username in my database to the array.
Does anyone know what I'm doing wrong?
You're re-executing the query endlessly, because you're doing it as part of your while, so if any records are returned , your code will re-query and return the same result time and again
Execute the query, then iterate over the result set
$result = mysql_query("SELECT Username FROM inloggen");
$array = array();
while ($row = mysql_fetch_array($result)) {
$array[] = $row['Username'];
}
Caveat: The MySQL extension is a deprecated interface; you should be using MySQLi or PDO

Put mysql results in one php array, like this?

To get an array like this array("123","456","789"); I use the code:
$Regids = mysql_query("SELECT regid FROM $tabel WHERE active = '1'");
while($row = mysql_fetch_array($Regids))
{
$result_array[] = "\"".$row['regid']."\"";
}
$regIDs = implode(',', $result_array);
$registrationIDs = array($regIDs); // array("123","456","789");
but I would expect PHP/mySQL has a simpler/faster solution for this?
I doubt that your code produces the result you want.
// assuming the this query produces 123,456,789
$Regids = mysql_query("SELECT regid FROM $tabel WHERE active = '1'");
// $row contains: array("123")
while($row = mysql_fetch_array($Regids))
{
$result_array[] = "\"".$row['regid']."\"";
}
// $result_array now contains: array("\"123\"", "\"456\"", "\"798\"");
$regIDs = implode(',', $result_array);
// $regIDS now contains a single string: "\"123\",\"456\",\"798\"";
$registrationIDs = array($regIDs);
// registrationIDs now is an array containing a single string: array("\"123\",\"456\",\"798\"");
If you really need an array that looks like this: array("123","456","789"); it is much simpler.
$Regids = mysql_query("SELECT regid FROM $tabel WHERE active = '1'");
while($row = mysql_fetch_array($Regids))
$registrationIDs[] = $row['regid'];
and that's all.
If your mysql result contains the number as an integer instead of an string you can convert it like this:
$Regids = mysql_query("SELECT regid FROM $tabel WHERE active = '1'");
while($row = mysql_fetch_array($Regids))
$registrationIDs[] = strval($row['regid']);
Also, keep in mind that the mysql_* functions are becoming deprecated. Don't start new code with it and make plans to port your existing code to mysqli_* or PDO.
You can use PDO implementation. At first sight, it may be more difficult to understand, but once you get used to it, it reveals to be really powerful and handy (IMHO! One year ago i switched to it and i love it)!
For your example, the PDO implementation would be like this:
/*CONNECT TO DB, FIRST. $dbh contains a handler to the current DB connection*/
$stmt = $dbh->prepare("SELECT regid FROM table WHERE active = '1'");
$stmt->execute();
$Regids = $stmt->fetchAll(PDO::FETCH_COLUMN,0);
There are many formatting options you can specify, like
PDO::FETCH_COLUMN
PDO::FETCH_ASSOC
and more...These options will allow you to get the array formatted as you prefer. As you can see i got the result in just 3 simple rows.
EDIT
Note: you are not escaping PHP variables before inserting them in your Query, and your code may suffer SQL INJECTION. Be careful!! Here is a simple guide to prevent it.
(In my code, just to be clear, i avoided the problem by just putting the table name instead of $table, just to show simply how to get the result you wanted.)
try this .. use Group concat in query ...
$Regids = mysql_fetch_array(mysql_query("SELECT GROUP_CONCAT(regid) as regids FROM $tabel WHERE active = '1'"));
echo $Regids[0]['regids']; // 123,456,789
for getting result "123","456","789" try this
$Regids = mysql_fetch_array(mysql_query("SELECT GROUP_CONCAT('\"',CONCAT(regid),'\"') as regids FROM $tabel WHERE active = '1'"));
echo $Regids[0]['regids']; // "123","456","789"

mysql query and implode

I try to retrieve a array from one table What is wrong with this code?
$_fbexclude = mysql_query("SELECT fbempfang FROM fbinvite WHERE fbreturn = '1' ");
$fbexcludearray= mysql_fetch_array($_fbexclude);
// Convert the array
$excludes = implode(',', $fbexcludearray);
From echo $excludes; It only gives me just the following response: 1000033xxx161,1000033xxx161 Twice the same fbempfang
See if the following gives you what you want (FIXED):
$_fbexclude = mysql_query("SELECT fbempfang FROM fbinvite WHERE fbreturn = '1'");
$fbexcludearray = array();
while ($row = mysql_fetch_assoc($_fbexclude)) {
$fbexcludearray[] = $row['fbempfang'];
}
// Convert the array
$excludes = implode(',', $fbexcludearray);
mysql_fetch_array() and it's siblings (_assoc, _row) only retrieve one row at a time. This means that your original code will only give you the first returned row - to work around this, we use the loop you see above.
The reason you see the same data twice is because mysql_fetch_array() returns a mixed indexed and associative array, which contains all the data twice over. For this reason, it is much better to use mysql_fetch_assoc() or mysql_fetch_row(), as you rarely need both formats.
In fact, it is much better to use mysqli, but the same information applies to that as well.
Use right SQL query:
SELECT GROUP_CONCAT(`fbempfang`) as imploded from `fbinvite` WHERE fbreturn = '1'
It's return string as PHP implode(',', array(…));
Try this on for size:
$implode_arr = array();
$_fbexclude = mysql_query("SELECT fbempfang
FROM fbinvite
WHERE fbreturn = '1'");
while($row = mysql_fetch_array($_fbexclude)) {
$implode_arr[] = $row['fbempfang'];
}
// Convert the array
$excludes = implode(',', $implode_arr);
You need to loop over the mysql_fetch_* functions because they only return one of the result rows at a time. For more information and examples see the manual page for mysql_fetch_assoc().

Categories