-4

I'm hesitant to post this, as I'd really prefer to figure this out myself, but I don't think I will. I'm just trying to set a class for mysqli stuff, to make it as dynamic as possible, and yes I'm newer to OOP, but have been using PHP and Mysql as a hobby, and more heavily lately, for quite some time. I figured it was time to switch, but there just isn't that much on oop classes with mysqli and prepared statements with a possibility of multiple results (yes I've check documentation, guess I'm just not getting it or something). After quite a few hours, this is what I have. I'm not necessarily looking for a "quick fix". I really want to understand this and learn, so please explain thoroughly.

I'm using a dbconfig.php file to store my database info at root/config/dbconfig.php

in root/classes/mysqlicon.php

<?php
/*
* class MYSQLIDB
* @param Host
* @param User 
* @param Password
* @param Name
*/
class MYSQLIDB
{
private $host;       //MySQL Host
private $user;       //MySQL User
private $pass;       //MySQL Password
private $name;       //MySQL Name   
private $mysqli;     //MySQLi Object
private $last_query; //Last Query Run

/*
 * Class Constructor
 * Creates a new MySQLi Object
*/
public function __construct()
{   
    include('./config/dbconfig.php');
    $this->host = $db_host;
    $this->user = $db_user;
    $this->pass = $db_pass;
    $this->name = $db_name;

    $this->mysqli = new mysqli($this->host, $this->user, $this->pass, $this->name);
    if ($mysqli->connect_errno) {
        return "Failed to connect to MySQLi: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
    }

}

private function __destruct()
{   
    $mysqli->close();
}

public function select($fields, $from, $where, $whereVal, $type, $orderByVal, $ASDESC, $limitVal)
{
    if (is_int($whereVal))
    {
        $bindVal = 'i';
    } else {
        $bindVal = 's';
    }
    switch($type)
    {
        case "regular":
            $queryPre = "SELECT " . $fields;
            $querySuff = " WHERE " . $where . " =  ?";
            break;
        case "orderByLimit":
            $queryPre = "SELECT " . $fields;
            $querySuff = " ORDER BY " . $orderByVal . " " . $ASDESC . " LIMIT " . $limitVal;
            break;
    }
    //$query = "SELECT * FROM news ORDER BY id DESC LIMIT 4";
    if ($stmt = $mysqli->prepare('$queryPre . " FROM " . $from . " " . $querySuff')) 
    {
        if ($type == 'regular') {
            $stmt->bind_param($bindVal, $whereVal);
        }
        $stmt->execute(); 
        $stmt->bind_result($values); 
        $stmt->store_result(); 
        $sr = new Statement_Result($stmt);      
        $stmt->fetch(); 
        // call by this style printf("ID: %d\n", $sr->Get('id') ); 
        //$stmt->fetch(); 
        //$stmt->close(); 
        //return $value;
        printf("ID: %d\n", $sr->Get_Array() );
    } else return null; 
}
//use to call $db = new MYSQLI('localhost', 'root', '', 'blog');
/*
 * Function Select
 * @param fields
 * @param from
 * @param where
 * @returns Query Result Set

function select($fields, $from, $where, $orderBy, $ASDESC, $limit, varNamesSent)
{   
    if ($orderBy == null &&)
    $query = "SELECT " . $fields . " FROM `" . $from . "` WHERE " . $where;
    $result = $this->mysqli->query($query) or exit("Error code ({$sql->errno}): {$sql->error}");

    $this->last_query = $query;

    return $result;
}

/*
 * Function Insert
 * @param into
 * @param values
 * @returns boolean
*/
public function insert($into, $values)
{
    $query = "INSERT INTO " . $into . " VALUES(" . $values . ")";

    $this->last_query = $query;

    if($this->mysqli->query($query))
    {
        return true;
    } else {
        return false;
    }

}

/*
 * Function Delete
 * @param from
 * @param where
 * @returns boolean
*/
public function delete($from, $where)
{
    $query = "DELETE FROM " . $from . " WHERE " . $where;

    $this->last_query = $query;

    if($this->mysqli->query($query))
    {
        return true;
    } else {
        return false;
    }
}
}
//Hand arrays for multiple returned items from database
class Statement_Result 
{ 
private $_bindVarsArray = array(); 
private $_results = array(); 

public function __construct(&$stmt) 
{ 
    $meta = $stmt->result_metadata(); 

    while ($columnName = $meta->fetch_field()) 
        $this->_bindVarsArray[] = &$this->_results[$columnName->name]; 

    call_user_func_array(array($stmt, 'bind_result'), $this->_bindVarsArray);

    $meta->close(); 
} 

public function Get_Array() 
{ 
    return $this->_results;    
} 

public function Get($column_name) 
{ 
    return $this->_results[$column_name]; 
} 
} 
?>

And just as a test, I'm trying to pull all the news in my db by:

<?php
require_once('classes/mysqlicon.php');
$testing = new MYSQLIDB;
$testing->select('*','news',null,null,'orderByLimit','id','DESC',4);
?>

But what I really want is stuff that can do the equivalent of this:

<?php
    /*
    require('config/dbconfig.php');
    $query = "SELECT * FROM news ORDER BY id DESC LIMIT 4";
    if ($stmt = $mysqli->prepare($query)) {
        // execute statement
        $stmt->execute();

        // bind result variables
        $stmt->bind_result($idn, $titlen, $categoryn, $descn, $postdaten, $authorn);

        // fetch values
        while ($stmt->fetch()) {*/

            //echo 'id: '. $id .' title: '. $title;
            echo "<table border='0'>";
            $shortDescLengthn = strlen($descn);
            if ($shortDescLengthn > 106) {
                $sDCutn = 106 - $shortDescLengthn;
                $shortDescn = substr($descn, 0, $sDCutn);
            } else {
                $shortDescn = $descn;
            }
            echo "<h1>$titlen</h1>"; 
            echo "<tr><td>$shortDescn...</td></tr>"; 
            echo '<tr><td><a href="javascript:void(0);" onclick="' 
            . 'readMore(' . $idn . ',' . htmlspecialchars(json_encode($titlen)) . ',' 
            . htmlspecialchars(json_encode($categoryn)) . ',' 
            . htmlspecialchars(json_encode($descn)) . ',' . htmlspecialchars(json_encode($postdaten)) . ',' 
            . htmlspecialchars(json_encode($authorn)) . ')">Read More</a></td></tr>'; 
            echo "<tr><td>Written by: $authorn</td></tr>"; 
            echo '<tr><td><img src="images/hardcore-games-newsbar-border.png" width="468px" /></td></tr>'; 
        }
        echo "</table><br />";

        /* close statement */
        $stmt->close();
    }

    /* close connection */
    $mysqli->close();
?>

Again, please, please explain in detail. I'm a blockhead sometimes.

tereško
  • 58,060
  • 25
  • 98
  • 150
Grant
  • 196
  • 1
  • 4
  • 16
  • 1
    I don't really understand why people are so rude on this site (which is usually why I hate posting here). I forgot. Plain and simple. If you want me to get into why I can, as I have a pretty sick kid right now, but "...do you want to guess" is really unnecessary isn't it? in /home/content/20/9628620/html/classes/mysqlicon.php on line 62 – Grant Aug 06 '12 at 01:03
  • Certainly worth reading or re-reading: [How to ask a question](http://stackoverflow.com/questions/how-to-ask). If you want, you may edit your question to add relevant information. – Jocelyn Aug 06 '12 at 01:12
  • 1
    Only because someone comments your question is not rude. Take the comment as a reminder and that's it. No problem that you have forgotten something as long as it is okay for you that others ask for details. – hakre Aug 06 '12 at 01:13
  • "Hey can you tell us what line the error is on? It's not here." compated to "You are not giving us the line where the error occurs, do you want us to guess?" Well gee golly yup that's it. Must be it. I want you all to guess. Winner gets a prize. -_- You kidding me? – Grant Aug 06 '12 at 01:15
  • that are comments. they are quickly typed. don't read them and weight every word in gold. I'm fine with a rhetorical question and I do not think it's unfriendly. So just read more broadly please otherwise you can start to find a lot of negativity in written language, always. – hakre Aug 06 '12 at 01:21
  • It's not even a legitimate question for this site. "...do you want us to guess?" If you're going to slam me for forgetting something, refer to me on how to ask a question, then you should keep yourself to not be so rude (I'm sure something like that is in these site rules). Should I post a link on politeness on the internet and how to be nice? That's not a legimitate question per this site, it's policies, or in terms of "kindness" and "helpfullness". And that's not trying to find negativity, that IS negativity. – Grant Aug 06 '12 at 01:23
  • 1
    I agree. People can be real jerks on here. It is the plight of working with a bunch of programmers lacking soft skills. They don't mean it, they're just socially inept. –  Sep 12 '12 at 18:32
  • @Grant Kessler Jr You are right they do not understand that a new programmer or a new member might not know how to ask a question on this sit they just down vote yet they gain nothing from it . i really hate their behavior –  Feb 25 '13 at 15:59

1 Answers1

3

I'm assuming the error is coming from this line:

if ($stmt = $mysqli->prepare('$queryPre . " FROM " . $from . " " . $querySuff'))

$mysqli is not defined in the context of this function. You should be accessing $this->mysqli instead. The same applies to other references you have made such as here:

if ($mysqli->connect_errno)
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
  • 3
    Side note: that string is literal. – Wiseguy Aug 06 '12 at 01:00
  • Yup, probably need to take the single quotes off both ends. – Niet the Dark Absol Aug 06 '12 at 01:03
  • 1
    Done for all of that, and also took out $stmt->bind_result($values); as a different class is handeling the bind. I'm have it give me back "ID:1" now, so I'm still pretty lost. – Grant Aug 06 '12 at 01:09
  • 1
    @Kolink we want people like u who gives answers not those who execise down voting and by the end of the day they do not answer –  Feb 25 '13 at 16:01