Get row from SQL with PHP - php

I am using the following method to query from my SQL database:
function query() {
global $link;
$debug = false;
//get the sql query
$args = func_get_args();
$sql = array_shift($args);
//secure the input
for ($i=0;$i<count($args);$i++) {
$args[$i] = urldecode($args[$i]);
$args[$i] = mysqli_real_escape_string($link, $args[$i]);
}
//build the final query
$sql = vsprintf($sql, $args);
if ($debug) print $sql;
//execute and fetch the results
$result = mysqli_query($link, $sql);
if (mysqli_errno($link)==0 && $result) {
$rows = array();
if ($result!==true)
while ($d = mysqli_fetch_assoc($result)) {
array_push($rows,$d);
}
//return json
return array('result'=>$rows);
} else {
//error
return array('error'=>'Database error');
}
}
$result = $result = query("SELECT * FROM users WHERE email='$email' limit 1");
$name = (what goes here?)
I am trying to get the string name from users, how can I do this?

If your query is right then
try this:
function query() {
global $link;
$debug = false;
//get the sql query
$args = func_get_args();
$sql = array_shift($args);
//secure the input
for ($i=0;$i<count($args);$i++) {
$args[$i] = urldecode($args[$i]);
$args[$i] = mysqli_real_escape_string($link, $args[$i]);
}
//build the final query
$sql = vsprintf($sql, $args);
if ($debug) print $sql;
//execute and fetch the results
$result = mysqli_query($link, $sql);
if (mysqli_errno($link)==0 && $result) {
$rows = array();
if ($result!==true)
while ($d = mysqli_fetch_assoc($result)) {
array_push($rows,$d);
}
//return json
return array('result'=>$rows);
} else {
//error
return array('error'=>'Database error');
}
}
$result = query("SELECT * FROM users WHERE email='$email' limit 1");
$name = $result['result'][0]['name'];

You forgot to pass the value to the function
function query($sql) {
global $link;
$debug = false;
//get the sql query
$args = func_get_args();
$sql = array_shift($args);
//secure the input
for ($i=0;$i<count($args);$i++) {
$args[$i] = urldecode($args[$i]);
$args[$i] = mysqli_real_escape_string($link, $args[$i]);
}
//build the final query
$sql = vsprintf($sql, $args);
if ($debug) print $sql;
//execute and fetch the results
$result = mysqli_query($link, $sql);
if (mysqli_errno($link)==0 && $result) {
$rows = array();
if ($result!==true)
while ($d = mysqli_fetch_assoc($result)) {
array_push($rows,$d);
}
//return json
return array('result'=>$rows);
} else {
//error
return array('error'=>'Database error');
}
}
$result = $result = query("SELECT * FROM users WHERE email='$email' limit 1")

$name = "";
if(! isset($result["error"]) and isset($result["name"])) // check it returns error or not. then check name field exist or not.
{
$name = $result["name"];
}
echo $name;

Related

Why PHP function is returning Only the one row from mysql

I am fetching data from MYSQL database and Looping through the result but its returning only one row !!! can any one explain what's wrong
function getAll()
{
global $con;
$SQL = "SELECT * FROM users";
$stmt = $con->query($SQL);
if($stmt->num_rows > 0){
while($row = $stmt->fetch_row())
{
return $row;
}
}
}
The return should be outside the while loop !
Here is how you can get all the rows :
function getAll()
{
global $con;
$SQL = "SELECT * FROM users";
$stmt = $con->query($SQL);
if($stmt->num_rows > 0){
$arr = array();
while($row = $stmt->fetch_row())
{
$arr[] = $row;
}
return $arr;
}
}
Or you can do something like this return a generator and loop through :
function getAll()
{
global $con;
$SQL = "SELECT * FROM users";
$stmt = $con->query($SQL);
if($stmt->num_rows > 0){
while($row = $stmt->fetch_row())
{
yield $row;
}
}
}
see the result here !
echo '<pre>';
foreach (getAll() as $value) {
print_r($value);
}
Once you hit a return statement all execution of that function stops. You cannot return multiple times.
You can either return an array of all rows:
function getAll()
{
global $con;
$SQL = "SELECT * FROM users";
$stmt = $con->query($SQL);
if($stmt->num_rows > 0) {
while($row = $stmt->fetch_row())
{
$array[] = $row;
}
return $array;
}
}
Or use it as a generator (probably not what you want):
function getAll()
{
global $con;
$SQL = "SELECT * FROM users";
$stmt = $con->query($SQL);
if($stmt->num_rows > 0){
while($row = $stmt->fetch_row())
{
yield $row;
}
}
}

How to make a search webservice API with Codeigniter

I've made a Search API with native PHP in the past, but I don't know how to make it in Codeigniter. The code below is not showing the data. Could someone point me in the right direction?
public function peta(){
$data = array();
// $query = "select * from tb_peta";
$cari = isset($_REQUEST['cari']) ? $_REQUEST['cari'] : '';
if ($cari != null) {
$result = $this->db->query("SELECT * FROM tb_peta WHERE nama LIKE "."'%".$cari."%'");
} else {
$result = $this->db->query( "SELECT * FROM tb_peta");
}
// $q = $this->db->query($query);
if ($q -> num_rows() >0) {
$data ['success'] = 1;
$data ['message'] = 'data ada';
$data ['data']=$q->result();
} else {
$data['result']='0';
$data['message'] ='kosong';
}
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$data[] = $row;
}
echo json_encode(array('planet' => $json_response));
}
Make use of codeigniter query builder.
public function peta(){
$data = array();
$cari = isset($_REQUEST['cari']) ? $_REQUEST['cari'] : '';
if ($cari != null) {
$this->db->like('name',$cari,'both');
$result = $this->db->get("tb_peta");
} else {
$result = $this->db->get("tb_peta");
}
if ($result->num_rows() >0) {
$data ['success'] = 1;
$data ['message'] = 'data ada';
$data ['data']=$result->result_array();
} else {
$data['result']='0';
$data['message'] ='kosong';
}
echo json_encode(array('planet' => $data));
}

select query through function.. to fetch data from db

How do I fetch data from db using select query in a function?
Example
function ec_select_query($student, $row = '', $fields=array()) {
$qry = "SELECT * FROM student";
$qry = mysql_query($qry);
while($row = mysql_fetch_assoc($qry)){}
return $row;
}
If you want to return all rows then first save it in an array in while loop then return this array.
function ec_select_query($student,$row='',$fields=array())
{
$qry = "SELECT * FROM student";
$qry = mysql_query($qry);
$result = array();
while($row = mysql_fetch_assoc($qry))
{
$result[] = $row;
}
return $result;
}
Its is running code. Modify it according to your needs
$con = mysql_connect('localhost','root','') or die("Unable to connect to MySQL");
mysql_select_db('demo', $con) or die("Database not found");
function ec_select_query($student)
{
$query = "SELECT * FROM $student";
$result = mysql_query($query);
$row = array();
$getData = array();
while($row = mysql_fetch_array($result))
{
$getData[]=$row;
}
return $getData;
}
$information = ec_select_query('accountplans');
echo "<pre>"; print_r($information); die;
Try it
function select_query($table, $where=array(),$fields=array()){
$select_fields = $table."*";
if(!empty($fields) && is_array($fields)){
$select_fields = implode(",", $fields);
}
$sql = "select ".$select_fields." from ".$table." where 1=1 ";
if(!empty($where) && is_array($where)){
foreach ($where as $key => $value) {
$sql .= " AND ".$value;
}
}
$query = mysql_query($sql);
$result = array();
while($row = mysql_fetch_assoc($result)){
$result[] = $row;
}
return $result;
}
Call Function
$fields = array("id","name","city");
$where = array('name = "abc"','city like "aaa"');
$students = select_query("studendts", $where, $fields);
This code might help you :
function ec_select_query($student,$row='',$fields=array())
{
$q = "SELECT * FROM student";
$q = mysql_query($qry);
while($row = mysql_fetch_array($qry))
{
return $row;
}
}
It is easiest way to produce entire data in array
function db_set_recordset($sql) {
$qry = mysql_query($sql);
$row= array();
while($out = mysql_fetch_assoc($qry)) {
$row[] = $out;
}
return $row;
}
$qry = "SELECT * FROM student";
$result = db_set_recordset($qry);

Get the id of a newly inserted row php

I am trying to get the insert id from a newly inserted row. I use the following method to query. However I am unable to get the inserted id.
function query($sql) {
global $link;
$debug = false;
//get the sql query
$args = func_get_args();
$sql = array_shift($args);
//secure the input
for ($i=0;$i<count($args);$i++) {
$args[$i] = urldecode($args[$i]);
$args[$i] = mysqli_real_escape_string($link, $args[$i]);
}
//build the final query
$sql = vsprintf($sql, $args);
if ($debug) print $sql;
//execute and fetch the results
$result = mysqli_query($link, $sql);
$id = $result->insert_id; //no result, what do I put here?
if (mysqli_errno($link)==0 && $result) {
$rows = array();
if ($result!==true)
while ($d = mysqli_fetch_assoc($result)) {
array_push($rows,$d);
}
//return json
return array('result'=>$rows, 'id'=>$id);
} else {
//error
return array('error'=>'Database error');
}
}
How can I modify this method to get the insert id?
$id = mysqli_insert_id($link);
This value would be called the "identity", keep that in mind when searching for information pertaining to this.
check the below links
mysql_insert_id()
http://dev.mysql.com/doc/refman/5.0/en/getting-unique-id.html
http://dev.mysql.com/doc/refman/5.0/en/mysql-insert-id.html

how to loop through multiple MySQL databases in a PHP script

I have inherited the below code, which creates a web interface for a MySQL database named 'database_name' and defined by the variable $database.
I want to add an additional database to this script, so that the same interface can be created this second database (which is set up in exactly the same way as the first database with the same tables names, etc., but contains different data). Is there a way to make $database a string array which I can loop over for multiple database names?
<?php
class DatabaseInterface {
public $host = "localhost"; //(name or ip address)
public $userName = "aksfhah";
public $passWord = "**********";
public $database = 'database_name';
public $tableData = "measurements";
public $tableMinbins = "minbins";
public $tableHourbins = "hourbins";
public $tableDaybins = "daybins";
public $tableDescriptions = "measurementDescriptions";
public $tableSpecs = "experimentDescriptions";
public $connection;
public function __construct($databaseName = "database_name") {
$this->database = $databaseName;
$this->connect();
}
public function connect($databaseName = null) {
$dbh = mysql_connect($this->host, $this->userName, $this->passWord);
if (is_null($databaseName)) {
mysql_select_db($this->database);
} else {
mysql_select_db($databaseName);
}
$this->connection = $dbh;
return $dbh;
}
public function initializeDatabase() {
$this->createDataTable($this->tableData);
$query = "create table if not exists $this->tableDescriptions (id int auto_increment primary key,type varchar(255),
description varchar(255), experimentname varchar(255), unique Key(description,experimentname)) engine=myisam";
mysql_query($query); //create a table if it does not exist
echo mysql_error(); //report error if one occurred
}
private function createDataTable($tableName) {
$query = "CREATE TABLE IF NOT EXISTS $tableName (
id smallint(5) unsigned NOT NULL,
time datetime NOT NULL,
measurement float DEFAULT NULL,
rebinned tinyint(4) DEFAULT '0',
PRIMARY KEY (id,time),
KEY (rebinned,id)
) ENGINE=MyISAM";
mysql_query($query); //create a table if it does not exist
echo mysql_error(); //report error if one occurred
}
public function insertByDescription($time, $value, $channelDescription, $experimentDescription, $type = "other") {
$sensorID = $this->createIdFromDescription($channelDescription, $experimentDescription, $type);
return $this->insertById($time, $value, $sensorID);
}
public function insertMultipleById($timeArray, $valueArray, $sensorID,$tableName=null) {
if(is_null($tableName)){
$tableName= $this->tableData;
}
if (count($timeArray) == 0)
return 0;
$query = "insert ignore into $tableName (id,time,measurement)
VALUES ";
for ($index = 0; $index < count($timeArray); $index++) {
$timeString = $timeArray[$index]->format("Y-m-d H:i:s");
$value = $valueArray[$index];
$query = $query . "('$sensorID','$timeString','$value'),";
}
$query = substr($query, 0, strlen($query) - 1); //trim final comma
$result = mysql_query($query);
if (mysql_error()) {
echo mysql_error();
return false;
} else
return mysql_affected_rows();
}
public function insertMultipleByDescription($timeArray, $valueArray, $channelDescription, $experimentDescription, $type = "other",$tableName=null) {
$sensorID = $this->createIdFromDescription($channelDescription, $experimentDescription, $type);
return $this->insertMultipleById($timeArray, $valueArray, $sensorID,$tableName);
}
public function insertById(DateTime $time, $value, $sensorID) {
$timeString = $time->format("Y-m-d H:i:s");
$query = "insert ignore into $this->tableData (id,time,measurement)
VALUES ('$sensorID','$timeString','$value')";
$result = mysql_query($query);
if (mysql_error()) {
echo mysql_error();
return false;
} else if (mysql_affected_rows() == 0) {
return false;
} else {
return true;
}
}
public function createIdFromDescription($channelDescription, $experimentDescription, $type) {
$sensorId = $this->getIdFromDescription($channelDescription, $experimentDescription);
if (!$sensorId) {
$query = "insert ignore into $this->tableDescriptions (description,experimentname,type)
VALUES ('$channelDescription','$experimentDescription','$type')";
$result = mysql_query($query);
$sensorId = mysql_insert_id();
}
return $sensorId;
}
public function getIdFromDescription($measurementDescription, $experimentDescription) {
$sensorId = false;
$query = "select id from $this->tableDescriptions where description like '$measurementDescription'
&& experimentname like '$experimentDescription'";
$result = mysql_query($query);
if (mysql_error()) {
echo mysql_error(); //report error if one occurred
return false;
}
if (mysql_num_rows($result) > 0) {
$row = mysql_fetch_array($result);
$sensorId = $row['id'];
}
return $sensorId;
}
function getDataById($id, $startDate, $endDate, $interval = "") {
$data = array();
$startDateString = $startDate->format("Y-m-d H:i:s");
$endDateString = $endDate->format("Y-m-d H:i:s");
$query = "select time,measurement from $this->tableData where id='$id' && time>='$startDateString' && time <='$endDateString' order by time asc " . $interval = "" ? "" : "group by $interval";
$result = mysql_query($query);
if (mysql_error()) {
echo mysql_error(); //report error if one occurred
return false;
}
while ($row = mysql_fetch_array($result)) {
//$time = new DateTime($row['time']);
$data[] = array($row['time'], $row['measurement'] * 1);
}
return $data;
}
public function getMostRecentData($id, $table) {
$query = "select date(max(time)) as time,measurement from $table where id='$id'";
$result = mysql_query($query);
if (mysql_error()) {
echo mysql_error(); //report error if one occurred
return false;
} elseif (mysql_num_rows($result) > 0) {
$row = mysql_fetch_array($result);
return $row;
} else {
return false;
}
}
public function getExperimentList() {
$list = array();
$query = "select distinct experimentname from $this->tableDescriptions";
$result = mysql_query($query);
if (mysql_error()) {
echo mysql_error(); //report error if one occurred
return false;
}
while ($row = mysql_fetch_array($result)) {
$list[] = $row['experimentname'];
}
return $list;
}
public function getChannelList($experimentDescription) {
$list = array();
$query = "select id,description,type from $this->tableDescriptions where experimentname='$experimentDescription'";
$result = mysql_query($query);
if (mysql_error()) {
echo mysql_error(); //report error if one occurred
return false;
}
while ($row = mysql_fetch_array($result)) {
$list[$row['description']] = array("id" => $row['id'], "type" => $row['type']);
}
return $list;
}
public function getDescriptionFromId($id) {
$query = "select * from $this->tableDescriptions where id='$id'";
$result = mysql_query($query);
if (mysql_error()) {
echo mysql_error(); //report error if one occurred
return false;
}
if (mysql_num_fields($result) > 0) {
$row = mysql_fetch_array($result);
return array($row['type'], $row['description'], $row['experimentname']);
} else {
return false;
}
}
public function getDisplayName($experimentName) {
$query = "select displayName from $this->tableSpecs where experimentName='$experimentName'";
$result = mysql_query($query);
echo mysql_error();
$row = mysql_fetch_array($result);
if ($row) {
return $row['displayName'];
} else {
return false;
}
}
public function simpleQuery($query) {
$result = mysql_query($query);
echo mysql_error();
if ($result) {
$row = mysql_fetch_array($result);
if ($row) {
return $row[0];
} else {
return FALSE;
}
} else {
return FALSE;
}
}
public function rebin($tableSource, $tableTarget, $numSeconds, $sum = false) {
$this->createDataTable($tableTarget);
echo "Updating $tableSource to set rebinned from 0 to 2...";
$query = "update $tableSource set rebinned=2 where rebinned =0;";
mysql_query($query);
echo mysql_error();
echo "Done.\n";
$numRows = mysql_affected_rows();
echo "Found $numRows records in $tableSource that need rebinning...\n";
$query = "select id,from_unixtime(floor(unix_timestamp(min(time))/$numSeconds)*$numSeconds) as mintime from $tableSource where rebinned=2 group by id;";
$result = mysql_query($query);
echo mysql_error();
if ($result) {
while ($row = mysql_fetch_array($result)) {
$id = $row['id'];
$mintime = $row['mintime'];
echo $id . "...";
$query = "INSERT INTO $tableTarget (id,time,measurement,rebinned)
SELECT id,from_unixtime(floor(unix_timestamp(time)/$numSeconds)*$numSeconds)," . ($sum ? "sum" : "avg") . "(measurement) as measurement,0
FROM $tableSource WHERE id=$id && time>='$mintime'
GROUP BY id,floor(unix_timestamp(time)/$numSeconds)
ON DUPLICATE KEY UPDATE measurement=values(measurement), rebinned=0;";
mysql_query($query);
//echo $query;
echo mysql_error();
echo "Done.\n";
}
echo "Updating $tableSource to set rebinned from 2 to 1...";
$query = "update $tableSource set rebinned=1 where rebinned =2;";
mysql_query($query);
echo mysql_error();
echo "Done.\n";
}
}
public function getDCPower($experimentName, $startDate, $endDate) {
$out = array();
$query = $this->buildDCPowerQuery($experimentName, $this->tableMinbins);
if ($query) {
if ($startDate != "") {
$query = $query . " && m0.time>='$startDate' ";
}
if ($endDate != "") {
$query = $query . " && m0.time<='$endDate' ";
}
echo $query;
$result = mysql_query($query);
echo mysql_error();
while ($row = mysql_fetch_array($result)) {
// echo $row['time'].", ".$row['power']."\n";
$out[] = array($row['time'], $row['power'] + 0);
}
return $out;
} else {
return FALSE;
}
}
}
?>
Is there a way to make $database a string array which I can loop over for multiple database names?
No, it does not work that way. The script you have defines a class. You have to look in the file that uses that class, where there will be something like
$interface = new DatabaseInterface("database1");
There you'll be able to do things such as
$interface = array();
$interface[0] = new DatabaseInterface("database1");
$interface[1] = new DatabaseInterface("database2");
and use two instances of the interface against the two databases.

Categories