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>";
}
Related
i already had forms where I got the variable from the header but the forms have always been pdo and always one single query. This form is connected via mysqli and I just can't figure out how to get a variable.
<?php
$mysqli = new mysqli("localhost:3307", "root", "root", "test");
if($mysqli->connect_errno)
die ("Connection failed".$mysqli->connect_error);
$query = "SELECT * FROM contacts WHERE id = ?;";
$query .= "SELECT * FROM companies WHERE id = ?;";
if($mysqli->multi_query($query)) {
do{
$result = $mysqli->store_result();
$finfo = $result->fetch_fields();
echo"<table border ='1'>";
echo "<tr>";
foreach($finfo as $f) {
echo "<th>".$f->name."</th>";
}
echo "<br>";
echo "<br>";
echo "</tr>";
while($row = $result->fetch_assoc()) {
echo "<tr>";
foreach($row as $v) {
echo "<td>".$v."</td>";
}
echo "</tr>";
}
} while ($mysqli->more_results() && $mysqli->next_result());
}
?>
So the column "id" in both tables is the PK/FK and I want to retrieve information where id = ?.
How do I get the ? variable from the header and pass it on?
I feel like in my past tries I got the variable successfully with this code
$id=isset($_GET['id']) ? $_GET['id'] : die('ERROR: Record ID not found.');
[...]
$statement = $mysqli->prepare($query);
$statement->bindParam(1, $id);
$statement->execute();
but didn't echo it correctly.
Thank you in advance!
I am currently learning php right now. I have been trying to create a to-do app in which I add tasks to a SQL database using PDO. I have set up a table to display the task but I would like to add a button at the end of each row.
<?php
echo "<table>";
echo "<tr><th>Id</th><th>Task</th><th>Time entered</tr></tr>";
class TableRows extends RecursiveIteratorIterator {
function __construct($it) {
parent::__construct($it, self::LEAVES_ONLY);
}
function current() {
return "<td style='width:150px;border:1px solid black;'>" . parent::current(). "</td>";
}
function beginChildren() {
echo "<tr>";
}
function endChildren() {
echo "</tr>" . "\n";
}
}
$servername = "localhost";
$username = "root";
$password = "";
$dbname ="todolist";
$pdo = new PDO("mysql:host=$servername;dbname=$dbname",$username,$password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if(isset($_POST['submit'])){
$task = $_POST['task'];
//Create Record
$sql = "INSERT INTO todoapp (task) VALUES ('$task')";
$pdo->exec($sql);
$last_id = $pdo->lastInsertId();
echo "New record is created and the last inserted ID is: ".$last_id;
$stmt = $pdo->prepare("SELECT * FROM todoapp");
$stmt->execute();
$result= $stmt->setFetchMode(PDO::FETCH_ASSOC);
foreach(new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as $k=>$v){
echo $v;
}
}
$pdo = null;
?>
Hi I am learning how to make a simple mvc with php, but seem to be running into a little trouble with executing the queries inside the class function.
When I take the codes out of the class function they work fine. But they dont work when the code is inside. Any ideas would be appreciated thanks.
<?php
include_once("model/book.php");
class Model {
public function getBookList()
{
$conn=mysqli_connect("localhost","Ory4n","","test");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT Title, Author, Description FROM books";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo '<h2 class="word">'.$row["Title"].'</h2>';
echo '<h4 class="word">'.$row["Author"].'</h4>';
echo '<p class="word">'.$row["Description"].'</p>';
}
} else {
echo "0 results";
}
} // close function
public function getBook($title)
{
getBookList();
}
}
?>
Summarizing the comments...
<?php
class Model {
/**
* #return array Empty array in case of no results
*/
public function getBookList() {
$conn=mysqli_connect("localhost","Ory4n","","test");
if($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT Title, Author, Description FROM books";
$result = $conn->query($sql);
$books = array();
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$book = new stdClass();
$book->title = $row['Title'];
$book->author = $row['Author'];
$book->description = $row['Description'];
$books[] = $book;
}
}
return $books;
}
}
//Demo - how to use
$model = new Model();
$books = $model->getBookList();
foreach($books as $book) {
echo '<h2 class="word">'.$book->title.'</h2>';
echo '<h4 class="word">'.$book->author.'</h4>';
echo '<p class="word">'.$book->description.'</p>';
}
?>
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);
I have tried following code in several ways. but problem is occurred always in "$row = mysqli_fetch_assoc($result)" ..... print_r() method prints the result as an array, that means there is no error with MYSQL query. it gives correct result. problem is in fetch assoc. instead of 'assoc' I have used 'array' as well.
error says "Warning: mysqli_fetch_assoc() expects parameter 1 to be
mysqli_result, array given in
C:\xampp\htdocs\offoptimizer2\action\fetch_client.php on line 21"
class fetch_client{
public function fetchdata(){
$phn_number = $_GET["phn"];
$db_action = new db_action();
$result = $db_action->select_all("offopt_client","client_phn_no='".$phn_number."'");
print_r($result);
echo '<table border="0">';
echo '<tr>';
echo '<th> client name </th>';
echo '<th> client phone number </th>';
echo '</tr>';
if($result != null){
while($row = mysqli_fetch_assoc($result)){
echo '<tr>';
echo "<td> ".$row['client_name']." </td>";
echo "<td> ".$row['client_phn_no']." </td>";
echo '</tr>';
}
echo '</table>';
}else{
echo 'No result';
}
}
}
// this is my select_all function below
public function select_all($table_name, $where){
$db_connect = new db_connect();
$con = $db_connect->connect();
if(!$con){
echo "Connection error";
}else{
$query = mysqli_query($con,"select * from ".$table_name." where ".$where." ");
if(!$query){
echo "Error in your query".mysqli_error($query);
}else{
$result = mysqli_fetch_array($query);
return $result;
}
}
}
Uptate your 'select_all' function as below.
public function select_all($table_name, $where){
$db_connect = new db_connect();
$con = $db_connect->connect();
if(!$con){
echo "Connection error";
}else{
$query = mysqli_query($con,"select * from ".$table_name." where ".$where." ");
if(!$query){
echo "Error in your query".mysqli_error($query);
}else{
$result = array();
while($row = mysqli_fetch_assoc($query))
array_push($result, $row);
return $result;
}
}
}
And now, you can use the foreach loop on the result like below:
foreach($result as $row)
echo '<tr>';
echo "<td> ".$row['client_name']." </td>";
echo "<td> ".$row['client_phn_no']." </td>";
echo '</tr>';
}
mysqli_fetch_assoc need a ressource not an array. So this looks like your $db_action->select_all method return your database data in an array, so performing additional task with the result on mysqli functions won't work.
Edit your class behind $db_action if you wish to get assoc return data.