please help me out regarding this function. I want to fetch data from the database and if there are results, I want to return a message and data array.
$this->query=("select * from user where pno='".$search."'");
$rd = $this->executeQuery();
$data = $rd->fetch_assoc();
if ($data) {
$message = "Record found.";
} else {
$message = "Record not found.";
}
return array($data, $message);
I am calling it this way:
list($data, $message)=$user->search($result);
echo $message
echo $data['name'];
I am getting the message but I am unable to fetch the array.
Please help me out if there is a problem in the function or if I can improve it.
Never do it this way
you should put your message setting code outside of the function.
function getData(){
$this->query=("select * from user where pno='".$search."'");
$rd = $this->executeQuery();
return $rd->fetch_assoc();
}
if ($data = getData()){
$message = "Record found.";
echo $message;
echo $data['name'];
} else {
$message = "Record not found.";
echo $message;
}
I'm not sure what you're using, but most likely you'll have an array of rows in $data, even if there is only single row. Try $data[0]['name']. Besides, I'd suggest that you move that message from your function to the place where it's called, and make the function return NULL or FALSE if nothing found.
$this->query=("select * from user where pno='".$search."'");
$rd = $this->executeQuery();
$data = $rd->fetch_assoc();
return empty($data)?FALSE:$data;
You’re missing a semicolon after echo $message in your code example.
Try appending this to your code and tell us what it returns:
var_dump($data);
Related
i have a small problem with my php code.
i've created a class for Clients, to return me a list with all clients. The problem is when i call the function from outsite, it dont show me the clietsList.
<?php
$returnData = array();
class Clients
{
public function readAll(){
$query = "SELECT * FROM clients";
$result = $this->con->query($query);
if ($result->num_rows > 0){
while ($row = $result->fetch_assoc()){
$returnData['clientsList'][] = $row;
}
return $returnData;
}
else{
echo "No found records";
}
}
}
if ($auth->isAuth()){
$returnData['message'] = "you are loggedin, so is ok";
$clientsObj = new Clients();
$clientsObj->readAll();
}
echo json_encode($returnData);
?>
and the result is like that, but without clietslist
{
"message": "you are loggedin, so is ok"
}
Where im doing wrong? Thanks for your answer. i want to learn php, im begginer. thanks in advance.
You need to get return value of function in a variable:
$returnData['message'] = "you are loggedin, so is ok";
$clientsObj = new Clients();
$returnData['clients'] = $clientsObj->readAll();
$returnData on you first line will not be same as $returnData in your function. $returnData in readAll function will be a new variable.
I suggest you to read about variable scope in php.
https://www.php.net/manual/en/language.variables.scope.php
Now, You will need to store returned value from function in a variable
like this
$returnData['message'] = "you are loggedin, so is ok";
$clientsObj = new Clients();
$clientListArray = $clientsObj->readAll(); //store returned value in a variable
$returnData['clientsList'] = $clientListArray['clientsList'];
This problem should be simple to resolve, but I can't...
After a request, a condition has to verify if the concerned article really exists, verifying the URL ($_GET).
My code : ( a testing file with simple echos )
$id = $bdd->prepare('SELECT content FROM articles WHERE idArticle = ?');
$id->execute(array($_GET['numArticle']));
while ($dataID = $id->fetch()) {
if (empty($dataID) or $dataID == null or !isset($dataID)) {
echo 'No content';
} else {
echo 'Can load the page';
}
}
$id->closeCursor();
The page behaviour : "can load the page" is writing when numArticle is right, but if it is not, nothing appears, neither an error message or something.
Any idea/advice? Thank you.
One way to do this is by checking the number of rows returned by mysqli:
$id = $bdd->prepare('SELECT content FROM articles WHERE idArticle = ?');
$id->execute(array($_GET['numArticle']));
if($id->num_rows > 0){
echo "can load page";
}else{
echo 'No content';
}
You can use fetchAll() function of PDO then run a foreach loop on data:
$rows = $id->fetchAll(PDO::FETCH_ASSOC);
if(!empty($rows)){
foreach($rows as $row){
echo "content";
}
}
else{
echo "No Content";
}
Assuming you are using Pdo, it looks like you want to be using Pdo's fetchColumn method.
<?php
$stmt = $db->prepare('SELECT content FROM articles WHERE idArticle = ? LIMIT 1');
$stmt->execute(array($_GET['numArticle']));
if ($result = $stmt->fetchColumn()) {
echo 'A result';
} else {
echo 'Db fetch returned false (or could be a string that evaluates to false).';
}
For some reason, the while loop below never fires.
All of this is inside a class.
$code = $this->get_postal_state_no('Western Cape');
private function get_postal_state_no($psn)
{
$sql = "
SELECT
no
FROM
ct_state
WHERE
name LIKE('".$psn."');";
$stmt = sqlsrv_query($this->conn1, $sql);
// This statement is not false, so the error handling does not happen, this is expected.
if($stmt === FALSE)
{
if(($errors = sqlsrv_errors()) != NULL)
{
foreach($errors as $error)
{
$sqlstate = $error['SQLSTATE'];
$code = $error['code'];
$sqlmessage = $error['message'];
}
}
$msg = 'Error in $stmt in get_postal_state_no() method.';
$this->do_error_log($error_msg, $sqlstate, $code, $sqlmessage, $msg, __LINE__, __FILE__, __FUNCTION__, __CLASS__, __METHOD__);
sqlsrv_free_stmt($stmt);
}
//This loop is never entered. This is not expected.
while($obj = sqlsrv_fetch_object($stmt))
{
echo "I am here now";
break;
if(!empty($obj->no) && $obj->no != '')
{
echo "Hello, I exist";
break;
// This break never happens
return $obj->no;
}
else
{
echo "Hello, I don't exist";
break;
// This break never happens
$code = $this->sp_aa_iud_ct_state($psn);
return $code;
}
sqlsrv_free_stmt($stmt);
}
}
Does anyone have an idea why? I am using the php_sqlserv driver. The SQL server profiler shopws the query for the first part executing.
Thanks
J
Looking at the documentation page for sqlsrv_fetch_object it says this about the return value:
Returns an object on success, NULL if there are no more rows to return, and FALSE if an error occurs or if the specified class does not exist.
I suspect the function is either returning NULL or FALSE, though the reasons are a little unclear. Try adding this above the while loop and see what the output is:
$obj = sqlsrv_fetch_object($stmt)
var_dump($obj);
die;
while($obj = sqlsrv_fetch_object($stmt))
{ // ...
Another helpful debugging trick is to dump out the query and then copy/paste it into your DBMS system and run the query you are executing in code directly against your database to see if any results are actually being returned:
$sql = "
SELECT
no
FROM
ct_state
WHERE
name LIKE('".$psn."');";
var_dump($sql);
I have one problem.I wanted to echo my message ("subject created", "subject creation failed" depending on whether my subject is created or not). The problem is the message is on every page even though setting the $_SESSION["message"] is under if condition . I really don't know where is the problem. I lost probably 2 hours on this...
All includes and requires are included...
This is on my proceeding page:
if(isset($_POST["submit"])) {
$menu_name = mysql_prep($_POST["menu_name"]);
$position = (int) $_POST["position"];
$visible = (int) $_POST["visible"];
$query = "INSERT INTO subjects(";
$query .= " menu_name, position, visible ";
$query .= ") VALUES ('{$menu_name}', '{$position}', '{$visible}')";
$result = mysqli_query($connection,$query);
if($result) {
//success //
$_SESSION["message"] = "Subject created";
redirect_to("manage_content.php");
} else {
$_SESSION["message"] = "Subject creation failed";
redirect_to("create_new_content.php");
}
} else {
redirect_to("create_new_content.php");
}
my message function is:
session_start();
function message() {
if (isset($_SESSION["message"])){
$output = $_SESSION["message"];
return $output;
}
}
and after all Im echoing on my manage_content.php and create_new_content.php
<?php echo message(); ?>
You should clear the session when its not needed any more.
E.g.
unset($_SESSION['message']);
Try to clear your $_SESSION message and check if is not empty
function message() {
if (isset($_SESSION["message"]) && !empty($_SESSION["message"])){
$output = $_SESSION["message"];
$_SESSION["message"] = '';
return $output;
}
}
if you show your message only one time, you need to clear the $_SESSION["message"] before return
session_start();
function message() {
if (isset($_SESSION["message"])){
$output = $_SESSION["message"];
// clear the session message
$_SESSION["message"] = null;
// remove message index from $_SESSION
unset($_SESSION["message"]);
return $output;
}
}
For example:
$qrInsert = "INSERT INTO DBASE1.DBO.TABLE1 VALUES ('sampVal','sampVal','sampVal')";
odbc_exec($msCon,$qrInsert);
if( 'the query if successfully executed' ){
//then do this
//if not then
}else{
//then do this
}
Is there an easy way to know if it is successfully inserted, or in other cases, updated, and deleted succesfully?
Thanks
Try like
if(odbc_exec($msCon,$qrInsert))
{
echo 'Executed Successfully';
} else {
echo 'Error in execution';
}
odbc_exec only will return true if the query executed successfully,or else return false if it is not
if (odbc_exec($msCon,$qrInsert)){
// do this
}
else{
// do that
}
just replace your code with
$qrInsert = "INSERT INTO DBASE1.DBO.TABLE1 VALUES ('sampVal','sampVal','sampVal')";
if( odbc_exec($msCon,$qrInsert); )
{
//then do this
//if not then
}
else
{
//then do this
}
It Return 0 or 1 depends on failure or success of your query.You Can store result of "odbc_exec" in a variable & compare it in 'If','Else' condition.Benefit of storing in a variable is ,you can use it where ever you want .
i.e.
$query_result = odbc_exec($msCon,$qrInsert);
if($query_result)
echo 'Executed Successfully';
else
echo 'Execuion Error';