Does PHP have a construct similar to .NET's DataSet? - php

How can I implement a DataSet in PHP like .NET?
I want this class to read data from database only once, then I should be able to use the data without connecting again to MySQL to run queries.
select * from user
When I run this query on the DataSet the data is fetched from memory.
How can I implement this mechanism in PHP?

You could push your data into an array like this:
$result = mysql_query( 'select * from user' );
$results = array();
while ( $row = mysql_fetch_array( $result ) ) {
array_push( $results, $row );
}
mysql_close();
Then you can do whatever operations you want on the array...
foreach( $results as $record ){
$foo = $record['col_name'];
//...
}

What you are describing is the DataSet / DataTable data container classes of .NET which can work in disconnected mode.
A DataReader is kind of a cursor and needs to have the connection open in order to move through the result set of the underlying query.
In PHP you could do this:
<?PHP
$user_name = "root";
$password = "";
$database = "addressbook";
$server = "127.0.0.1";
$db_handle = mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database, $db_handle);
if ($db_found) {
$SQL = "SELECT * FROM tb_address_book";
$result = mysql_query($SQL);
while ($db_field = mysql_fetch_assoc($result)) {
print $db_field['ID'] . "<BR>";
print $db_field['First_Name'] . "<BR>";
print $db_field['Surname'] . "<BR>";
print $db_field['Address'] . "<BR>";
}
mysql_close($db_handle);
}
else {
print "Database NOT Found ";
mysql_close($db_handle);
}
?>

I don't think php can provide what you're looking for as it's very much text code and HTML driven, so you don't get the fancy GUI objects like you do in .net. PEAR provides a lot of source code that will produce data grids, that you could possibly investigate, all stored in code like arrays etc. I'm relatively new to php, so maybe someone would disagree...

Related

Error is Trying to get property 'id' of non-object, but seems object has

I am using PHP for 1st time.
I am just trying to fetch data from database. Here is my code -
try{
///try to connect with database
$conn=new PDO("mysql:host=localhost:3306;dbname=try", "root", "abcdef12");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $ex){
echo "error";
}
$mysqlcode="SELECT * FROM users";
$ret=$conn->query($mysqlcode);
foreach($ret as $ret1)
print $ret1->id;
in the browser,
showing this error:
Notice: Trying to get property 'id' of non-object in /opt/lampp/htdocs/secAsite/verifylogin.php on line 44
In the users table, I have 4 data.
In here, why $ret seems non object. I can't find anything wrong. How to fetch data. Or debug the object.
I have checked your code. Everything is fine. Just do this.
foreach($ret as $ret1)
print $ret1['id'];
You are not getting data because you are not fetching it..
you have to fetch the data before print it
updated code
$mysqlcode = "SELECT * FROM users";
$ret = $conn->query($mysqlcode);
if ($ret->num_rows > 0) {
// output data of each row
while($row = $ret->fetch_assoc()) {
echo "id: " . $ret["id"] . "<br>";
}
} else {
echo "0 results";
}
$conn->close();
that'll work fine.
Before trying to use Object Oriented PHP, is much easier to understand Procedural. Take a look at the code below.
First, connect to database:
<?php
//Store log in info into variables
$servername = 'localhost';
$serveruser = 'youruser';
$serverpassword = 'yourpassword';
$serverdatabase = 'yourdatabase';
// Create connection
$conn = mysqli_connect( $servername, $serveruser, $serverpassword, $serverdatabase );
if ( !$conn ) {echo "Connection Fail" . mysqli_connect_error();}
//else {echo "Connected to database $serverdatabase";}
?>
Then, call the information from your database and your table and store it into an associative array $data
$sql = "SELECT * FROM `table`";
$result = mysqli_query($conn, $sql);
$data = mysqli_fetch_all($result, MYSQLI_ASOCC);
mysqli_free_result($result);
Now you can use the array to print the results with print_r
echo '<pre>'; print_r($data); echo '</pre>';}
Now you are ready to use foreach depending on your table columns,for example if you have ID column then
<?php foreach ($data as $value){
echo $value['id]."<br>";
} ?>
It will print out all the IDs. Hope this helps.

Parse database table from GET request

Good morning
I've been struggling to work arround this recently, as I'm fairly new to PHP & MySQL in general.
I have a database with a table "videos" in which I store useful informations about videos and I have a document called search.php who will display specific videos based on GET Request.
A Request looks like this:
http://example.ex/search.php?tag=EXAMPLE1
The logic would be to store the tag value like this:
if(!empty($_GET["tag"])){
// Get videos from tag only
$curTag = strval($_GET["tag"]);
displayByTag($curTag); //the function that parse the database
}
I have my connection ready:
$server = "localhost";
$username = "root";
$password = "";
$db = "mydatabase";
$conn = mysqli_connect($server, $username, $password, $db);
$query = "SELECT * FROM videos";
$response = array();
$result = mysqli_query($conn, $query);
while($row = mysqli_fetch_array($result)) {
$response[] = $row;
}
Technically as of right now, my table is stored inside $response[].
What I need to do is to parse the database and looks for the "tags" column, split its string value ("EXAMPLE1,EXAMPLE2,EXAMPLE3" in table) and then see if the GET value matches one of them.
That's when I need your help. I understand the logic, the steps, but can't "translate" it into PHP. Here's what I would do (human-language):
function displayByTag($tag) {
for each $video-item inside $array {
$tagsArray = explodes(",", $video-item[tags-column]); //That's how I split the tags stored inside the table
for i as integer = 0 to $tagsArray.length {
if $tagsArray(i) == $tag {
//THATS A MATCH
}
}
}
}
Is this the right way to do it ? And how can I translate that "human" language into PHP code ?
Thanks for the help.
After a little bit of testing and debugging I got my function working pretty easily. If anyone is interested:
function searchVideos($search) {
$currentSearchQueries = explode(" ", strtoupper($search)); //Split the searched tags in a array and make them to uppercase for easier comparaison.
//Establish a connection the MySql Database
$server = "localhost";
$username = "root";
$password = "";
$db = "mydatabase";
$conn = mysqli_connect($server, $username, $password, $db);
//Select all the entries from my 'videos' table
$query = "SELECT * FROM videos";
$response = array();
$result = mysqli_query($conn, $query);
while($row = mysqli_fetch_array($result)){
$response[] = $row; //Place them into a array
}
//Parse the array for matching entries
foreach ($response as &$video){ //Each entries goes through the process
foreach ($currentSearchQueries as $t) {
//We compare if one the tags searched matches for this particular entry
if((strtoupper($video[tags]) == $t) {
//THAT'S A MATCH
}
}
}
}
It was very fun to code, looking forward for new experiences !

Why do i get more results from my mysql query in php then what i ask for?

I am getting return values that do not exist in my current database. Even if i change my query the return array stays the same but missing values. How can this be what did i do wrong?
My MYSQL server version is 10.0.22 and this server gives me the correct result.
So the issue must be in PHP.
My code:
$select_query = "SELECT process_state.UID
FROM process_state
WHERE process_state.UpdateTimestamp > \"[given time]\"";
$result = mysql_query($select_query, $link_identifier);
var_dump($result);
Result:
array(1) {
[1]=> array(9) {
["UID"]=> string(1) "1"
["CreationTimestamp"]=> NULL
["UpdateTimestamp"]=> NULL
["ProcessState"]=> NULL
}
}
Solution:
I have found this code somewhere in my program. The program used the same name ass mine. This function turns the MYSQL result into a array. This happens between the result view and my script. This was done to make the result readable.
parent::processUpdatedAfter($date);
Function:
public function processUpdatedAfter($date)
{
$result = parent::processUpdatedAfter($date);
$array = Array();
if($result != false)
{
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$array[$row["UID"]]["UID"] = $row["UID"];
$array[$row["UID"]]["CreationTimestamp"] = $row["CreationTimestamp"];
$array[$row["UID"]]["UpdateTimestamp"] = $row["UpdateTimestamp"];
$array[$row["UID"]]["ProcessState"] = $row["ProcessState"];
}
return $array;
}
return false;
}
I edited this and my script works fine now thanks for all the help.
Note that, var_dump($result); will only return the resource not data.
You need to mysql_fetch_* for getting records.
Example with MYSQLi Object Oriented:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT process_state.UID
FROM process_state
WHERE process_state.UpdateTimestamp > \"[given time]\"";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
/* fetch associative array */
while ($row = $result->fetch_assoc()) {
echo $row['UID'];
}
}
else
{
echo "No record found";
}
$conn->close();
?>
Side Note: i suggest you to use mysqli_* or PDO because mysql_* is deprecated and closed in PHP 7.
You are var_dumping a database resource handle and not the data you queried
You must use some sort of fetching process to actually retrieve that data generated by your query.
$ts = '2016-09-20 08:56:43';
$select_query = "SELECT process_state.UID
FROM process_state
WHERE process_state.UpdateTimestamp > '$ts'";
$result = mysql_query($select_query, $link_identifier);
// did the query work or is there an error in it
if ( !$result ) {
// query failed, better look at the error message
echo mysql_error($link_identifier);
exit;
}
// test we have some results
echo 'Query Produced ' . mysql_num_rows($result) . '<br>';
// in a while loop if more than one row might be returned
while( $row = mysql_fetch_assoc($result) ) {
echo $row['UID'] . '<br>';
}
However I have to mention Every time you use the mysql_
database extension in new code
a Kitten is strangled somewhere in the world it is deprecated and has been for years and is gone for ever in PHP7.
If you are just learning PHP, spend your energies learning the PDO or mysqli database extensions.
Start here
$select_query = "SELECT `UID` FROM `process_state ` WHERE `UpdateTimestamp` > \"[given time]\" ORDER BY UID DESC ";
$result = mysql_query($select_query, $link_identifier);
var_dump($result);
Try this hope it will works

how to acess my database elements using the for loop?

I'm learning PHP and I'm well versed with Java and C. I was given a practice assignment to create a shopping project. I need to pull out the products from my database. I'm using the product id to do this. I thought of using for loop but I can't access the prod_id from the database as a condition to check! Can anybody help me?! I have done all the form handling but I need to output the products. This is the for-loop I am using. Please let me know if I have to add any more info. Thanks in advance :)
for($i=1; $i + 1 < prod_id; $i++)
{
$query = "SELECT * FROM products where prod_id=$i";
}
I would suggest that you use PDO. This method will secure all your SQLand will keep all your connections closed and intact.
Here is an example
EXAMPLE.
This is your dbc class (dbc.php)
<?php
class dbc {
public $dbserver = 'server';
public $dbusername = 'user';
public $dbpassword = 'pass';
public $dbname = 'db';
function openDb() {
try {
$db = new PDO('mysql:host=' . $this->dbserver . ';dbname=' . $this->dbname . ';charset=utf8', '' . $this->dbusername . '', '' . $this->dbpassword . '');
} catch (PDOException $e) {
die("error, please try again");
}
return $db;
}
function getproduct($id) {
//prepared query to prevent SQL injections
$query = "SELECT * FROM products where prod_id=?";
$stmt = $this->openDb()->prepare($query);
$stmt->bindValue(1, $id, PDO::PARAM_INT);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $rows;
}
?>
your PHP page:
<?php
require "dbc.php";
for($i=1; $i+1<prod_id; $i++)
{
$getList = $db->getproduct($i);
//for each loop will be useful Only if there are more than one records (FYI)
foreach ($getList as $key=> $row) {
echo $row['columnName'] .' key: '. $key;
}
}
First of all, you should use database access drivers to connect to your database.
Your query should not be passed to cycle. It is very rare situation, when such approach is needed. Better to use WHERE condition clause properly.
To get all rows from products table you may just ommit WHERE clause. Consider reading of manual at http://dev.mysql.com/doc.
The statement selects all rows if there is no WHERE clause.
Following example is for MySQLi driver.
// connection to MySQL:
// replace host, login, password, database with real values.
$dbms = mysqli_connect('host', 'login', 'password', 'database');
// if not connected then exit:
if($dbms->connect_errno)exit($dbms->connect_error);
$sql = "SELECT * FROM products";
// executing query:
$result = $dbms->query($sql);
// if query failed then exit:
if($dbms->errno)exit($dbms->error);
// for each result row as $product:
while($product = $row->fetch_assoc()){
// output:
var_dump($product); // replace it with requied template
}
// free result memory:
$result->free();
// close dbms connection:
$dbms->close();
for($i=1;$i+1<prod_id;$i++) {
$query = "SELECT * FROM products where prod_id=$i";
$result = mysqli_query($query, $con);
$con is the Database connection details
you can use wile loop to loop thru each rows
while ($row = mysqli_fetch_array($result))
{
......
}
}
Hope this might work as per your need..
for($i=1; $i+1<prod_id; $i++) {
$query = "SELECT * FROM products where prod_id = $i";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
print_r($row);
}
}
I think you want all records from your table, if this is the requirement you can easily do it
$query = mysql_query("SELECT * FROM products"); // where condition is optional
while($row=mysql_fetch_array($query)){
print_r($row);
echo '<br>';
}
This will print an associative array for each row, you can access each field like
echo $row['prod_id'];

Multi database schema migration (php/mysql)

I have an application where each user has their own database and share the same schema. (I have another thread discussing this, so I don't need any information on this)
When migrating the databases, I wrote a script shown below:
<?php
$sql = <<<SQL
ALTER TABLE xyz....;
ALTER TABLE abc.....;
SQL;
$sql_queries = explode(";", $sql);
$exclude_dbs = array();
$conn = mysql_connect("localhost", "USER", "PASSWORD");
$show_db_query = mysql_query('SHOW databases');
$databases = array();
while ($row = mysql_fetch_assoc($show_db_query))
{
if (!in_array($row['Database'], $exclude_dbs))
{
$databases[] = $row['Database'];
}
}
foreach($databases as $database)
{
mysql_select_db($database, $conn);
echo "Running queries on $database\n***********************************\n";
foreach($sql_queries as $query)
{
if (!empty($query))
{
echo "$query;";
if (!mysql_query($query))
{
echo "\n\nERROR: ".mysql_error()."\n\n";
}
}
}
echo "\n\n";
}
?>
It has been working fine without any problems. I then use stepancheg / mysql-diff to make sure the database schemas are good.
Are there any things I should be doing when migrating databases? (I test on a staging server before hand also)
Your approach seems to be working, and the use of mysql-diff is good. Have you considered using mysqldump to back up actual data? It's a more conventional approach than a custom script.

Categories