making a comfortable php multidimensional array from database - php

i got a code like this:
include 'dbconnect.php';
mysql_query("SET NAMES utf8;");
$sql = mysql_query("SELECT * From courseEnglish");
$courseInfo = array();
while ($row_course = mysql_fetch_assoc($sql))
$courseInfo[] = $row_course;
it gives me a php array from the db, but in order to present the data i need to use:
echo $courseInfo[2]['Course'];
i would like for the array to be so i can just type somthing like:
echo $courseInfo[2][2];
is there an option for changing the code so ill have an array i can loop on with just indexes?

I think that you're looking for mysql_fetch_row, which does the same as mysql_fetch_assoc, except for the fact that it returns a numerically indexed array. here's the link to the docs.
Having said that, you might want to consider ditching the deprecated mysql_* extension, in favour of either mysqli_* (the i stands for improved), or the fully OO-style PDO extension. Check the red box at the top of any mysql_* function's manual page, it contains links to the preferred counterpart-function...
But all things considered, looking at your query (SELECT * FROM ...), I'd not use a numerically indexed array at all to get the results. If your table contains more than 1 field, you'll hit trouble sooner or later, when trying to work out what piece of data is coming from what field. Seriously... just use an assoc array, or even better: use objects.
Suppose you change the table layout (add/remove certain fields?), it'll be hell to maintain your code in that case. Still, it's up to you to decide, but I thought I'd might mention this.

Maybe this..?
foreach ($courseInfo as $course_index = > $course_content)
foreach ($course_content as $field)
echo $field;
cheers

Try this :
while ($row_course = mysql_fetch_array($sql))

Related

how to show the result of a query on my website

so I want to show the result of my query, and I can't seem to find anything that works.
this is what I have so far and I have no idea why it won't work.
daydream festival <?php
$queryday="SELECT `tickets_MAX`-`tickets_VERKOCHT` AS `tickets_over` FOR `evenementdata` WHERE `ev id`=1";
$resultday=mysql_query($queryday);
$rowday = mysql_fetch_assoc($resultday);
echo $rowday;?> tickets left
Building on other reasons why this won't print anything like your rows not existing, or misnaming things.
If I'm not mistaken mysql_fetch_assoc returns an array, echo does not print arrays. You need to use print_r($rowday); - Assuming that $rowday contains data.
I'm making a few assumptions here, but I think it's likely that you should do it like:
<?php
$queryday="SELECT `tickets_MAX`-`tickets_VERKOCHT` AS `tickets_over` FROM `evenementdata` WHERE `ev_id`=1";
$resultday=mysql_query($queryday);
$rowday = mysql_fetch_assoc($resultday);
print_r($rowday);
?>
That being said, I would strongly recommend not using the mysql_ functions, since they are now being depreciated. You should do some research into The PHP Data Objects (PDO).

How to merge some static data with json encode mysql array data?

I am trying to merge a static data with json encode array data for output. Here is my php code:
$arr = array();
$rs = mysql_query("SELECT id, name, picture, mail, gender, birthday FROM users WHERE id='$logged_id' ");
while($obj = mysql_fetch_object($rs)) {
$arr[] = $obj;
}
echo '{"users":'.json_encode($arr).'}';
Now I want to merge other data with it:
$user_ip = array("user_ip" => $user_ip_address);
I have tried array_merge($arr, $user_ip). But it didn't work. I think this is not correct json array format if I merge with existing data array. Please let me know what to do how to output other data as well as current data coming from mysql with json encode.
I am getting such output with my existing code, which is correct:
{"users":[{"id":"14","name":"Sonu Roy","picture":"image012.jpg","mail":"myemail#gmail.com","gender":"Male","birthday":"1983-01-11"}]}
But now I want to add other variable e.g $user_ip_address as user's data joining with current output data like this:
{"users":[{"id":"14","name":"Sonu Roy","picture":"image012.jpg","mail":"myemail#gmail.com","gender":"Male","birthday":"1983-01-11",user_ip:"127.0.0.1"}]}.
I want to get it in this way. How to do it? Please let me know. Thanks in advance.
try this:
echo json_encode(array('users' => $arr, 'user_ip' => $user_ip_address));
on a side note:
you should use PHP PDO class to connect and query the database.
mysql_fetch_object returns an object, not an array. So, what are you doing by $arr[] = $obj; is just adding an object into an array. So, the actual structure of the $arr is something like
$arr => [
[0] => Object(....),
[1] => Object(....),
....
]
In your particular case, I assume you are fetching single row by primary key, so there are only one object.
THe simpliest way to fix this is to add a field to an object. I haven't worked with PHP since 5.3, so can't be sure, but it's as simple as adding
$obj->user_ip = $user_ip_address;
inside the loop.
Btw, a couple of questions for you:
Why do you use loop if it should result in a single row?
Why you are embedding the variable directly into SQL query. It's quite vulnerable, read about sql-injections and how to prevent it (one day I was really tired telling people here on SO to use PDO and prepared statements, so just go read about it),
Have you read the documentation about mysql_fetch_object and array_merge? Why not (because if you have read it you wouldn't be asking the question).
Tried debugging? E.g. attaching a debugger and watching for variables contents? Inserting logging or (God forgive me) debug print with echo?
"Didn't work" is a quite bad error description. This time you was lucky, because the error was obvious. Next time, please, be more specific.

An imported array from mysql works, but the array can't be used by php as an array?

The code below won't work because of this line $params=array($data);. It needs something other than $data. Or it needs something to happen with $data prior to this line.
If the line is written as $params=array("A", "B", "C", "D"); then it works great, but my array is in the $data variable, not written out like that. If there is a way to get the array converted to being written out like that, that would work too.
The end result should show every possible combination (not permutation) of the contents of the array. Like in the example above it shows ABC, BD, etc.
$data = mysql_query('SELECT weight FROM my_table WHERE session_id = "' . session_id() . '"');
$params=array($data);
$combinations=getCombinations($params);
function getCombinations($array)
{
$length=sizeof($array);
$combocount=pow(2,$length);
for ($i=1; $i<$combocount; $i++)
{
$binary = str_pad(decbin($i), $length, "0", STR_PAD_LEFT);
$combination='';
for($j=0;$j<$length;$j++)
{
if($binary[$j]=="1")
$combination.=$array[$j];
}
$combinationsarray[]=$combination;
echo $combination."<br>";
}
return $combinationsarray;
}
mysql_query() only returns a result resource ID. To retrieve data, you must use one of the "fetch" commands, for example
$params = array();
while ($row = mysql_fetch_assoc($data)) {
$params[] = $row['weight'];
}
Also, your query is possibly vulnerable to SQL injection. I wouldn't implicitly trust the value from session_id(). I'm not entirely sure of this but it may simply retrieve the value from the session cookie.
At the very least, sanitise the value with mysql_real_escape_string(). A more robust solution which would bring your code out of the dark ages would be to use PDO and parameter binding.
$data is not an array. Assuming mysql_query() did not return an error or an empty result (both of which you should check for, by the way--lookup documentation for mysql_error() and mysql_num_rows() perhaps, maybe some others), $data is a resource.
So you want $params=mysql_fetch_array($data) to make it an array. (That assumes that there is only one result. If it might return more than one row, you'll probably want to wrap it in a loop. If you are 100% certain that session_id is unique , then you can get away without the loop, I suppose. You can also get away without the loop if you only care about the first result in a multi-row result, although I'd throw in a LIMIT 1 in your query in that case to improve performance.)
There are lots of options (do you want a numerically indexed array, or one where they keys are the names of the columns, etc.) so read up at http://www.php.net/manual/en/function.mysql-fetch-array.php.
Ok there are alot of fundamental problems with your script. I personally recommend to first read this article and then about the actual function called mysql_fetch_array().
Simply put, what you are receiving from mysql is resource (corrent me if i'm wrong!) and you have to fetch array on that.
$params = mysql_fetch_array($data);
PS: This makes no sense: $params=array($data);

How do I stop MySQL from duplicating every column's entry in returned arrays?

My MySQL queries are returning arrays with duplicate entries: numbered keys and labeled keys with the same data inside. This may be standard, but it seems like a waste, and something that could cause problems if I'm printing values. I mean, not a huge problem, obviously. But I'm just curious if I can stop that. It seems unnecessary. For example:
Array(
[0] => "Ted",
[first_name] => "Ted",
[1] => "Schmidlap",
[last_name] => "Schmidlap"
)
And so on.
I'm pretty new to a lot of this, so this may be a simple question, but Googling doesn't seem to have any answers for me. Anyone know the reason this happens? I'm using PHP's PDO now, but I was doing it straight through the MySQL functions before and the same thing was happening, so I assume it's a byproduct of MySQL interaction.
I can iterate through and unset the numeric ones, because I don't need them, but they're not really in the way right now, so that's just an extra step. Still, is there a way to simply not have them fetched in the first place?
Presumably this is happening after you use mysql_fetch_array (or similar).
You need to add in a flag to specify what array type you want returned or PHP assumes both.
i.e. mysql_fetch_array($result_set, MYSQL_ASSOC|MYSQL_NUM|MYSQL_BOTH)
That depends on the function you are using.
Some functions return both types, others return only one of them.
If you are using PDOStatement->fetch, notice the optional $fetch_style argument it takes.
Your issue is with the mysql_fetch_array function.
If you want only the numbers, use:
$row = mysql_fetch_array($result, MYSQL_NUM)
If you want only the text indexes, use:
$row = mysql_fetch_array($result, MYSQL_ASSOC)
I usually use MySQLi but for PDO you can find more information here: http://us3.php.net/manual/en/pdostatement.fetch.php
Which seems to mean that you should be using this for text indexes:
$row = $statement->fetch(PDO::FETCH_ASSOC);
And this for numeric indexes:
$row = $statement->fetch(PDO::FETCH_NUM);
Also, just to note this since it isn't listed here, if you want an associative array, you can use mysql_fetch_assoc(), or if you want an enumerated (numbered) array use mysql_fetch_row() instead of mysql_fetch_array(). I use this mostly because without it I would often forget the flag, so I got into the habit of just using the specific function.

How do I create a list or an array of objects in PHP?

I'm a .net programmer vb & c#, but I can't seem to figure out how to get my objects into a list or array in PHP.
var mylist = new List<myobject>();
mylist.add(myobject1);
mylist.add(myobject2);
What I have tried.
Products being a property for a collection of orderitems:
$this->Products = getOrderItems();
public function getOrderItems()
{
$items = array();
$count = 0;
// connect to db, query.....
while($row = mysql_fetch_array($result, MYSQL_BOTH)){
$count++;
$items[$count] = ($row);
}
echo 'Count of Order Items...' . $count;
return $items;
}
Am I even close?
$items = array();
while($row = mysql_fetch_array($result, MYSQL_BOTH)) {
$items[] = $row;
}
echo 'Count of Order Items...', count($items);
$this->Products = getOrderItems(); is legal in PHP, but it refers to the (global) function getOrderItems() instead of the class method. class methods and variables always have to be prefixed with $this-> (or self::, if they're static vars) when called from inside the class.
in your sample-code, you have that wrong. getOrderItems is defined as class method, but your call is not $this->-scoped, thus php assumes a function. it should throw an function not found-error.
the [] notation adds an element to the end of an array.
the index of the first element in your sample code is 1 (isn't that the standard case for VB?). php normally starts at 0 - though it's possible (because php-arrays are not real arrays) to start at arbitrary indices i'd recommend to stick with zero.
mysql_fetch_array is an ancient way of working with mysql. nowadays you're better of with mysqli or (even better) PDO.
(...) a list or array in php.
lists, arrays, stacks, whatever: in php everthing is an ordered map (misleadingly called array):
PHP: Arrays: An array in PHP is actually an ordered map. A map is a type that associates values to keys. This type is optimized for several different uses; it can be treated as an array, list (vector), hash table (an implementation of a map), dictionary, collection, stack, queue, and probably more. As array values can be other arrays, trees and multidimensional arrays are also possible.
update:
sorry, i haven't got enough time right now to explain the finer nuances of pdo/mysqli over mysql.
so here are just the basics:
oop: pdo and mysqli are object oriented (tough mysqli got functional aliases)
prep statements: most important: pdo/mysqli got prepared statements. that means, you first prepare the query with placeholders once, then fill in the values later (without the need to prepare the query a second time). this approach has 3 obvious advantages:
performance: it's faster, because the database only has to analyze, compile and optimize the query once (at least with complex queries)
security: no need for quoted strings (happens automatically!), making sql-injection attacks harder
maintainability: the logic and data part of the query are separated, thus easier to read and you don't have to do a lot of string concenation
driver driven: pdo is not database specific. there are several supported db-systems, making it easier to port your code to other db-backends (but it's not an db-abstraction layer like ODBC, so the SQL still has to be compatible) and increasing reusability
of course, there's a lot more to it
What orlandu63 posted is correct - using $items[] = $row means that $row is appended numerically as the next element of $items.
Another option is that if there's an id field in $row, you can do $items[$row->id] = $row;, which has the advantage of indexing your array and making it easier to find a given item.
I really suggest reading through http://www.php.net/manual/en/language.types.array.php, which will explain to you some of the cool things PHP allows with arrays.

Categories