I'm pulling a joined query from the DB using the following code:
$query = 'SELECT `profiles`.`city`, `users`.`first_name`, `users`.`last_name`'
. ' FROM profiles, users'
. ' WHERE ((`profiles`.`user_id` = 3) AND (`users`.`user_id` = 3))'
. ' LIMIT 1';
$result = $connection -> query($query);
$arr = $result -> fetch_array();
$feedback = $arr;
$result -> close();
return $feedback;
This isn't my final code, this is just preliminary to test my join.
The query seems to work fine, it pulls the single row of information I need but I noticed that when I var_dump it, it's put the array into 2 different indexes, a numerical index and an index of the name of the db field. Here's what the var_dump looks like:
array(6) { [0]=> string(4) "Reno" ["city"]=> string(4) "Reno" [1]=> string(4) "John" ["first_name"]=> string(4) "John" [2]=> string(3) "Doe" ["last_name"]=> string(3) "Doe" }
This is effectively doubling the size of my query result. For a single row this won't be that big of a deal but if/when I begin to use this same method to draw multiple records, doubling the size of the result can be costly.
I've tried to do a foreach loop:
foreach ($arr as $key=>$value) {
$feedback[$key] = $value;
}
but it leaves me with the same result. Am I doing something wrong and if so, how do I correct it or is this normal?
Thanks for you help
The default result type for mysqli_result::fetch_array() is MYSQLI_BOTH meaning you get both named and numeric result array indices (see http://php.net/manual/en/mysqli-result.fetch-array.php).
Try using fetch_assoc() instead.
To reduce the size, you'll want to look at the second optional argument to mysql_fetch_array. This is documented here:
http://www.php.net/manual/en/function.mysql-fetch-array.php
You can specify if you just want numerical-indexes or associative arrays.
If you use fetch row (http://www.php.net/manual/en/mysqli-result.fetch-row.php) you will fetch without the names. I think this is what you are looking for, right?
EDIT: This also apllied to mysql, but the function is mysql_fetch_row($result) instead of mysqli
Related
//List of id's I want displayname for
$IDListSQL = '10,10,10,11,10,10';
//My query statement
$q = "SELECT displayname FROM accounts WHERE id IN($IDListSQL)";
//Executes query
$Res = $DB->Query($q);
//Gets all results
$Rows = $Res->fetch_all();
echo var_dump($Rows);
//Output
#->array(2)
{
[0]=> array(1)
{
[0]=> string(14) "Apple"
}
[1]=> array(1)
{
[0]=> string(10) "Orange"
}
}
The behaviour I want is an array with all the displayname's in the $IDListSQL, even if its the same ID. I also want them in the order I specified. Trying to figure this out in 1 query rather than doing up to 16 separate select queries for the purpose this is for. Any help would be appreciated kindly.
I ended up getting this done with PHP since I already had an array of ID's in the specified order. Used my same query to only get one of each ID, then joined the data into my array with the help of a couple for loops. Appreciate the help, Ctznkane525 I think what you posted would work. It sounds like it is doing the same thing I done up in PHP, trying not to use complex queries unless absolutely necessary. Speed and high ccu is critical for this app.
array(2) {
[0]=>
array(1) {
["url_id"]=>
string(2) "45"
}
[1]=>
array(1) {
["h"]=>
string(1) "3"
}
}
echo $column_list = join(',', $items);
...
This PDO Insert Array Using Key As Column Name helps me inserting array values in MySQL table easily. But now I do have an array containing subarrays and it looks like this join(',', $items); does not work. Guess you think "of course it doesn't work" right now, but how can I store the keys and the values into a variable to use $sql = "INSERT INTO applications ($column_list) VALUES ($param_list)"; successfully.
I have tried array_merge but that did not work at all. I would like to show some code examples, but I have no idea what to try and how to achieve that.
Thanks for your help! I appreciate it!
I am having trouble correctly counting elements within the array that I pulled from my database. Please see my code below:
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn)
{
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully!";
//NEW QUERY TO OUR DATABASE
$query = $conn -> query("Select distinct Race from Races");
while($race[] = $query->fetch_object());
//Check how many elements are within our query
$racecount = count($race);
echo "<br>" . $racecount . "<br><br>";
$racecount = count($race,COUNT_RECURSIVE);
echo "<br>" . $racecount . "<br><br>";
var_dump($race);
echo "<br><br><br>";
Using both type count() in both ways yields the same result of "4". However, please see the result from my var_dump.
array(4) { [0]=> object(stdClass)#3 (1) { ["Race"]=> string(5) "Human" } [1]=> object(stdClass)#4 (1) { ["Race"]=> string(7) "Vampire" } [2]=> object(stdClass)#5 (1) { ["Race"]=> string(5) "Demon" } [3]=> NULL }
Var_dump shows that it is an array with 4 elements within it. So count was correct, it's just not giving me the number that I'm looking for.
Thus, I have three questions.
1) How do I count my elements correctly?
2) Could someone explain to me why this reads as 4 elements?
3) Is my array not multi-dimensional? (since both counts yield the same result of 4)
Best Regards and Thanks in advance,
Josh
`while($race[] = $query->fetch_object());`
$query->fetch_object() returns a null to indicate that there are no more entries in the dataset, but you're still assigning that null value to your $race array as a last entry, and only then allowing the while to terminate its loop.... that's why you have 4 entries in the array rather than 3.
Your array is not multidimensional, because the entities stored in the $races array are objects, not arrays; it would only be multi-dimensional if it was an array of arrays
The reason is actually pretty straight forward. When inserting data into your array using while($race[] = $query->fetch_object()) you always insert the final $query->fetch_object() which is gonna be equal to null. That is when you exit your while loop. Thus, your array's last item will always be null, just like in your own var_dump.
One way to fix this would simply to subtract 1 from your result. Another way would be to implement inserting like this:
$race = [];
while($row = $query->fetch_object()) {
array_push($race , $row);
}
The best way to count however would be by simply executing an SQL COUNT command:
$query = $conn->query("SELECT COUNT(DISTINCT Race) FROM Races");
Your php count is returning the amount of fields on your result object, not the amount of rows.
Try this for your SQL query:
$query = $conn->query("SELECT COUNT(DISTINCT Race) FROM Races");
Should you wish to use the same query as you have now, try:
$raceCount = $query->num_rows;
I need to know if there is a chance to get an PHP5 array from a MySQL PDO Query like this:
Array = (
keywordID = 1321,
keyword = "Its a test",
position = Array(
today = 12,
month = 17
)
)
Now i have this MySQL Query:
$sql = "SELECT
keywords.id AS keywordID,
keywords.keyword,
statistic.position
FROM
keywords
LEFT JOIN statistic ON (statistic.kid = keywords.id)
WHERE
keywords.uid = ? AND statistic.date IN (?, ?)";
$stmt = WPStatsDB::getInstance()->prepare($sql);
$stmt->execute(array($array['userID'], date("d.m.Y", time()), date("d.m.Y", strtotime('-30 days'))));
$result = $stmt->fetchAll();
This is the current result of var_dump($result):
This is one of the results. I try to write it in my post.
array(244) {
...
[1]=>
array(6) {
["keywordID"]=>
string(4) "1978"
[0]=>
string(4) "1978"
["keyword"]=>
string(20) "Weiterbildung in NRW"
[1]=>
string(20) "Weiterbildung in NRW"
["position"]=>
string(2) "38"
[2]=>
string(2) "38"
}
...
}
EDIT 1:
I need the attribute position as array with two values not as int with only one value. I need position as array with the two attributes for less database queries.
Today and Month are values with information of position of today and the position from the day a month ago of today.
EDIT 2:
Sorry, i've forgot to say that i can't edit this table. The table statistics contains the stats of every day of every keyword connected to every domain. It's very big.
I really don't know how i can solve this.
Thanks for help!! :-)
It's arguable what's faster, in a lot of cases is faster to do separated queries for the relationship.
You either
1) Get a row for each position and deal with it after you get the result
2) Go on a loop for each keyword and get the positions on a separate query for each keyword
3) You do a group by keyword id in MySQL and retrieve the positions with something like group_concat. You can then parse that afterwards. This may seem faster but probably depends on your dataset and may not be as good as you'd expect it to be.
Yes, you can. Use any ORM, list of examples
I am trying to get all the values from a column with mysqli.
I have tried
$emaildbs = $db->query("SELECT email from subscribers");
while($emaildbsrow = $emaildbs->fetch_row()) {
$emaildbsrows[] = $emaildbsrow;
}
var_dump($emaildbsrows);
but the var_dump looks like this:
array(2) {
[0]=>
array(1) {
[0]=>
string(6) "asdasd"
}
[1]=>
array(1) {
[0]=>
string(1) "s"
}
}
and the expected output is
array(2) {
[0]=> string(6) "asdasd"
[1]=> string(1) "s"
}
I have also tried:
with fetch_assoc and I get smth similar. I searched on stackoverflow, and tried numerous functions instead of fetch_row but same thing. Where am I mistaking.
You're assigning complete row to $emaildbsrows array so just change it to,
$emaildbs = $db->query("SELECT email from subscribers");
while($emaildbsrow = $emaildbs->fetch_row()) {
$emaildbsrows[] = $emaildbsrow[0];
}
var_dump($emaildbsrows);
Each row is an array itself - but as you are selecting a single column, it is a single index array.
You might want to do the following instead:
$emaildbs = $db->query("SELECT email from subscribers");
while($emaildbsrow = $emaildbs->fetch_row()) {
$emaildbsrows[] = $emaildbsrow[0];
}
var_dump($emaildbsrows);
This will add the single element from the array as a new element in $emaildbsrows. As you are only selecting a single column from the table, this will work nicely. Had you selected more than one column, this wouldn't work.
You should use abstraction libraries instead of raw mysqli, such as PDO
$sql = "SELECT email from subscribers";
$emails = $pdo->query($sql)->fetchAll(PDO::FETCH_COLUMN, 0));
or safeMysql
$emails = $db->getCol("SELECT email from subscribers");
the purpose of an abstraction library is to get rid of all the dirty job, making your code cleaner and more readable. See - everything can be done in one single line, making your code four times shorter. Assuming 20 queries per page in average it can save you 60 lines of code.
However, to tell you truth, I don't believe myself you would follow this suggestion. According to my observations, PHP users rather inclined to writing as much code as possible, producing screens of code out of every trifle operation.