SELECT query with bindParam returns nothing - php

public function showSingleVisit(){
//echo $this->doctorID; the printed 1111
//$this->doctorID = 1111;
$db = connect_db();
$query = "SELECT * FROM visit WHERE doctorID = :doctorID";
$result = $db->prepare($query);
$result->bindParam(':doctorID', $this->doctorID);
$result->execute();
return $result;
}
This query doesn't return any row but when putting $this->doctorID = 1111 I get the rows that is wanted. I use bindParam in INSERT query in this class and works correctly. What's the problem?
UPDATE:
class visit{
//define public varibles
public function showSingleVisit(){
$db = connect_db();
$query = "SELECT * FROM visit WHERE visit = 0 AND doctorID = :doctorID AND patientID = :patientID";
$result = $db->prepare($query);
$result->bindParam(':patientID', $this->patientID);
$result->bindParam(':doctorID', $this->doctorID);
$result->execute();
return $result;
}
}
Here's how I call the function un the other page:
$visit = new visit;
$visit->doctorID = $auth->user->IDNo;
$visit->caseNo = $_SESSION['caseNo'];
$result = $visit->showSingleVisit();
if($result){
while($row = $result->fetch()){
echo'<p>
<label>Date:</label>
<span>'.$row->visitDate.'</span>
</p>';
}
}
else{
echo "No exists!";
}
Neither it shows any dates, nor it prints "No exists!".

you have to specify the type of the param :
$result->bindParam(':doctorID', $this->doctorID, PDO::PARAM_INT);
look at here :
http://php.net/manual/fr/pdostatement.bindparam.php

since doctorID is integer, you should add data_type to INT. it look like this
$result->bindParam(':doctorID', $this->doctorID, PDO::PARAM_INT);

Related

How to do an if-else condition in sql and php?

What I want to do is a select query and then if it is true set a variable of a table called 'afiliadospadron' to 1 but if it is false (it do not return anything) just set the variable to 0. My code isn't working. Can somebody help me please?
$query= "select nrodoc from oct20 where nrodoc = 05463xx union select nrodoc from dic20 where nrodoc = 054631xx";
$query2= "update afiliadospadron set condVotar = '1' where nroDoc = '5463xxx' ";
//$query3= "UPDATE afiliadospadron SET condVotar = 0 WHERE nroDoc = '5463xxx'";
if ($query) {
$query2;
} else {
echo "next time";
// $query3 = "UPDATE afiliadospadron SET condVotar = 0 WHERE nroDoc = '5463192'";;
}
$statement = $conexion->prepare($query);
$statement = $conexion->prepare($query2);
//$statement = $conexion->prepare($query3);
$statement->execute();
try it
if ($result = $mysqli -> query($query)) {
$query2;
// Free result set
$result -> free_result();
}
code from: https://www.w3schools.com/php/func_mysqli_query.asp
The answer was
$statement = $conexion->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
if ($result = $result ) {
echo "yas";
$statement = $conexion ->prepare($query2);
$statement->execute();
// Free result set
} else {
echo "Wasnt found";
$statement = $conexion ->prepare($query3);
$statement->execute();
}

PHP MYSQLI Query is failing

When trying to run a MYSQLI command in PHP, Its coming back failing.
function DB_query($query, $params = []) {
$conn = DB_connect();
if ($params)
{
$stmt = $conn->prepare($query);
$types = str_repeat('s', count($params));
$stmt->bind_param($types, ...$params);
$stmt->execute();
$result = $stmt->get_result();
} else {
$result = mysqli_query($conn, $query);
}
if ($result)
{
$result = mysqli_fetch_all($result);
return $result;
} else {
return mysqli_affected_rows($conn);
}
}
Here is my query:
DB_query("SELECT count(*) FROM members WHERE email = ? LIMIT 1",[$email])
It runs on:
$result = mysqli_fetch_all($result);
The results from $result: array(1)([0]=>array(1)([0]=>(int)1))
Here is my query:
DB_query("SELECT id, username, password FROM members WHERE email = ? LIMIT 1",[$email]);
It runs on:
$result = mysqli_fetch_all($result);
The results from $result: > array(0)
I have tried changing out the "mysqli_fetch_all" to fetch_all, but I cant figure it out. I need both query to run through the same function.
I cant figure out why the last query is returning nothing in the array.
<?php
$sql = "SELECT * FROM members WHERE email = '".$email."'";
$result = mysqli_query($con, $sql);
while($row = mysqli_fetch_row($result)) {
echo $row[0];
echo $row[1];
echo $row[2];
}
?>
Alternatively, you can use mysqli_fetch_array and use $row['fieldname'] inside the loop.

PHP - failed to output no data where no data in table

I've tried to find any reference to display data where no data in table for an hours, but I'm not yet found a code to fix the issue
I've this code:
//function
function readAll(){
$query = "SELECT * FROM ".$this->table_name." ORDER BY id_nilai ASC";
$stmt = $this->conn->prepare( $query );
$stmt->execute();
return $stmt;
}
//execute
$pro3 = new Nilai($db);
$stmt3 = $pro3->readAll();
while ($row3 = $stmt3->fetch(PDO::FETCH_ASSOC)){
// not yet fix how to display no data
//if($row3==false){ tried to change $row3==0 still won't work
//echo "No Data";
//}
//die(var_dump($row3)); showing `bool(false)`
echo $row3['ket_nilai'] (echo $row3['jum_nilai'])
}
any idea how to do?
I want to display some text when no data found in database table
You need to fetch the results before entering the loop, check if you do get the results then if you do enter the loop else display the message
see bellow code :
<?php
//function
function readAll(){
$query = "SELECT * FROM ".$this->table_name." ORDER BY id_nilai ASC";
$stmt = $this->conn->prepare( $query );
$stmt->execute();
return $stmt;
}
//execute
$pro3 = new Nilai($db);
$stmt3 = $pro3->readAll();
$results = $stmt3->fetchall(PDO::FETCH_ASSOC);
if(count($results) > 0){
foreach($results as $row3){
//display them
echo $row3['ket_nilai'] ;
echo $row3['jum_nilai'];
}
}else{
echo "No data available";
}
?>

Run php action for every element

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.

MySQL data is not returned in PHP variables

<?php
require("config.inc.php");
$query = "Select 1 FROM dogs WHERE dog_id = :iddog ";
$query_params = array(':iddog'=> $_POST['iddogPHP2']);
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
$dono2 = $result ->fetchColumn(1);
$raca2 = $result ->fetchColumn(2);
$sex2 = $result ->fetchColumn(3);
$estado2 = $result ->fetchColumn(4);
$query = "Select * FROM dogs WHERE dispon = 'Sim' AND dono != '$dono2' AND estado = '$estado2' AND raca = '$raca2' AND sex != '$sexo2' ";
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute();
}
catch (PDOException $ex)
{
$response["success"] = 0;
$response["message"] = "Database Error!";
die(json_encode($response));
}
// Finally, we can retrieve all of the found rows into an array using fetchAll
$rows = $stmt->fetchAll();
?>
This is my code and the problem is that the variables dono2, raca2, gender2 are not getting the values from the database. What's wrong in it?
Instead of SELECT 1 you need to use SELECT * in your first query.
$query = "Select * FROM dogs WHERE dog_id = :iddog ";
The following returns an array of results
$rows = $stmt->fetchAll();
So you would need to specify which one to reference.
$dono2 = $rows[0]['dono'];
$raca2 = $rows[0]['raca'];
$sexo2 = $rows[0]['sex'];
$estado2 = $rows[0]['estado'];
$rows = $stmt->fetchAll();
fetch all rows from database you need to specify which row you want if it's multiple row
$dono2 = $rows[0]['dono'];
$raca2 = $rows[0]['raca'];
$sexo2 = $rows[0]['sex'];
$estado2 = $rows[0]['estado'];
Try this code
$stmt = $db->prepare($query);
$stmt->bindParam(':iddog', $_POST['iddogPHP2']);
$stmt->execute($query_params);
$dono2 = $stmt ->fetchColumn(1);
$raca2 = $stmt ->fetchColumn(2);
$sex2 = $stmt ->fetchColumn(3);
$estado2 = $stmt ->fetchColumn(4);

Categories