Im trying to convert this script, in my Zend program.
http://github.com/jackmoore/colorrating/raw/master/rating/rating.php
<?php
class rating{
public $average = 0;
public $votes;
public $status;
public $table;
private $path;
function __construct($table){
try{
$pathinfo = pathinfo(__FILE__);
$this->path = realpath($pathinfo['dirname']) . "/database/ratings.sqlite";
$dbh = new PDO("sqlite:$this->path");
$this->table = $dbh->quote($table);
// check if table needs to be created
$table_check = $dbh->query("SELECT * FROM $this->table WHERE id='1'");
if(!$table_check){
// create database table
$dbh->query("CREATE TABLE $this->table (id INTEGER PRIMARY KEY, rating FLOAT(3,2), ip VARCHAR(15))");
$dbh->query("INSERT INTO $this->table (rating, ip) VALUES (0, 'master')");
} else {
$this->average = $table_check->fetchColumn(1);
}
$this->votes = ($dbh->query("SELECT COUNT(*) FROM $this->table")->fetchColumn()-1);
}catch( PDOException $exception ){
die($exception->getMessage());
}
$dbh = NULL;
}
function set_score($score, $ip){
try{
$dbh = new PDO("sqlite:$this->path");
$voted = $dbh->query("SELECT id FROM $this->table WHERE ip='$ip'");
if(sizeof($voted->fetchAll())==0){
$dbh->query("INSERT INTO $this->table (rating, ip) VALUES ($score, '$ip')");
$this->votes++;
//cache average in the master row
$statement = $dbh->query("SELECT rating FROM $this->table");
$total = $quantity = 0;
$row = $statement->fetch(); //skip the master row
while($row = $statement->fetch()){
$total = $total + $row[0];
$quantity++;
}
$this->average = round((($total*20)/$quantity),0);
$statement = $dbh->query("UPDATE $this->table SET rating = $this->average WHERE id=1");
$this->status = '(thanks!)';
} else {
$this->status = '(already scored)';
}
}catch( PDOException $exception ){
die($exception->getMessage());
}
$dbh = NULL;
}
}
function rating_form($table){
$ip = $_SERVER["REMOTE_ADDR"];
if(!isset($table) && isset($_GET['table'])){
$table = $_GET['table'];
}
$rating = new rating($table);
$status = "<div class='score'>
<a class='score1' href='?score=1&table=$table&user=$ip'>1</a>
<a class='score2' href='?score=2&table=$table&user=$ip'>2</a>
<a class='score3' href='?score=3&table=$table&user=$ip'>3</a>
<a class='score4' href='?score=4&table=$table&user=$ip'>4</a>
<a class='score5' href='?score=5&table=$table&user=$ip'>5</a>
</div>
";
if(isset($_GET['score'])){
$score = $_GET['score'];
if(is_numeric($score) && $score <=5 && $score >=1 && ($table==$_GET['table']) && isset($_GET["user"]) && $ip==$_GET["user"]){
$rating->set_score($score, $ip);
$status = $rating->status;
}
}
if(!isset($_GET['update'])){ echo "<div class='rating_wrapper'>"; }
?>
<div class="sp_rating">
<div class="rating">Rating:</div>
<div class="base"><div class="average" style="width:<?php echo $rating->average; ?>%"><?php echo $rating->average; ?></div></div>
<div class="votes"><?php echo $rating->votes; ?> votes</div>
<div class="status">
<?php echo $status; ?>
</div>
</div>
<?php
if(!isset($_GET['update'])){ echo "</div>"; }
}
if(isset($_GET['update'])&&isset($_GET['table'])){
rating_form($_GET['table']);
}
How can I change this to Mysql?
Im using $dbh = Zend_Registry::get ( "db" ); normally to get my sql access.
Thanks everyone, hopefully there isnt too many changes invloved
If the db object in the registry is one of Zend_Db then:
$dbh->quote() becomes $db->quote() (the easy one)
$dbh->query() statements that manipulate data could translate to $dbh->query() (again, easy). However, it would be better to update the code to use $db->insert($table, $data) - or use Zend_Db_Table objects with $table->insert($data).
$dbh->query() statments that return data can become $db->fetchAll($sql) statements, but you need to update the code to expect Zend_Db Row and Rowset objects.
I'd suggest reading the Zend_Db
documentation to understand the what functions map to the different PDO functions.
If you just need this to work with MySQL change the DSN string to your MySQL connection. Something like:
$dbh = new PDO("mysql:dbname=testdb;host=127.0.0.1", $user, $pass);
See the PDO documentation for details.
If the db object in the registry a PDO instance just grab that object and use it, instead of creating a new PDO object.
Related
I am adding straw polls to a website using this tutorial: http://code.tutsplus.com/articles/creating-a-web-poll-with-php--net-14257
I have modified this code so I can create my own polls by entering the poll title and questions which gets stored in a database table. This table is then queried and the polls are loaded from the database. This is working fine, however, when I am trying to return the number of votes for each question the value is coming back 0 every time. The table 'tally' holds the question id, answer id and number of votes.
When I try to insert data into this tally table from the webPoll class, both the QID and AID rows are blank, only the votes value increments each time.
My database is MySQL, the tutorial I followed was to insert data into an SQLite DB, I think this might be the problem but I can't seem to find a solution as of yet.
In summary, I need to get the insert statements in the webPoll class inserting QID, AID & votes values as QID and AID are not inserting.
tally
CREATE TABLE tally (
QID varchar(32) NOT NULL,
AID integer NOT NULL,
votes integer NOT NULL,
PRIMARY KEY (QID,AID))
webPoll Class
$mysql_host = "localhost";
$mysql_database = "vote";
$mysql_user = "root";
$mysql_password = "";
class webPoll {
# makes some things more readable later
const POLL = true;
const VOTES = false;
# number of pixels for 1% on display bars
public $scale = 2;
public $question = '';
public $answers = array();
private $header = '<form class="webPoll" method="post" action="%src%">
<input type="hidden" name="QID" value="%qid%" />
<h4>%question%</h4>
<fieldset><ul>';
private $center = '';
private $footer = "\n</ul></fieldset>%button%\n</form>\n";
private $button = '<p class="buttons"><button type="submit" class="vote">Vote!</button></p>';
private $md5 = '';
/**
* ---
* Takes an array containing the question and list of answers as an
* argument. Creates the HTML for either the poll or the results depending
* on if the user has already voted
*/
public function __construct($params) {
$this->question = array_shift($params);
$this->answers = $params;
$this->md5 = md5($this->question);
$this->header = str_replace('%src%', $_SERVER['SCRIPT_NAME'], $this- >header);
$this->header = str_replace('%qid%', $this->md5, $this->header);
$this->header = str_replace('%question%', $this->question, $this->header);
# seperate cookie for each individual poll
isset($_COOKIE[$this->md5]) ? $this->poll(self::VOTES) : $this- >poll(self::POLL);
}
private function poll($show_poll) {
$replace = $show_poll ? $this->button : '';
$this->footer = str_replace('%button%', $replace, $this->footer);
# static function doesn't have access to instance variable
if(!$show_poll) {
$results = webPoll::getData($this->md5);
$votes = array_sum($results);
}
for( $x=0; $x<count($this->answers); $x++ ) {
$this->center .= $show_poll ? $this->pollLine($x) : $this->voteLine($this->answers[$x],$results[$x],$votes);
}
echo $this->header, $this->center, $this->footer;
}
private function pollLine($x) {
isset($this->answers[$x+1]) ? $class = 'bordered' : $class = '';
return "
<li class='$class'>
<label class='poll_active'>
<input type='radio' name='AID' value='$x' />
{$this->answers[$x]}
</label>
</li>
";
}
private function voteLine($answer,$result,$votes) {
$result = isset($result) ? $result : 0;
$percent = round(($result/$votes)*100);
$width = $percent * $this->scale;
return "
<li>
<div class='result' style='width:{$width}px;'> </div> {$percent}%
<label class='poll_results'>
$answer
</label>
</li>
";
}
/**
* processes incoming votes. votes are identified in the database by a combination
* of the question's MD5 hash, and the answer # ( an int 0 or greater ).
*/
static function vote() {
if(!isset($_POST['QID']) ||
!isset($_POST['AID']) ||
isset($_COOKIE[$_POST['QID']])) {
return;
}
try{
$dbh = new PDO('mysql:host=localhost;dbname=vote', 'root', '');
$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
} catch(PDOException $e) {
echo "Error: " . $e->getMessage() . "<br/>";
}
try {
$sth = $dbh->prepare("INSERT INTO tally (QID,AID,votes) values ('QID', 'AID', '1')" );
$sth->execute(array($_POST['QID'],$_POST['AID']));
}
catch(PDOException $e) {
# 23000 error code means the key already exists, so UPDATE!
if($e->getCode() == 23000) {
try {
$sth = $dbh->prepare("UPDATE tally SET votes = votes + 1 WHERE QID='$QID' AND AID='$AID'");
$sth->execute(array($_POST['QID'],$_POST['AID']));
}
catch(PDOException $e) {
webPoll::db_error($e->getMessage());
}
}
else {
webPoll::db_error($e->getMessage());
}
}
# entry in $_COOKIE to signify the user has voted, if he has
if($sth->rowCount() == 1) {
setcookie($_POST['QID'], 1, time()+60*60*24*365);
$_COOKIE[$_POST['QID']] = 1;
}
}
static function getData($question_id) {
try {
$dbh = new PDO('mysql:host=localhost;dbname=vote', 'root', '');
$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$STH = $dbh->prepare('SELECT AID, votes FROM tally WHERE QID = ?');
$STH->execute(array($question_id));
}
catch(PDOException $e) {
# Error getting data, just send empty data set
webPoll::db_error($e->getMessage());
return array(0);
}
while($row = $STH->fetch()) {
$results[$row['AID']] = $row['votes'];
}
return $results;
}
/*
* You can do something with the error message if you like. Email yourself
* so you know something happened, or make an entry in a log
*/
static function db_error($error) {
echo "A database error has occured. $error";
exit;
}
}
You are using the prepared statements incorrectly. Inside the values you should have placeholders. The values in the execute are bound to those placeholders.
So:
$sth = $dbh->prepare("INSERT INTO tally (QID,AID,votes) values ('QID', 'AID', '1')" );
Is sending QID, and AID to your DB. If those are integer columns I suspect you'll get 0s in their place.
You should change this to:
$sth = $dbh->prepare("INSERT INTO tally (QID,AID,votes) values (?, ?', '1')" );
Your execute:
$sth->execute(array($_POST['QID'],$_POST['AID']));
Is already set up correctly to pass the two values to the placeholders.
You also need to fix another update further down.
$sth = $dbh->prepare("UPDATE tally SET votes = votes + 1 WHERE QID=? AND AID= ?");
Prepared statements should rarely have variables in them and if they are in there they should have been checked against a whitelist of allowed terms.
You can read more about prepared statements:
http://php.net/manual/en/pdo.prepared-statements.php
https://en.wikipedia.org/wiki/Prepared_statement
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.
Hello I'm trying to make a code to UPDATE or EDIT the survey answers and comments per answer but when I execute the function submiting the form, it did not save any value into the database. What can I do to fix it?
I'm new in PDO.
Thanks in advance.
Database Structure
"Questions" (idquestion, question)
"Surveys" (idsurvey, idquestion, answers, comments_per_question, survey_number)
Update function
public function ModifySurveyMulti($answer = array())
{
if(!empty($answer)) {
foreach($answer as $questi => $value ) {
$this->MyDB->Write("UPDATE survey SET(
`idquestion` = '".$questi."',
`answers` = '".$value[0]."',
`comments_per_answer`= '".$_POST["comment"][$questi]."')");
}
}
}
modify_surveyform.php
<th><?php echo $row["questions"];?></th>
<td>
<input type = "text"
name = "answer[<?php echo $row['idquestion'];?>][]"
value = "<?php echo $row["answers"];?>">
</input>
</td>
<td>
<Textarea type = "text"
name = "comment[<?php echo $row['idquestion'];?>]"
cols = "50" rows = "3"/> <?php echo $row["comment"];?
</textarea>
</td>
</tr><?php } ?>
Mydbconnect.php
<?php
// I'm adding my PDO database because yours is deprecated
class DBConnect
{
public $con;
// Create a default database element
public function __construct($host = '',$db = '',$user = '',$pass = '')
{
try {
$this->con = new PDO("mysql:host=$host;
dbname=$db",$user,
$pass, array(
PDO::ATTR_ERRMODE
=> PDO::ERRMODE_WARNING
)
);
}
catch (Exception $e) {
return 0;
}
}
// Simple fetch and return method
public function Fetch($_sql)
{
$query = $this->con->prepare($_sql);
$query->execute();
if($query->rowCount() > 0) {
while($array = $query->fetch(PDO::FETCH_ASSOC)) {
$rows[] = $array;
}
}
return (isset($rows) && $rows !== 0 && !empty($rows))? $rows: 0;
}
// Simple write to db method
public function Write($_sql)
{
$query = $this->con->prepare($_sql);
$query->execute();
}
}?>
Few things you need to do:
First of all ditch this code, it is useless and expose you to sql
injection
Use PDO directly with prepared statement
The query you need is :
UPDATE survey SET(`answers`= ?,`comments_per_answer`= ?) WHERE idquestion = ?
You will need to adjust your class to only create the connection
class DBConnect
{
public $con;
public function __construct($host = '',$db = '',$user = '',$pass = '')
{
try {
$this->con = new PDO(
"mysql:host=$host;dbname=$db",
$user,$pass,
array(PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING)
);
}
catch (Exception $e) {
die($e);
}
}
public function get_connection(){
return $this->con;
}
}
So that you can create it like this:
$db = new DBConnect(/*pass arguments here*/);
$this->MyDB = $db->get_connection();
Modify and use it in your function:
public function ModifySurveyMulti($answer = array(), $comments)
{
$sql = 'UPDATE survey SET(`answers`= ?,`comments_per_answer`= ?)
WHERE idquestion = ?';
$stmt->prepare($sql);
foreach($answer as $questi => $value ) {
$stmt->execute(array($value, $comments[$questi],$questi));
$count = $stmt->rowCount();
echo $count > 0 ? $questi.' updated' : $questi.' did not update';
}
}
Call the function :
if(isset($_POST['answer'], $_POST['comments'])){
$answers = $_POST['answer'];
$comments = $_POST['comments'];
ModifySurveyMulti($answers, $comments);
}
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'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'];
?>