I'm trying to read from mysql with php and with oop.How can use from propeties?
This is my class and search function for reading from the database:
<?php
require_once('dbconfig.php');
class Film {
public $name;
public $year;
public $country;
public $director;
private $conn;
public function __construct() {
$database = new Database();
$db = $database->dbConnection();
$this->conn = $db;
}
public function runQuery($sql) {
$stmt = $this->conn->prepare($sql);
return $stmt;
}
public function search($name,$year,$country,$director) {
try {
$stmt = $this->conn->prepare("SELECT * FROM table where name='$name' or year='$year' or country='$country' or director='$director'");
$stmt->execute();
$num_rows = $stmt->rowCount();
if ($num_rows > 0) {
echo "</br>".$num_rows." film is found. </br>";
echo "</br><table><tr><th>Name</th><th>Year</th><th>Country</th><th>durationMinutes</th><th>Director</th></tr>";
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo "<tr><td>" . $row['name'] . "</td><td>" . $row['year'] . "</td><td>" . $row['country'] . "</td><td>" . $row['durationMinutes'] . "</td><td>" . $row['director'] . "</td></tr>";
}
echo "</table>";
} else {
echo "Nothing found !";
}
} catch (PDOException $e) {
echo $e->getMessage();
}
}
}
I want search() is based on the object and properties.
How to change my code?
Did you mean you want to call that function?
just put this code wherever you wanna place it e.g in index.php.
$film->search($name,$year,$country,$director);
but you have to initial class film in your connection file like this
session_start();
$host = "localhost";
$user = "root";
$pass = "";
$database="database";
try {
$con = new PDO ("mysql:host={$host}; dbname={$database}", $user, $pass);
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT);
}
catch (PDOEXception $e) {
echo $e->getMessage();
}
include_once 'class_film.php';
$film= new Film($con);
Related
I have zf2 model. Inside the model, there is a function to communicate with the database with transaction.
Between the transaction I'm calling a recursive function to do transaction, where I'm passing the transaction object. Without recursive function calling it's running fine, but when I'm going to call any function where some query is running, it sends false, and due to receiving false it's being rollbacked. Below are the example code:
<?php
namespace Admin\Model;
use Zend\Db\TableGateway\TableGateway;
use Exception;
class ProjectAssignTable {
protected $tableGateway;
public function __construct(TableGateway $tableGateway) {
$this->tableGateway = $tableGateway;
}
/**
* $empidArray = array(1, 2, 3, 5, 12, 35);
*/
public function saveProjectAssignment($project_id, $empidArray, $data) {
$connection = $this->tableGateway->getAdapter()->getDriver()->getConnection();
$connection->beginTransaction();
try {
$sqlDelete = "DELETE FROM rjs_assignproject WHERE project_id= '" . $project_id . "' ";
$connection->execute($sqlDelete);
for ($x = 0; $x < count($empidArray); $x++) {
$sqlInsert = "INSERT INTO `rjs_assignproject` SET project_id='" . $project_id . "',admin_id='" . $empidArray[$x] . "',designation_id='" . $data['desgi_' . $empidArray[$x]] . "',comment='" . $data['comment_' . $empidArray[$x]] . "',datetime_from='" . $data['time_from' . $empidArray[$x]] . "',datetime_to='" . $data['time_to' . $empidArray[$x]] . "' ";
$resultHistory = $connection->execute($sqlInsert);
if (!$this->recursiveEntry($connection, $empidArray[$x], $project_id)) {
throw new Exception();
} else {
return true;
}
}
$connection->commit();
return true;
} catch (Exception $ex) {
$connection->rollback();
}
}
public function recursiveEntry($connection, $admin_id, $project_id) {
try {
$sql1 = "select * from rjs_admins where admin_id in(select parent_id from rjs_admins where admin_id=$admin_id)";
$result1 = $connection->execute($sql1);
if (count($result1) > 0) {
$sql2 = "select * from rjs_assignproject where admin_id='" . $result1[0]->admin_id . "'";
$result2 = $connection->execute($sql2);
if (count($result2) < 1) {
$sql3 = "INSERT INTO `rjs_assignproject` SET project_id='" . $project_id . "',admin_id='" . $result1[0]->admin_id . "',designation_id='" . $result1[0]->designation_id . "' ";
$connection->execute($sql3);
if (!$this->recursiveEntry($connection, $result1[0]->admin_id, $project_id)) {
throw new Exception();
} else {
return true;
}
}
}
} catch (Exception $ex) {
return false;
}
}
}
Your method doesn't return anything after try/catch block:
public function recursiveEntry($connection, $admin_id, $project_id) {
try {
// ...
if (!$this->recursiveEntry($connection, $result1[0]->admin_id, $project_id)) {
throw new Exception();
} else {
return true; // We will never get here
}
} catch (Exception $ex) {
return false;
}
// return null
}
Try this:
public function recursiveEntry($connection, $admin_id, $project_id) {
try {
$sql1 = "select * from rjs_admins where admin_id in(select parent_id from rjs_admins where admin_id=$admin_id)";
$result1 = $connection->execute($sql1);
if (count($result1) > 0) {
$sql2 = "select * from rjs_assignproject where admin_id='" . $result1[0]->admin_id . "'";
$result2 = $connection->execute($sql2);
if (count($result2) < 1) {
$sql3 = "INSERT INTO `rjs_assignproject` SET project_id='" . $project_id . "',admin_id='" . $result1[0]->admin_id . "',designation_id='" . $result1[0]->designation_id . "' ";
$connection->execute($sql3);
if (!$this->recursiveEntry($connection, $result1[0]->admin_id, $project_id)) {
throw new Exception();
}
}
}
} catch (Exception $ex) {
return false;
}
return true;
}
I am a total noob with performing OOP, and am currently looking to refactor a procedural PHP project. Currently, I am having issues trying to simply display my results from a SELECT query--ironically doing an INSERT query made sense instead. This is my Class file:
<?php
class MadLibs {
private $noun;
private $verb;
private $adverb;
private $adjective;
private $story;
// Getters
public function getNoun() {
return $this->noun;
}
public function getVerb() {
return $this->verb;
}
public function getAdverb() {
return $this->adverb;
}
public function getAdjective() {
return $this->adjective;
}
public function getStory() {
return $this->story;
}
// Setters
public function setNoun($noun) {
$this->noun = $noun;
}
public function setVerb($verb) {
$this->verb = $verb;
}
public function setAdverb($adverb) {
$this->adverb = $adverb;
}
public function setAdjective($adjective) {
$this->adjective = $adjective;
}
public function setStory($story) {
$this->story = $story;
}
// Figured this one out
public function insertStoryToDatabase() {
date_default_timezone_set('America/Chicago');
$submit_date = date('Y-m-d' . " " . 'H:i:s');
$dbc = mysqli_connect('localhost','root','','mad_libs')
or die('Error establishing connection');
$query = "INSERT INTO storyTime (noun, verb, adjective, adverb, createdDate, fullStory) " .
"VALUES ('$this->noun','$this->verb','$this->adjective','$this->adverb','$submit_date','$this->story')";
mysqli_query($dbc,$query)
or die('Error querying database');
mysqli_close($dbc);
}
// method I am having trouble setting up
public function displayAllStories() {
$dbc = mysqli_connect('localhost','root','','mad_libs')
or die('Error establishing connection');
$result = "SELECT fullStory, createdDate FROM storyTime ORDER BY createdDate DESC";
$display = mysqli_query($dbc,$result)
or die('Error gathering data!');
while ($row = mysqli_fetch_array($display)) {
echo $row['story'] . '<br/>';
}
return $display;
}
}
?>
And this is what I am doing in my other php file:
<?php
require_once('MadLibs.php');
// Instantiating instance of MadLibs()
$foo = new MadLibs();
// Playing around to see ensure getters/setters were correct
$foo->setNoun('Bob');
$foo->setVerb('jumps');
$foo->setAdverb('quietly');
$foo->setAdjective('ugly');
$foo->setStory("The " . $foo->getNoun() . " always " . $foo->getVerb() . " at the "
. $foo->getAdjective() . " strangers " . $foo->getAdverb() . ".");
echo $foo->getNoun();
echo '<br />';
echo $foo->getVerb();
echo '<br />';
echo $foo->getAdverb();
echo '<br />';
echo $foo->getAdjective();
echo '<br />';
echo $foo->getStory();
$foo->insertStoryToDatabase();
$foo->displayAllStories();
?>
I'm sure it's something simple, but for the life of me I can't figure out what I'm doing wrong.
Any and all feedback is most appreciated!
You trying to display wrong variable in displayAllStories() function .
'echo $row['story']should be change to$row['fullStory'];` or change your query to
SELECT fullStory as story, createdDate FROM storyTime ORDER BY createdDate DESC
I'm not new to PHP, but I am new to all this PDO and MVC stuff. I'm basically trying to echo out data from the database to the page.
Model (_dashboard.php)
<?php
require_once('_connection.php');
class ConnectToDB {
private $db;
public function __construct(){
$this->db =new connection();
$this->db = $this->db->dbConnection(); //uses the connection in connection class
}
public function teachersStudents($id){
// this function checks whether the user name exists and if its a match
if(!empty($id)){
$st = $this->db->prepare("SELECT * FROM students WHERE id=?");
$st->bindParam(1, $id);
$st->execute();
if ($st->rowCount() == 1) {
$result = $st->fetchAll();
foreach($result as $row){
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "</tr>";
}
}
}
}
}
// Close database connection
$dbh = null;
?>
View (dashboard.phtml)
<?php
require_once('_dashboard.php');
$object = new ConnectToDB();
$object->teachersStudents($id);
echo $result;
?>
Result
Notice: Undefined variable: result
I'm probably doing this completely wrong so a push in the right direction would be appreciated. Here's the controller but really has nothing to do with it.
Controller
<?php
$view = new stdClass();
$view->pageTitle = 'Dashboard';
require_once('views/dashboard.phtml');
$result is undefined Change your function to return the result.
$result = $st->fetchAll();
return $result;
Then move your code to display HTML in the view instead:
require_once('_dashboard.php');
$object = new ConnectToDB();
$result = $object->teachersStudents($id);
foreach($result as $row){
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "</tr>";
}
I have a class like this:
<?php
class DataConnection {
private $hostName = "localhost";
private $username = "root";
private $password = "";
private $dbName = "test";
private $link = "";
public function __construct() {
}
private function connect() {
$this->link = mysql_connect($this->hostName, $this->username, $this->password)
or die ("Could not connect to the database");
mysql_select_db($this->dbName, $this->link) or die("Could not select database");
}
// lay kieu du lieu cua record trong table
public function getDataTypeTable($tableName) {
$this->connect();// ERROR HERE
$query = "SELECT * FROM {$tableName}";
$result = mysql_query($query);
$fields = mysql_num_fields($result);
$rows = mysql_num_rows($result);
$table = mysql_field_table($result, 0);
echo "Your '" . $table . "' table has " . $fields . " fields and " . $rows . " record(s)\n";
echo "The table has the following fields:\n";
for ($i=0; $i < $fields; $i++) {
$type = mysql_field_type($result, $i);
$name = mysql_field_name($result, $i);
$len = mysql_field_len($result, $i);
$flags = mysql_field_flags($result, $i);
echo $type . " " . $name . " " . $len . " " . $flags . "\n";
}
//var_dump($results);
//mysql_free_result($results);
}
public function __destruct() {
mysql_close($this->link);
}
}
?>
I get an error "Fatal error: Using $this when not in object context in C:\xampp\htdocs\demo\test\DataConnection.php on line 44", it means that there is something wrong in connect function. How can I fix it? Thanks for watching!
Data that I add inside an SQLite3 db using prapared statements are not searchable with WHERE:
SELECT Active FROM Users WHERE Username="john"
I have a demonstration in PHP that adds data with a prepared and a direct statement and then tries to search for them.
My questions are two:
Why is this happening?
How can I search data that I add through prepared statements?
Here is the PHP script.
<?php
error_reporting(E_ALL);
date_default_timezone_set('Europe/Helsinki');
ini_set('default_charset', 'UTF-8');
mb_internal_encoding("UTF-8");
header('Content-Type: text/html; charset=UTF-8');
$timezone = date('Z');
$db = '';
// ---
//
// adds a user in the db with a prepared statement
//
function add_user1($name, $pass)
{
global $timezone;
global $db;
$time = time();
try
{
$statement = "INSERT INTO Users (Username, Password, Time, Timezone, Active) VALUES (:Username,:Password,:Time,:Timezone,:Active);";
$query = $db->prepare($statement);
$query->bindValue(':Username', $name, SQLITE3_TEXT);
$query->bindValue(':Password', $pass, SQLITE3_TEXT);
$query->bindValue(':Time', $time, SQLITE3_INTEGER);
$query->bindValue(':Timezone', $timezone, SQLITE3_INTEGER);
$query->bindValue(':Active', '1', SQLITE3_INTEGER);
$ok = $query->execute();
}
catch(PDOException $exception)
{
echo $exception->getMessage();
}
}
//
// adds a user in the db with a direct execution
//
function add_user2($name, $pass)
{
global $timezone;
global $db;
$time = time();
try
{
$db->exec('INSERT INTO Users (Username, Password, Time, Timezone, Active) VALUES ("' . $name . '", "' . $pass . '", ' . $time . ', ' . $timezone . ', 1);');
}
catch(PDOException $exception)
{
echo $exception->getMessage();
}
}
//
// seeks a password for a given username
//
function seek($user)
{
global $timezone;
global $db;
try
{
// previous tests showed that this doesn't work on all cases
$result = $db->query('SELECT Password FROM Users WHERE Username="'. $user . '"');
foreach ($result as $row)
{
$password = $row['Password'];
echo "search through SQLite: password for $user is $password\n";
}
$result = $db->query("SELECT * FROM Users");
foreach($result as $row)
{
$username = $row['Username'];
$password = $row['Password'];
if ($username == $user)
{
echo " search through array: password for $username is $password";
break;
}
}
}
catch(PDOException $exception)
{
echo $exception->getMessage();
}
}
// ---
echo "<pre>\n";
try
{
$db = new PDO('sqlite::memory:');
$db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$db->exec("CREATE TABLE IF NOT EXISTS Users (Id INTEGER PRIMARY KEY, Username TEXT UNIQUE NOT NULL, Password TEXT NOT NULL, Time INTEGER UNIQUE NOT NULL, Timezone INTEGER NOT NULL, Active BOOLEAN NOT NULL);");
}
catch(PDOException $exception)
{
echo $exception->getMessage();
}
add_user1("Bob", "cat");
sleep(1);
add_user1("Mark", "dog");
sleep(1);
add_user2("John", "mouse");
sleep(1);
add_user2("Alice", "rodent");
try
{
$result = $db->query('SELECT * FROM Users');
foreach ($result as $row)
{
echo " Id: " . $row['Id'] . "\n";
echo "Username: " . $row['Username'] . "\n";
echo "Password: " . $row['Password'] . "\n";
echo " Time: " . $row['Time'] . "\n";
echo "Timezone: " . $row['Timezone'] . "\n";
echo " Active: " . $row['Active'] . "\n";
echo "\n";
}
}
catch(PDOException $exception)
{
echo $exception->getMessage();
}
seek("Alice");
echo "\n\n";
seek("Mark");
$db = NULL;
?>
Someone told me I should remove the types on the binding. I did and it works :)
Thanks anyone who read it.
Here is the full working example.
<?php
error_reporting(E_ALL);
date_default_timezone_set('Europe/Helsinki');
ini_set('default_charset', 'UTF-8');
mb_internal_encoding("UTF-8");
header('Content-Type: text/html; charset=UTF-8');
$timezone = date('Z');
$db = '';
// ---
//
// adds a user in the db with a prepared statement
//
function add_user1($name, $pass)
{
global $timezone;
global $db;
$time = time();
try
{
$statement = "INSERT INTO Users (Username, Password, Time, Timezone, Active) VALUES (:Username,:Password,:Time,:Timezone,:Active);";
$query = $db->prepare($statement);
$query->bindValue(':Username', $name);
$query->bindValue(':Password', $pass);
$query->bindValue(':Time', $time);
$query->bindValue(':Timezone', $timezone);
$query->bindValue(':Active', '1');
$ok = $query->execute();
}
catch(PDOException $exception)
{
echo $exception->getMessage();
}
}
//
// adds a user in the db with a direct execution
//
function add_user2($name, $pass)
{
global $timezone;
global $db;
$time = time();
try
{
$db->exec('INSERT INTO Users (Username, Password, Time, Timezone, Active) VALUES ("' . $name . '", "' . $pass . '", ' . $time . ', ' . $timezone . ', 1);');
}
catch(PDOException $exception)
{
echo $exception->getMessage();
}
}
//
// seeks a password for a given username
//
function seek($user)
{
global $timezone;
global $db;
try
{
// previous tests showed that this doesn't work on all cases
$result = $db->query('SELECT Password FROM Users WHERE Username="'. $user . '"');
foreach ($result as $row)
{
$password = $row['Password'];
echo "search through SQLite: password for $user is $password\n";
}
$result = $db->query("SELECT * FROM Users");
foreach($result as $row)
{
$username = $row['Username'];
$password = $row['Password'];
if ($username == $user)
{
echo " search through array: password for $username is $password";
break;
}
}
}
catch(PDOException $exception)
{
echo $exception->getMessage();
}
}
// ---
echo "<pre>\n";
try
{
$db = new PDO('sqlite::memory:');
$db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$db->exec("CREATE TABLE IF NOT EXISTS Users (Id INTEGER PRIMARY KEY, Username TEXT UNIQUE NOT NULL, Password TEXT NOT NULL, Time INTEGER UNIQUE NOT NULL, Timezone INTEGER NOT NULL, Active BOOLEAN NOT NULL);");
}
catch(PDOException $exception)
{
echo $exception->getMessage();
}
add_user1("Bob", "cat");
sleep(1);
add_user1("Mark", "dog");
sleep(1);
add_user2("John", "mouse");
sleep(1);
add_user2("Alice", "rodent");
try
{
$result = $db->query('SELECT * FROM Users');
foreach ($result as $row)
{
echo " Id: " . $row['Id'] . "\n";
echo "Username: " . $row['Username'] . "\n";
echo "Password: " . $row['Password'] . "\n";
echo " Time: " . $row['Time'] . "\n";
echo "Timezone: " . $row['Timezone'] . "\n";
echo " Active: " . $row['Active'] . "\n";
echo "\n";
}
}
catch(PDOException $exception)
{
echo $exception->getMessage();
}
seek("Alice");
echo "\n\n";
seek("Mark");
$db = NULL;
?>