I have a php script which retrieves data from mysql db.
Everything works fine, but my problem is that this $result = $dao->joinedEvents($userId); returns an array of numbers and what I would like to do is to run this $secondResult = $dao->joinedEventsInfo($receivedIds); for every ID and this script I'm using right now returns data only for one ID.
This is part of my php script:
$userId = htmlentities($_REQUEST["userId"]);
$result = $dao->joinedEvents($userId); //This is getting the IDs array
if(!empty($result)) {
$receivedIds = $result["event_id"];
$ids = explode(",", $receivedIds);
foreach($ids as $id){
$secondResult = $dao->joinedEventsInfo($id);
if(!empty($secondResult)) {
$returnValue["finalResult"][] = $secondResult;
} else {
$returnValue["status"] = "error";
$returnValue["message"][] = "Could not find records for id" . $id;
}
}
} else {
$returnValue["status"] = "Empty error";
$returnValue["message"] = "Could not find records";
}
$dao->closeConnection();
echo json_encode($returnValue);
And this is joinedEvents script:
public function joinedEvents($userId){
$returnValue = array();
$sql = "SELECT event_id from MyTable WHERE userId= '$userId' LIMIT 0 , 30";
$statement = $this->conn->prepare($sql);
if (!$statement)
throw new Exception($statement->error);
$statement->execute();
$result = $statement->get_result();
while ($myrow = $result->fetch_assoc())
{
$returnValue[] = $myrow;
}
return $returnValue;
}
This is joinedEventsInfo script:
public function joinedEventsInfo($eventId){
$returnValue = array();
$sql = "SELECT * FROM Events WHERE eventId = '$eventId' LIMIT 0 , 30";
$statement = $this->conn->prepare($sql);
if (!$statement)
throw new Exception($statement->error);
$statement->execute();
$result = $statement->get_result();
while ($myrow = $result->fetch_assoc())
{
$returnValue[] = $myrow;
}
return $returnValue;
}
Edit: Tha reason I need this is that I have two tables. In the first one I have just IDs and in the second one I have info. So first I need to get the IDs and then I need to get data for every ID I have just received.
Thank you very much , I'm totally stuck.
Based on the updated code snippets and the discussion below, it is found that $result is indeed an array, and the solution is:
$userId = htmlentities($_REQUEST["userId"]);
$result = $dao->joinedEvents($userId);
if(count($result)){
foreach($result as $array){
$event_id = $array['event_id'];
$secondResult = $dao->joinedEventsInfo($event_id);
if(!empty($secondResult)) {
$returnValue["finalResult"][] = $secondResult;
} else {
$returnValue["status"] = "error";
$returnValue["message"][] = "Could not find records for id: " . $event_id;
}
}
}else {
$returnValue["status"] = "Empty error";
$returnValue["message"] = "Could not find records";
}
$dao->closeConnection();
echo json_encode($returnValue);
Have you tried array_map()?
That would allow you to call a php function on each member of an array easily.
Another way would be to use the common while ($row = mysql_fetch_array($result)) which would execute the code in the while loop for each row of your returned results. Note, you will likely have to change the mysql_fetch_array to something specific for your SQL connection.
Related
I have a method to read the data from the database. The code is completely working, but there is a problem, it is if I run the code and there is no data in the database, I get the error:
E/flutter (29414): [ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: FormatException: Unexpected character (at character 1)
E/flutter (29414): No Data Found.
E/flutter (29414): ^
And my code:
Future<List<data>> FetchT() async {
apiURL = 'https://*******.com/getList.php?C=' +
gatName.toString();
var response = await http.get(apiURL);
if (response.statusCode == 200) {
final items = json.decode(response.body).cast<Map<String, dynamic>>();
List<data> listOfFruits = items.map<data>((json) {
return data.fromJson(json);
}).toList();
return listOfFruits;
} else {
//throw Exception('Failed to load data from Server.');
}
}
PHP code:
<?php
include 'connt.php';
$C= $_GET["C"];
$sql = "SELECT * FROM top WHERE C=? ORDER BY id DESC ";
$result = $con->query($sql);
$stmt = $con->prepare($sql);
$stmt->bind_param("s",$C);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows >0) {
while($row[] = $result->fetch_assoc()) {
$item = $row;
$json = json_encode($item, JSON_NUMERIC_CHECK);
}
} else {
echo "No Data Found.";
}
echo $json;
$con->close();
?>
I previously searched the old topics here and tried all the topics and problems similar to mine, but I did not find a solution to my problem.
How can I solve this problem?
You didn't specify the header code if no data is found.
You should change your php code to this:
<?php
include 'connt.php';
$C= $_GET["C"];
$sql = "SELECT * FROM top WHERE C=? ORDER BY id DESC ";
$result = $con->query($sql);
$stmt = $con->prepare($sql);
$stmt->bind_param("s",$C);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows >0) {
while($row[] = $result->fetch_assoc()) {
$item = $row;
$json = json_encode($item, JSON_NUMERIC_CHECK);
}
} else {
http_response_code(404);
$json = json_encode(["error" => "No Data Found."]);
}
echo $json;
$con->close();
?>
I created the code using mysqli_fetch_assoc with 'while' as shown below.
But it does not work.
if ($ result = mysqli_query ($ dbconn, $ query)) {
It works by here.
while ($ row = mysqli_fetch_assoc ($ result)) {
It does not work from here.
I can not find the wrong part.
If I do not use 'while', it works as follows.
What is the problem?
// not works
$query = "select * from member where f_status='1'";
if ($result=mysqli_query($dbconn, $query)) {
while ($row = mysqli_fetch_assoc($result)) {
if ($row[f_status]==0) {
error("No data");
} else {
echo $row[f_user_id];
echo $row[f_user_name];
}
}
mysqli_free_result($result);
}
// works
$query = "select * from member where f_status='1'";
$result = mysqli_query($dbconn, $query);
$row = mysqli_fetch_assoc($result);
if ($row) {
echo $row[f_user_id];
echo $row[f_user_name];
} else {
error("No data");
}
I think the problem is the way you have iterated while loop and condition to show No data message,
You should try this way:
$query = "select * from member where f_status='1'";
if ($result = mysqli_query($dbconn, $query)) {
if ($result->num_rows) {
while ($row = mysqli_fetch_assoc($result)) {
echo $row[f_user_id];
echo $row[f_user_name];
}
}
else {
error("No data");
}
mysqli_free_result($result);
}
Hope this should solve your issue.
$stmt is execute and give Result in Print_r($stmt). Result is this "Resource id #4" but when Print_r($stmt) is put in if (odbc_num_rows($stmt) > 0) {Print_r($stmt);}. it's not give Result. and gone else conditon give message else condition.so How to Put odbc function instead of odbc_num_rows($stmt).if right Parameter pass query execute and gone if condition.
which Odbc function used in if condtion.
<?php
include 'Connection.php';
if(isset($_REQUEST["insert"]))
{
$user = $_GET['user'];
$pwd = $_GET['pass'];
$yid = $_GET['yid'];
$sql = "select RegNo, UserName, Pasword from Std_Reg where UserName= '$user' and Pasword = '$pwd' and YearID = $yid and IsActive = True";
$stmt = odbc_exec($conn, $sql);
$result = array();
if (!empty($stmt)) {
// check for empty result
if (odbc_num_rows($stmt) > 0)
{
print_r($stmt);
$stmt1 = odbc_fetch_array($stmt);
$product = array();
$product['RegNo'] = $stmt1['RegNo'];
$product['UserName'] = $stmt1['UserName'];
$product['Pasword'] = $stmt1['Pasword'];
// success
$result["success"] = 1;
// user node
$result["product"] = array();
array_push($result["product"], $product);
// echoing JSON response
echo json_encode($result);
} else {
// no product found
$result["succes"] = 0;
$result["message"] = "No product found";
// echo no users JSON
echo json_encode($result);
}
//sqlsrv_free_stmt($stmt);
odbc_close($conn); //Close the connnection first
}
}
?>
For INSERT, UPDATE and DELETE statements odbc_num_rows() returns the number of rows affected. The manual says-
Using odbc_num_rows() to determine the number of rows available after a SELECT will return -1 with many drivers.
one way around this behaviour is to do a COUNT(*) in SQL instead. See here for an example.
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
I'm a fairly new programmer, especially in PHP as i have come from a VB environment.
Below is the function I am having troubles with, as you can see i have had quite a few attempts (in comments). I thought id leave the comments there in case i'm closer with my other attempts.
I have never used PDO before and as you can see this function pretty much allows the user to log in.
The line if($temp == $_POST['password']) is where the problem is. Apparently $temp is undefined, but i cannot see why, i have even declared it at the top of the function to be sure. Anyone have any ideas?
public function load_user_data() {
$temp;
$sql;
try{
// $STH = dbHandler::$DBH->prepare("SELECT * FROM tblCustomer WHERE email = :email");
// $STH->bindValue(':email', $this->email);
// $STH->execute();
// $posts = $STH->fetch(PDO::FETCH_ASSOC); //If only fetch 1 line use just "fetch" instead of "fetchAll"
// echo '<pre>';
// print_r($posts);
// echo '</pre>';
//--------
$STH = dbHandler::$DBH->prepare("SELECT password FROM tblCustomer WHERE email = :email");
$STH->bindValue(':email', $_POST['usermail']);
$STH->setFetchMode(PDO::FETCH_ASSOC);
while($row = $STH->fetch()) {
$temp = $row;
}
//$temp = $STH->fetch(['password']);
// while($row = $STH->fetch()) {
// $temp = $row['password'];
// }
//--------
// $sql = "SELECT password FROM tblCustomer WHERE email = :email";
// $stmt = $PDO->query($sql);
// $row = $stmt->fetchObject();
// $temp = $row->password;
if($temp == $_POST['password']) {
$STH = dbHandler::$DBH->prepare("SELECT * FROM tblCustomer WHERE email = :email");
$STH->bindValue(':email', $this->email);
$STH->setFetchMode(PDO::FETCH_ASSOC);
echo("we have reached here");
while($row = $STH->fetch()) {
$firstname = $row['firstName'];
$lastname = $row['secondName'];
$title = $row['title'];
$companyname = $row['companyName'];
$email = $row['email'];
$phone = $row['phone'];
$email = $row['mobile'];
$startdate = $row['startDate'];
$isauthorised = $row['isAuthorised'];
$accstop = $row['accStop'];
$stopdate = $row['stopdate'];
}
}
}
catch (PDOException $e) {
print $e->getMessage();
}
}
The problem is here:
$STH = dbHandler::$DBH->prepare("SELECT password FROM tblCustomer WHERE email = :email");
$STH->bindValue(':email', $_POST['usermail']);
$STH->setFetchMode(PDO::FETCH_ASSOC);
while($row = $STH->fetch()) {
$temp = $row;
}
First, you need to do:
$STH->execute();
before you try to fetch rows.
Second, if the query doesn't match any rows, your while loop will never go into the body, so $temp will not be set. Since you apparently only expect to get one row from the query, you don't need to use while. Instead, do:
if ($temp = $STH->execute()) {
// all the code that depends on finding a row goes here
...
}
Inside that block, you'll need to do:
if ($temp['password'] == $_POST['password'])