navigating an array of objects in javascript - php

Need help forming javascript objects from MySQL rows of data. I'm using IE9 and Chrome on Windows-7.
I've managed to get what I believe to be an array (of objects) in Javascript from mySQL data. I can use alerts to see the whole array, as well as one individual object, as in my code.
What I cannot do yet is navigate a particular object's properties (the column values of a particular row in the database).
What I need to do is iterate through myObjects, and use the property values in each to create some graphics. I also need to be able to retrieve each object's properties at any time going forward as well.
UPDATE: including my php located in head html object:
<?php
//------------------- constants --------------------
$objects = array();
$jsonData = "";
//------------------- database connection ----------
$data_source = 'mysql:host=localhost;dbname=myDB';
$db_user = 'root';
$db_password = 'password';
$conn = new PDO($data_source, $db_user, $db_password,
array(PDO::ATTR_EMULATE_PREPARES => false,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_PERSISTENT));
//prepare query
$stmt = $conn->prepare("SELECT * FROM tblbranchstatus");
$stmt->execute();
//fetch each row of results
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$rows[] = json_encode($row);
}
?>
var ART = {};
//capture data from database as json string data
ART.strJSON = <? php echo json_encode($rows); ?> ;
//capture json string data as array of javascript objects
//using 'eval' cause I know this data's source and I couldn't get JSON.parse to work
ART.myObjects = eval(ART.strJSON);
ART.branch = ART.myObjects[6];
alert(ART.branch); // this gives me the expected object {"a":"aa", "b":"bb"...}
alert(ART.branch.a); // can't retrieve the property - gives me 'undefined'

This doesn't look like the right thing to do. Here's what you should be doing:
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$rows[] = $row;
}
Don't do json_encode() on each row.
ART.myObjects = <?php echo json_encode($rows); ?>;
You can immediately use the output of json_encode($rows) in your script.
Update
As rightfully mentioned by bfavaretto, you can make this even shorter by encoding all rows in one go:
ART.myObjects = <?php echo json_encode($stmt->fetchAll(PDO::FETCH_ASSOC)); ?>;

I would check if ART.branch is actually a string with the JSON notation rather than the actual object.

Related

How to get entire MongoDB collection with PHP

Using the following code, I can grab a node from a collection:
<?php
$user = "xxxx";
$pwd = 'xxxx';
if (isset($_POST['needleID'])) {
$needleID = $_POST['needleID'];
} else {
echo "needle ID not set";
}
//Manager Class
$connection = new MongoDB\Driver\Manager("mongodb://${user}:${pwd}#localhost:27017");
// Query Class
$filter = ['id'=> $needleID];
$query = new MongoDB\Driver\Query($filter);
// Output of the executeQuery will be object of MongoDB\Driver\Cursor class
$rows = $connection->executeQuery('DBNAME.DBCOLLECTION', $query);
// Convert rows to Array and send result back to javascript as json
$rowsArr = $rows->toArray();
echo json_encode($rowsArr);
?>
However, what I'm really looking to do is get everything from the DBCOLLECTION.
I'm kind of at a loss on how to do this. A few searches either go over my head or are for older versions of the PHP driver, such as this one fetch all data from mongodb collection
If you query on a specific ID, then you will only receive the document with that ID as its value. If you want to retrieve all document in a collection, leave the filter empty, i.e. with $filter = [];.
It is better to use mongoexport for exporting collections. On large collections your code will be slow and will timeout. Consider using pagination for results.

How to get json encoding for a list sql database table names and data in them in php

How can I list names of tables in sql database and the table columns for the each table and then get a json encoding of the results in PHP?
Here is code to display tables:
$result = mysql_query("show tables"); // run the query and assign the result to $result
while($table = mysql_fetch_array($result)) {
// go through each row that was returned in $result
echo($table[0] . "<BR>"); // print the table that was returned on that row.
}
You could create an array/object and add the data to it. To get a json result just call json_encode on the array/object.
Here is what I would do:
// Create an object
$results = new stdClass();
// Get all tables
$result = mysql_query("show tables");
// Always check if the query returned anything to prevent possible errors
if(mysql_affected_rows() > 0) {
// Loop through each table
while($table = mysql_fetch_assoc($result)) {
// Get the columns in the table
$resultColumns = mysql_query("show columns from ".$table);
if(mysql_affected_rows() > 0) {
// Columns found. Create a new property in the object and assign the columns to it
$tableColumns = mysql_fetch_assoc($resultColumns);
$results[$table] = $tableColumns;
}
else {
// No columns found. Create a new property in the object and assign a blank array.
$results[$table] = [];
}
}
}
Now we can return that data as a json with json_encode($results).
http://php.net/manual/en/function.json-encode.php
As a side note, I would look to use mysqli, not mysql (as it is now depreciated). The syntax for it is basically exactly the same, but you need to pass the connection variable as the first parameter in most cases. So it would be useful to use create a database/connection class and call to those methods, instead of calling mysql or mysqli functions directly.
See here: https://www.w3schools.com/php/php_ref_mysqli.asp
And here (an example): https://www.johnmorrisonline.com/simple-php-class-prepared-statements-mysqli/
Note: This is pseudo code and not tested but should be okay. Let me know if you need any help with it.

Getting information from MySQL

I'm having trouble getting info from my MySQL database.
Here is my code :
/********************
* Database Info
********************/
$host = "localhost";
$user = "admin";
$pass = "admin#";
$database = "db_admin";
/********************
* Database connection
********************/
$con = mysqli_connect( $host, $user, $pass, $database );
if (mysqli_connect_errno ()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error ();
}
$result = array();
if (isset($_POST['ID'])) {
$id = $_POST['ID'];
$query = "SELECT * FROM Servers WHERE PID='" .$id. "'";
$result = mysqli_query($con, $query);
}
print("<pre>".print_r($result,true)."</pre>");
My first question, Did I use "isset" function currectly?
Because it doesnt seem like it is actually going though the if statement.
The Url I am using is : #..com/view.php?ID=1
My second question, Did I use the $query correctly?
Because I echo $id and that echoed out a "MySQL Object()"
Finally, the print printed out "Array()"
I'm just starting on PHP, Thanks for the help :)
A few things:
If you're passing the variable in the query string, use $_GET instead of $_POST to retrieve the values.
$result will return an pointer to the recordset, not the rows themselves. You will have to use mysqli_fetch_array() to fetch the rows.
ADD:
If you are sure that you will only have 1 record returning, you can use:
$row = mysqli_fetch_assoc($query);
echo $row['field_name'];
More then 1 record?
while($row = mysqli_fetch_assoc($query)){
echo $row['field_name'];
}
# your first question: if you have a input field with the name="ID", then its good.
Please also post your HTML :)
$var = 'Hello world';
if(isset($var)){ //If the var $var has been set (in this case it is)
echo $var;
} else {
//If $var is not set, then we get in the else
echo 'The var $var is not set';
}
The best thing is debugging the code with a debugger, you may use XDebug, or at least use var_dump(); to see what happens
var_dump($_REQUEST, $result);
Answer to your first question: It's hard to say if you've used it correctly when you haven't said what you're trying to do. I'm presuming that you only want run the code enclosed in the if-statement if the POST variable 'ID' has been received. If so, yes you've done it correctly.
Answer to your second question: I'm presuming on this line you're trying to build a string with a valid MySQL query. You've done that correctly, assuming $_POST['ID'] is a string (or can be converted to a string, see http://www.php.net/manual/en/language.types.string.php#language.types.string.casting).
If you're echoing $id and it's returning an object, however, you'll have a problem. You can't combine a string and an object like that. You'd need to iterate the object with a foreach, for example, and extract the id from that. The rest of the code won't work until that part is resolved.
The thing to investigate now is why $_POST['ID'] is returning an object. You'll need to provide the form code at the very least.

How to display all data from a table?

Well i've been searching google, but I still can't find out how to do this.
I'm a beginner in php so i'm really stumped.
Anyways what I need to do is get all the data from a table and display it on my page.
Like
Contents of row 1
Contents of row 2
etc.
Well that's nice, get down voted for asking for help.
This might help you
print_r() displays information about a variable in a way that's readable by humans.
print_r(), var_dump() and var_export() will also show protected and private properties of objects with PHP 5. Static class members will not be shown.
Remember that print_r() will move the array pointer to the end. Use reset() to bring it back to beginning.
http://php.net/manual/en/function.print-r.php
This is pretty much PHP DB access 101
$pdo = new PDO('mysql:host=localhost;dbname=myDbName', 'username', 'password');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $pdo->prepare('SELECT * FROM a_table');
$stmt->execute();
$resultSet = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($resultSet as $idx => $row) {
echo '<p>Contents of row ', $idx + 1, '</p><dl>';
foreach ($row as $col => $val) {
printf('<dt>%s</dt><dd>%s</dd>',
htmlspecialchars($col),
htmlspecialchars($val));
}
echo '</dl>';
}
I think google should have given you your answer since this is a rather easy to answer question, but when starting, you don't always know what to search for.
Anyways, hope this helps.
<?php
// connect with you database, returns boolean so you know if you succeeded or not
$con = mysql_connect($database,$username,$password);
if(!$scon){
die('Could not connect to database'); // Stop execution if connection fails
}
//create your query
$query = "Place your database query here";
//get the results
$result = mysql_query($query);
//now you want to go through each row of the result table and echo the contents, or
//use them for whatever reason
while($row = mysql_fetch_array($result)){
echo $row['field_you_want_to_display'];
echo $row['another_field_you_want_to_display']; //You see where this is going
}
//After doing what you want, close the connection to the database
mysql_close($con);
?>
Also, you may want to take a look at the documentation of php for find out what functions you have not seen before do.

convert mysql query in to an array format

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);

Categories