I have no records in a table called assessment
I have a function:
function check_assessment_record($p_id, $a_id, $c){
$dataexistsqry="SELECT * FROM assessments WHERE (pupil_id=$p_id && assessblock_id=$a_id)" ;
$resultt = $c->query($dataexistsqry);
if ($resultt->num_rows > 0) {
echo '<p>set $de = true</p>';
$de=TRUE;
}else{
echo '<p>set $de = false</p>';
$de=FALSE;
}
return $de;
$dataexists->close();
}; //end function
I call the function thus:
$thereisdata = check_assessment_record($pupil_id, $assessblock_id, $conn);
However my function is printing out nothing when I was expecting FALSE. It prints out true when there's a record.
When I get the result in $thereisdata I want to check for if its TRUE or FALSE but its not working.
I looked at the php manual boolean page but it didn't help
It seems that you are passing the database connection as an object using the variable $c in your function parameter. This tells me that you would greatly benefit by creating a class and using private properties/variables. Also, there are many errors in your code that shows me what you are trying to achieve, some errors are the way you are closing your db connection using the wrong variable, or how you place the close connection method after the return, that will never be reached.
Anyway, I would create a database class where you can then call on specific functions such as the check_assessment_record() as you wish.
Here's how I would redo your code:
<?php
class Database {
private $conn;
function __construct() {
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "test";
// Create connection
$this->conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($this->conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
}
function check_assessment_record($p_id, $a_id) {
$sql = "SELECT * FROM assessments WHERE (pupil_id=$p_id && assessblock_id=$a_id)";
$result = $this->conn->query($sql);
if ($result->num_rows > 0) {
echo '<p>set $de = true</p>';
$de = TRUE;
} else {
echo '<p>set $de = false</p>';
$de = FALSE;
}
return $de;
}
function __destruct() {
$this->conn->close();
}
}
$p_id = 1;
$a_id = 2;
$db = new Database();
$record = $db->check_assessment_record($p_id, $a_id);
var_dump($record);
?>
are you using PDO's correctly?
A call for me would normally look like;
$aResults = array();
$st = $conn->prepare( $sql );
$st->execute();
while ( $row = $st->fetch() ) {
//do something, count, add to array etc.
$aResults[] = $row;
}
// return the results if there is, else returns null
if(!empty($aResults)){return $aResults;}
if you didnt want to put the results into an array you could just check if a column is returned;
$st = $conn->prepare( $sql );
$st->execute();
if(! $st->fetch() ){
echo 'there is no row';
}
Here is the code
function check_assessment_record($p_id, $a_id, $c){
$dataexistsqry="SELECT * FROM assessments WHERE (pupil_id=$p_id && assessblock_id=$a_id)" ;
$resultt = $c->query($dataexistsqry);
if ($resultt->num_rows > 0) {
echo '<p>set $de = true</p>';
$de=TRUE;
}else{
echo '<p>set $de = false</p>';
$de=FALSE;
}
return $de;
$dataexists->close();
}; //end function
You can check the return value using if else condition as
$thereisdata = check_assessment_record($pupil_id, $assessblock_id, $conn);
if($thereisdata){ print_f('%yes data is present%'); }
else{ print_f('% no data is not present %'); }
The reason is , sometime function returning Boolean values only contain the true value and consider false value as null , that's why you are not printing out any result when data is not found.
Hope this will help you. Don't forget to give your review and feedback.
Related
I have a function that goes through the product database table and if there is a row with supplierid and name that matches the parameters, then it returns true.
But it always returns true even if it shouldn't.
function checkifhoused($productname, $supplier)
{
$db = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
$sql = "SELECT * FROM " . TBL_PRODUCTS;
$result = mysqli_query($db, $sql);
while ($row = $result->fetch_assoc()) {
if ($row['supplierid'] == $supplier and $row['name'] == $productname) {
return true;
}
}
return false;
}
First: I can advice you to use PDO extension. It have better variables binding options.
Second: as #pavel & Ro Achterbeg mentioned in theirs comment you need not fetch all rows from DB table, but check only record with needle parameters exists
<?php
define('TBL_PRODUCTS', 'TBL_PRODUCTS');
function checkifhoused($db, $productname, $supplier)
{
$sql="SELECT * FROM ".TBL_PRODUCTS." WHERE name = ? AND supplierid = ? ";
$stmt = $db->prepare($sql);
$result = $stmt->execute([$productname, $supplier]);
return $stmt->rowCount() > 0;
}
var_dump(checkifhoused($pdo, 'productname', 1));
var_dump(checkifhoused($pdo, 'other_productname', 1));
Here you can test PHP & SQL code
Hello every body is it possible to pass an array containing some data to a function and put this array of data in a WHERE condition of a mysql query?
Please, take a look to my code if it's correct. Anyway it is not working at the moment, it prints "No results" ...
public function target_query($ids_array){
include_once 'connection.php';
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$ids = join("','",$ids_array);
$sql = "SELECT codice_target FROM customer WHERE id_customer IN ('$ids')";
$result = $conn->query($sql);
$arraytoclass = array();
if ($result->num_rows > 0) {
// output data of each row
//echo "tutto ok";
while($row = $result->fetch_row()) {
//echo "Codice target: " . $row["codice_target"]."<br>";
$arraytoclass[] = $row;
//echo "codice target:".$arraytoclass[$i]['codice_target'];
}
//print_r($arraytoclass);
return $arraytoclass;
//print_r($arraytoclass);
} else {
echo "NO results";
}
return $arraytoclass;
$conn->close();
}
The result of the query will be passed inside another function here below:
public function fputToFile($file, $allexportfields, $object, $ae)
{
if($allexportfields && $file && $object && $ae)
{
//one ready for export product
$readyForExport = array();
//put in correct sort order
foreach ($allexportfields as $value)
{
$object = $this->processDecimalSettings($object, $ae, $value);
$readyForExport[$value] = iconv("UTF-8", $ae->charset, $object[$value]);
}
$arraytoclass = $this->target_query($readyForExport['id_customer']);
print_r ($arraytoclass);
// and so on...
// and so on...
Many thanks in advance.
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 am working with a MySQL Database and having some issues while trying to get data from several built-in PHP MySQL methods. I have written a class to interact with the database, and here are the relevant bits:
<?php
include("includes/Config.inc.php");
include_once("ChromePHP.class.php");
class Database{
private $db;
private $hostname;
private $username;
private $password;
private $schema;
function __construct() {
if(func_num_args() == 0){
$this->hostname = conf_hostname;
$this->username = conf_username;
$this->password = conf_password;
$this->schema = conf_schema;
}
else{
$params = func_get_args();
$this->hostname = $params[0];
$this->username = $params[1];
$this->password = $params[2];
$this->schema = $params[3];
}
$this->open();
}
private function open(){
$this->db = mysql_connect($this->hostname, $this->username, $this->password) or die ('Error connecting to mysql');
mysql_select_db($this->schema, $this->db);
mysql_query("SET NAMES utf8");
}
public function executeQuery($query){
$results = mysql_query($query, $this->db) or die ("Error in query: $query. ".mysql_error());
return $results;
}
public function executeNonQuery($query){
mysql_query($query, $this->db) or die ("Error in query: $query. ".mysql_error());
$info = mysql_info($this->db);
if($info){
$bits = explode(' ', $info);
return $bits[4];
}
return false;
}
public function close(){
mysql_close($this->db);
}
public function escape($string){
$output = mysql_real_escape_string($string , $this->db);
return $output;
}
public function getRegionTree(){
$query = "SELECT COUNT(parent.Name) - 2 as level, node.Name AS Name, node.ID, node.Parent
FROM Region AS node, Region AS parent
WHERE node.LeftVal BETWEEN parent.LeftVal AND parent.RightVal and node.Name <> 'Earth'
GROUP BY node.ID
ORDER BY node.LeftVal";
$result = $this->executeQuery($query);
$last_level = 0;
$output = '<ul id="regionTree">'.PHP_EOL;
while ($row = mysql_fetch_assoc($result)) {
$link = '<li>'.PHP_EOL.''.$row["Name"]."".PHP_EOL;
$diff = $last_level - $row["level"];
if($diff == 0){
// Sibling
$output .= ($row["level"] != 0) ? '</li>'.PHP_EOL.$link:$link;
}
elseif($diff < 0){
// Child
$demoter = '<ul>'.PHP_EOL;
for ($i=0; $i > $diff; $i--) {
$output .= $demoter;
}
$output .= $link;
}
else{
// Parent
$promoter = '</li>'.PHP_EOL.'</ul>';
for ($i=0; $i < $diff; $i++) {
$output .= ($row["level"] != 0) ? $promoter.PHP_EOL."</li>":$promoter;
}
$output .= $link;
}
$last_level = $row["level"];
}
$output .= "</li></ul>";
return $output;
}
public function addRegion($name, $type, $parentID){
$query = "select Name, Region_Type from Region where ID = ".$parentID;
$result = $this->executeQuery($query);
if($result){
$row = mysql_fetch_assoc($result);
$query = "call AddRegion('".$name."', '".$type."', '".$row["Name"]."', '".$row["Region_Type"]."', #returnCode, #returnMessage)";
$result = $this->executeQuery($query);
if($result){
return true;
}
else{
$query = "select #returnCode as code, #returnMessage as message";
$result = $this->executeQuery($query);
while($row = mysql_fetch_assoc($result)){
print_r($row);
}
return false;
}
}
return false;
}
public function getInfo(){
return mysql_info();
}
public function editRegion($id, $name, $type){
$query = "update Region set Name = '$name', Region_Type = '$type' where ID = $id";
if($this->executeNonQuery($query) > 0){
return true;
}
return false;
}
}
$db = new Database();
?>
With this Database class I am able to successfully make queries, get region trees, and successfully change data in the database using the ExecuteNonQuery function. However, any attempts I have made to use mysql_info, mysql_affected_rows, or other similar functions fails, making it really difficult to write any error handling code. To make matters stranger yet, if I run the following code:
<?php
$db = mysql_connect("localhost", "User", "Password") or die ('Error connecting to mysql');
mysql_select_db("DB", $db);
mysql_query("update Region set Name = 'test' where ID = 594", $db);
echo mysql_info($db);
?>
I am able to get results as expected. Any Ideas?
Are you using mysql_info and mysql_error outside the Database class? And if so how are you referencing the database connection? If you don't identify the database connection then:
The MySQL connection. If the link identifier is not specified, the last
link opened by mysql_connect() is assumed. If no such link is found,
it will try to create one as if mysql_connect() was called with no
arguments. If no connection is found or established, an E_WARNING
level error is generated.
So internally you should be doing mysql_info($this->db); to get mysql_info. Accessing $db externally requires you to write something to get around it being private.
But if you are going to be doing database stuff in an object-oriented mode you really should investigate PDO.
After adding "or die()" statements in several places in my script, I was surprised to see that nothing was actually failing to work, instead it was failing to work the way I expected it to. The problem I was having as it turns out, was that splitting the output of mysql_info (on the space character) resulted in several indices in the array containing nothing, as would be generated by inconsistent whitespace in the output of mysql_info. The index that I thought (based upon counting spaces visually) would contain an integer instead contained a string, and I was attempting to compare that string against the number 0, which won't work. I have updated my executeNonQuery function as follows:
public function executeNonQuery($query){
mysql_query($query, $this->db) or die ("Error in query: $query. ".mysql_error());
$info = mysql_info($this->db);
if($info){
$output = array();
$bits = explode(' ', $info);
$output["rowsMatched"] = $bits[2];
$output["rowsChanged"] = $bits[5];
$output["warnings"] = $bits[8];
return $output;
}
return false;
}
I'm a beginner in OOP PHP.
I'm trying to make a class that will connect,query and fetch data
I done the below coding
class MySQL {
private $set_host;
private $set_username;
private $set_password;
private $set_database;
public function __Construct($set_host, $set_username, $set_password){
$this->host = $set_host;
$this->username = $set_username;
$this->password = $set_password;
$con= mysql_connect($this->host, $this->username, $this->password);
if(!$con){ die("Couldn't connect"); }
}
public function Database($set_database)
{
$this->database=$set_database;
mysql_select_db($this->database)or die("cannot select Dataabase");
}
public function Fetch($set_table_name){
$this->table_name=$set_table_name;
$query=mysql_query("SELECT * FROM ".$this->table_name);
$result= mysql_fetch_array($query);
}
}
$connect = new MySQL('localhost','root','');
$connect->Database('cms');
$connect->Fetch('posts');
what I'm trying to achieve is this
$connect = new MySQL('localhost','root','');
$connect->Database('cms');
$connect->Fetch('posts');
and I want to fetch the data using a format like this
echo $result[0];
but I'm not getting that logic to make this happen
please help
Thanks!
Your Fetch function is only pulling one row from the database, and you aren't returning the results...
The method isn't the best, but in order to achieve what you're trying to do:
public function Fetch($set_table_name){
$query=mysql_query("SELECT * FROM ".$set_table_name);
$result = array();
while ($record = mysql_fetch_array($query)) {
$result[] = $record;
}
return $result;
}
This will make each row a part of $result, but you'll have to access it like this:
You would call the fetch function like this:
$result = $connect->Fetch('posts');
echo $result[0]['columnName']; // for row 0;
Or in a loop:
for ($x = 0; $x < count($result); $x++) {
echo $result[$x][0] . "<BR>"; // outputs the first column from every row
}
That said, fetching the entire result set into memory is not a great idea (some would say it's a very bad idea.)
Edit: It also looks like you have other issues with your class... I have to run but will check back tomorrow and if others haven't set you straight I will expand.
Edit2: Ok, going to do a once-over on your class and try to explain a few things:
class MySQL {
//declaring the private variables that you will access through $this->variable;
private $host;
private $username;
private $password;
private $database;
private $conn; // Adding the connection, more on this later.
public function __Construct($set_host, $set_username, $set_password){
$this->host = $set_host;
$this->username = $set_username;
$this->password = $set_password;
// Combining the connection & connection check using 'or'
// Notice that I removed the semi-colon after the mysql_connect function
$this->conn = mysql_connect($this->host, $this->username, $this->password)
or die("Couldn't connect");
}
public function Database($set_database)
{
$this->database=$set_database;
// Adding the connection to the function allows you to have multiple
// different connections at the same time. Without it, it would use
// the most recent connection.
mysql_select_db($this->database, $this->conn) or die("cannot select Dataabase");
}
public function Fetch($table_name){
// Adding the connection to the function and return the result object instead
return mysql_query("SELECT * FROM ".$table_name, $this->conn);
}
}
$connect = new MySQL('localhost','root','');
$connect->Database('cms');
$posts = $connect->Fetch('posts');
if ($posts && mysql_num_rows($posts) > 0) {
echo "Here is some post data:<BR>";
while ($record = mysql_fetch_array($posts)) {
echo $record[0]; // or a quoted string column name instead of numerical index.
}
} else {
echo "No posts!";
}
I hope this helps... It should get you started at least. If you have more questions you should ask them separately.
That's because $result is set inside the Fetch function. It won't be available outside the Fetch function.
Instead of this line $result= mysql_fetch_array($query);, you'll want something like return mysql_fetch_array($query);.
And then in your code
$row = $connect->Fetch('posts');
// do something with $row
On another note, your Fetch function only applies to database queries that return one row. You'll have to separate the mysql_query & mysql_fetch_array calls into another function if you want to loop through rows in a query result.
And on another note, you shouldn't need to encapsulate this code into a class. PHP already provides OOP-based database classes called PDO, or PHP Data Objects. There's a learning curve to it, but it's best practice, and will help secure your code against things like SQL injection.
This is a pretty good tutorial: http://www.giantflyingsaucer.com/blog/?p=2478
I would make a function that returns the value of the object.
public function returnData($data){
return $this->$data;
}
Then within the page you wish to get the data on just initiate the class and call the function within that class.
$post->returnDate("row name here");
<?php
//database.php
class Databases{
public $con;
public function __construct()
{
$this->con = mysqli_connect("localhost", "root", "", "giit");
if(!$this->con)
{
echo 'Database Connection Error ' . mysqli_connect_error($this->con);
}
}
public function insert($table_name, $data)
{
$string = "INSERT INTO ".$table_name." (";
$string .= implode(",", array_keys($data)) . ') VALUES (';
$string .= "'" . implode("','", array_values($data)) . "')";
if(mysqli_query($this->con, $string))
{
return true;
}
else
{
echo mysqli_error($this->con);
}
}
public function selectmulti($selecttype,$table_name)
{
$array = array();
$query = "SELECT ".$selecttype." FROM ".$table_name."";
$result = mysqli_query($this->con, $query);
while($row = mysqli_fetch_assoc($result))
{
$array[] = $row;
}
return $array;
}
public function selectsingle($selecttype,$table_name)
{
$query = "SELECT ".$selecttype." FROM ".$table_name."";
$result = mysqli_query($this->con, $query);
$row = mysqli_fetch_assoc($result);
return $row;
}
}
?>
<?php
$data = new Databases;
$post_data = $data->selectmulti('*','centerdetail');
$n = 1;
foreach($post_data as $post)
{
echo $n.'.'.$post['CenterCode'].'___';
$n += 1;
}
echo '<br>';
$post_data = $data->selectsingle('*','centerdetail');
echo $post_data['CenterCode'];
?>