I am new to writing web services and I cannot seem to figure this out! I have a simple php restful service that returns a json response, but I don't have any keys in the response (I don't know if that's the right term) What I get is something like this.
(
(
"name",
qty,
"image",
"price",
"date"
)
I am positive I am doing something wrong here.
Here is my service:
<?php
header('Content-type: application/json');
class InventoryAPI {
private $db;
function __construct() {
$this->db = new mysqli('localhost', 'user', 'pass', 'dbname');
$this->db->autocommit(FALSE);
}
function __destruct() {
$this->db->close();
}
function checkInv() {
$query = "SELECT model, sku, quantity, stock_status_id, image, price, date_available FROM table_name";
$result = $this->db->query($query);
$rows = array();
$i = 0;
while($row = $result->fetch_row())
{
$rows[] = $row;
$i++;
}
$result->close();
$this->db->close();
echo json_encode($rows);
}
}
$api = new InventoryAPI;
$api->checkInv();
?>
I'm assuming you will want to use fetch_assoc() instead of fetch_row(). fetch_assoc() will return an array with keys the same name as the columns. fetch_row() will return an enumerated array based on the column position. For example: model is 0, sku is 1.
You can always test this out by printing out the array.
while($row = $result->fetch_row())
{
print_r($row);
}
Related
I'm a newbie in oop style. I start practicing it since last week and I make simple CRUD website. but i got a problem when i tried fetching rows from mysql db its always display 1 row.
my created a class named class.user.php
and it shows here:
include "db_config.php";
class User{
private $db;
public function __construct(){
$this->connect();
}
private function connect($db_connect=true){
if ($db_connect){
$this->db = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
if(mysqli_connect_errno()) {
printf("DB Connect failed: %s\n", mysqli_connect_error());
exit;
}
}
}
public function get_tutoriallist(){
$db = $this->db;
if(empty($db)){
$this->connect();
$db = $this->db;
}
try {
$stmt = $this->db->prepare('SELECT * FROM `topic`');
$stmt->execute();
$result = $stmt->get_result();
$dataArray = array();
while($row = $result->fetch_assoc()){
$count_row = $result->num_rows;
if ($count_row == 1) {
$dataArray[] = $row;
}
}
return ($dataArray);
mysqli_close($db);
$this->db = null;
} catch (Exception $e) {
echo $e->errorMessage();
}
}
}
and i call it using this:
$data = $user->get_tutoriallist();
if (!empty($data)) {
foreach ($data as $row){
echo "<tr>";
echo"<td>".$row['category']."</td>";
echo"<td>".$row['title']."</td>";
echo"<td>".$row['detail']."</td>";
echo"<td>".$row['photo']."</td>";
echo"<td>".$row['video_link']."</td>";
echo"<td>".$row['date_post']."</td>";
echo"<td class='option'><center><a href ='#' class='edit'>Edit</a>
<a href='#'>Delete</a></center></td>";
echo "</tr>";
}
}else{
echo '<tr><td colspan="6"><center><h2>No entries</h2></center></td></tr>';
}
I'm not quite sure what is going on here:
while($row = $result->fetch_assoc()){
$count_row = $result->num_rows;
if ($count_row == 1) {
$dataArray[] = $row;
}
But normally, you just iterate through the results and append them to an array:
while($row = $result->fetch_assoc()){
$dataArray[] = $row;
}
Then your $datArray has all the rows in it.
This is because you are appending to the result array only when $current_row == 1.
Try changing your while loop like this:
while($row = $result->fetch_assoc()){
$dataArray[] = $row;
}
Also, you are not closing the db connection correctly, you are mixing OOP style with procedural mysqli functions. This is how it should be:
$this->db->close();
$this->db = null;
Finally, you should return the data array after you closed the connection. If you returned the data array first and closed the connection after, that code wont get executed.
So your last three lines should look like this:
$this->db->close();
$this->db = null;
return $dataArray;
Scenario:
I have a SQL Query INSERT INTO dbo.Grades (Name, Capacity, SpringPressure) VALUES ('{PHP}',{PHP}, {PHP})
The data types are correct.
I need to now get the latest IDENTIY which is GradeID.
I have tried the following after consulting MSDN and StackOverflow:
SELECT SCOPE_IDENTITY() which works in SQL Management Studio but does not in my php code. (Which is at the bottom), I have also tried to add GO in between the two 'parts' - if I can call them that - but still to no avail.
The next thing I tried, SELECT ##IDENTITY Still to no avail.
Lastly, I tried PDO::lastInsertId() which did not seem to work.
What I need it for is mapping a temporary ID I assign to the object to a new permanent ID I get back from the database to refer to when I insert an object that is depended on that newly inserted object.
Expected Results:
Just to return the newly inserted row's IDENTITY.
Current Results:
It returns it but is NULL.
[Object]
0: Object
ID: null
This piece pasted above is the result from print json_encode($newID); as shown below.
Notes,
This piece of code is running in a file called save_grades.php which is called from a ajax call. The call is working, it is just not working as expected.
As always, I am always willing to learn, please feel free to give advice and or criticize my thinking. Thanks
Code:
for ($i=0; $i < sizeof($grades); $i++) {
$grade = $grades[$i];
$oldID = $grade->GradeID;
$query = "INSERT INTO dbo.Grades (Name, Capacity, SpringPressure) VALUES ('" . $grade->Name . "',". $grade->Capacity .", ".$grade->SpringPressure .")";
try {
$sqlObject->executeNonQuery($query);
$query = "SELECT SCOPE_IDENTITY() AS ID";
$newID = $sqlObject->executeQuery($query);
print json_encode($newID);
} catch(Exception $e) {
print json_encode($e);
}
$gradesDictionary[] = $oldID => $newID;
}
EDIT #1
Here is the code for my custom wrapper. (Working with getting the lastInsertId())
class MSSQLConnection
{
private $connection;
private $statement;
public function __construct(){
$connection = null;
$statement =null;
}
public function createConnection() {
$serverName = "localhost\MSSQL2014";
$database = "{Fill In}";
$userName = "{Fill In}";
$passWord = "{Fill In}";
try {
$this->connection = new PDO( "sqlsrv:server=$serverName;Database=$database", $userName, $passWord);
$this->connection->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
}
catch( PDOException $e ) {
die("Connection Failed, please contact system administrator.");
}
if ($this->connection == null) {
die("Connection Failed, please contact system administrator.");
}
}
public function executeQuery($queryString) {
$results = array();
$this->statement = $this->connection->query( $queryString );
while ( $row = $this->statement->fetch( PDO::FETCH_ASSOC ) ){
array_push($results, $row);
}
return $results;
}
public function executeNonQuery($queryString) {
$numRows = $this->connection->exec($queryString);
}
public function getLastInsertedID() {
return $this->connection->lastInsertId();
}
public function closeConnection() {
$this->connection = null;
$this->statement = null;
}
}
This is PDO right ? better drop these custom function wrapper...
$json = array();
for ($i=0; $i < sizeof($grades); $i++) {
//Query DB
$grade = $grades[$i];
$query = "INSERT INTO dbo.Grades (Name, Capacity, SpringPressure)
VALUES (?, ?, ?)";
$stmt = $conn->prepare($query);
$success = $stmt->execute(array($grade->Name,
$grade->Capacity,
$grade->SpringPressure));
//Get Ids
$newId = $conn->lastInsertId();
$oldId = $grade->GradeID;
//build JSON
if($success){
$json[] = array('success'=> True,
'oldId'=>$oldId, 'newId'=>$newId);
}else{
$json[] = array('success'=> False,
'oldId'=>$oldId);
}
}
print json_encode($json);
Try the query in this form
"Select max(GradeID) from dbo.Grades"
I'm fairly new to PHP and I've been looking around and can't seem to find the specific answer I'm looking for.
I want to make a SQL query, such as this:
$result = mysqli_query($connection, $command)
if (!$result) { die("Query Failed."); }
// Create my array here ... I'm thinking of maybe having to
// make a class that can hold everything I need, but I dunno
while($row = mysqli_fetch_array($result))
{
// Put the row into an array or class here...
}
mysqli_close($connection);
// return my array or class
Basically I want to take the entire contents of the result and create an array that I can access in a similar fashion as the row. For example, if I have a field called 'uid' I want to be able to get that via myData['uid']. I guess since there could be several rows, maybe something more like myData[0]['uid'], myData[1]['uid'], etc.
Any help would be appreciated.
You can do:
$rows = [];
while($row = mysqli_fetch_array($result))
{
$rows[] = $row;
}
You might try to use mysqli_result::fetch_all() for arrays:
$result = mysqli_query($connection, $command)
if (!$result) { die("Query Failed."); }
$array = $result->fetch_all();
$result->free();
mysqli_close($connection);
NOTE: This works with MySQLND only.
For class, you might try to use something like this:
$result = mysqli_query($connection, $command)
if (!$result) { die("Query Failed."); }
while($model = $result->fetch_assoc()){
// Assuming ModelClass is declared
// And have method push() to append rows.
ModelClass::push($model);
}
$result->free();
mysqli_close($connection);
OR this:
// Base Model - abstract model class.
class ModelClass extends BaseModel {
// constructor
public function __construct(mysqli &$dbms){
// $this->dbms is MySQLi connection instance.
$this->dbms = &$dbms;
// $this->models is buffer for resultset.
$this->models = array();
}
// destructor
public function __destruct(){
unset($this->dbms, $this->models);
}
public function read(){
$result = $this->dbms->query($command);
if($this->dbms->errno){
throw new Exception($this->dbms->error, $this->dbms->errno);
}
$this->models = $result->fetch_all();
$result->free();
}
}
//object oriented style mysqli
//connect to your db
$mysqli = new mysqli("host", "user", "password", "dbname");
$result = $mysqli->query("SELECT * FROM `table`");
//use mysqli->affected_rows
for ($x = 1; $x <= $mysqli->affected_rows; $x++) {
$rows[] = $result->fetch_assoc();
}
//this will return a nested array
echo "<pre>";
print_r($rows);
echo "</pre>";
edit this and put it on a class and just call it anytime you're going to make a query with your database.
fetch_array: https://www.php.net/manual/en/mysqli-result.fetch-array.php
$result = $mysqli_connection->query($sql);
$row = $result->fetch_array(MYSQLI_ASSOC);
print_r($row);
I'm having trouble printing out the values from my MySQLi query. Here is the db connection class that I am using.
class db
{
public function __construct()
{
$this->mysqli = new mysqli('localhost', 'root','', 'database');
if (mysqli_connect_errno())
{
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
}
public function Query($SQL)
{
$this->SQL = $this->mysqli->real_escape_string($SQL);
$this->Result = $this->mysqli->query($SQL);
if ($this->Result == true)
return true;
else
die('Problem with Query: ' . $this->SQL);
}
public function Get($field = NULL)
{
if ($field == NULL)
{
$data = array();
while ($row = $this->Result->fetch_assoc())
{
$data[] = $row;
}
}
else
{
$row = $this->Result->fetch_assoc();
$data = $row[$field];
}
$this->Result->close();
return $data;
}
public function __destruct()
{
$this->mysqli->close();
}
}
Running a query
$db = new db;
$db->Query("SELECT * FROM tblclients WHERE clientid = $this->id");
$result = $db->Get();
echo $result['clientid'];
I'm getting error
PHP Notice: Undefined index: clientid
However I know the values are getting passed to the $results array when I run
print_r ($result);
I get this returned
Array ( [0] => Array ( [clientid] => 2 [firstname] => John [lastname] => Doe [dob] => 1962-05-08))
For what its worth, if I try echo $db->Get('firstname'); everything works. Been banging my head against the wall for a while now, any help appreciated.
As you can see you have an array inside another array. To get what you need you need to go like this:
$result[0]['clientid'];
So what we're doing here is you are first calling the $result variable which contains an array with an index of [0], then this array contains the column names from your query (ex: ['clientid']).
So you basically have to go deeper than $result['clientid'] to get your data from the database by firstly calling the array that contains those keys from the database.
To un-nest that array, do something like:
$result = $db->Get();
$normal_result = 0;
foreach ($result as $value)
{
$normal_result = $value;
}
You can use this inside your method, so you'll get normal results only in the future.
I was just wondering how i would be able to code perform an SQL query and then place each row into a new array, for example, lets say a table looked like the following:
$people= mysql_query("SELECT * FROM friends")
Output:
| ID | Name | Age |
--1----tom----32
--2----dan----22
--3----pat----52
--4----nik----32
--5----dre----65
How could i create a multidimensional array that works in the following way, the first rows second column data could be accessed using $people[0][1] and fifth rows third column could be accessed using $people[4][2].
How would i go about constructing this type of array?
Sorry if this is a strange question, its just that i am new to PHP+SQL and would like to know how to directly access data. Performance and speed is not a issue as i am just writing small test scripts to get to grips with the language.
$rows = array();
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
$rows[] = $row;
}
Are you open to using a DB module, like the PEAR::DB module? If so, check out this article by Paul Dubois on Writing Scripts with PHP's Pear DB Module. The Module has been superseded, but it will show you the basics of some more advanced (and more commonplace) DB practices.
As for your actual question, you could iterate over all the rows and populate an array...
$dsn = "mysqli://testuser:testpass#localhost/test";
$conn =& DB::connect ($dsn);
if (DB::isError ($conn)) { /* ... */ }
$result =& $conn->query ("SELECT * FROM friends");
if (DB::isError ($result)){ /* ... */ }
while ($row =& $result->fetchRow()) {
$people[] = $row;
}
$result->free ();
Or you could write an object which implements the ArrayAccess interface, requesting a particular row when you refer to that index. (This code could be completely wrong but here's my try)
class FriendsTable implements ArrayAccess {
function offsetGet($key) {
$result =& $conn->query ("SELECT * FROM friends LIMIT $key, 1",); // careful; this is vulnerable to injection...
if (DB::isError ($result)){ die ("SELECT failed: " . $result->getMessage () . "\n"); }
$people = null;
if ($row =& $result->fetchRow ()) {
$people = $row;
}
$result->free ();
return $people;
}
function offsetSet($key, $value) {
/*...*/
}
function offsetUnset($key) {
/*...*/
}
function offsetExists($offset) {
/*...*/
}
}
$people = new FriendsTable();
$person = $people[2]; // will theoretically return row #2, as an array
... or something.
$array = array();
$sql = "SELECT * FROM friends";
$res = mysql_query($sql) or trigger_error(mysql_error().$sql);
while($row = mysql_fetch_assoc($res)) $array[]=$row;