How to use multiple queries in one php function - php

Hi all i was just wondering how I would get a php function to run two sql queries my function at the moment is the code below the connection to the database is at the top of the page so I don't need to right the connection every time my full page code is :
<?php
class SelectList
{
protected $conn;
public function __construct()
{
$this->DbConnect();
}
protected function DbConnect()
{
include "db_config.php";
$this->conn = mysql_connect($host,$user,$password) OR die("Unable to connect to the database");
mysql_select_db($db,$this->conn) OR die("can not select the database $db");
return TRUE;
}
public function ShowCategory()
{
$sql = "SELECT subject.subject_id,subject.description,COUNT(media.subject_id) as media_count\n"
. "from subject LEFT OUTER JOIN media ON subject.subject_id = media.subject_id \n"
. "WHERE verified = 1\n"
. "GROUP BY subject.subject_id,subject.description ORDER BY subject.description ";
$res = mysql_query($sql,$this->conn);
$category = '<option value="%">Subject</option>';
while($row = mysql_fetch_array($res))
{
$category .= '<option value="' . $row['subject_id'] . '">' . $row['description']. '...('.$row['media_count'].')</option>';
}
return $category;
}
public function ShowType()
{
$sql = "SELECT section.section_id,section.description,section.subject_id,COUNT(media.section_id) as media_count
FROM section LEFT OUTER JOIN media ON section.section_id = media.section_id
AND section.subject_id = media.subject_id
WHERE section.subject_id={$_POST['id']} AND verified = 1
GROUP BY section.section_id,section.description";
$res = mysql_query($sql,$this->conn);
$type = '<option value="%">choose...';
while($row = mysql_fetch_array($res))
{
$type .= '<option value="' . $row['section_id'] . '">' . $row['description']. '...('.$row['media_count'].') </option>';
}
return $type;
}
public function ShowPrinciple()
{
$sql = "SELECT principle.principle_id,principle.description,principle.section_id,COUNT(media.principle_id) as media_count
FROM principle
LEFT OUTER JOIN media ON principle.principle_id = media.principle_id
AND principle.section_id = media.section_id
WHERE principle.section_id={$_POST['id']} AND verified = 1
GROUP BY principle.principle_id,principle.description";
$res = mysql_query($sql,$this->conn);
$principle = '<option value="%">choose...</option>';
while($row = mysql_fetch_array($res))
{
$principle .= '<option value="' . $row['principle_id'] . '">' . $row['description']. '...('.$row['media_count'].') </option>';
}
return $principle;
}
public function GetResults()
{
//$vars = $_POST["comboboxselections"]; // this gets comboboxselections from index.php
list($subjectID, $sectionID, $principleID) = explode('#', $_POST["comboboxselections"]);
$box = ""; // placeholder for the html results to be returned to
$sql = "SELECT media_id,title,blurb
FROM media
WHERE subject_id = $subjectID AND section_id = $sectionID AND principle_id= $principleID AND verified = 1"; // sql query
$hasprintedrecords = false; // capture records if there are no records printed to screen
$res = mysql_query($sql,$this->conn); // connection to database and also getting the results from query
while($row = mysql_fetch_array($res)) // the loop while there are results within the array run the function
{
$hasprintedrecords = true;// if there are records this equals true if not equals false
$box .= '
<div style="margin-top:5px;height:120px;padding:0px;"id="Video">
<div style="width:185px;height:105px;float:left;" id="VideoImage">
<img style="width:185px;"class="partimg1" src="images/thumbnails/'.$row['media_id'].'.png" />
</div>
<div style="float:right;padding-left:5px;width:72%;font-size:15px;padding-top:0px;font:verdana,sans-serif;" id="text">
<div style="color:#0099CC;font-weight:bold;" id="Title">'.$row['title'].'</div>
<a style="color:#000000;text-decoration:none;padding:0px;margin:0px;font-size:12px;" href="http://www.thomasdudley.co.uk/" target="_blank">By Thomas Dudley</a>
<div style="font-size:13.4px;"id="Blurb">'.$row['blurb'].'</div>
<div id="Downloads">
<a href="http://thor/classroom/Downloads/'.$row['media_id'].''.$row['title'].'.exe" target="_blank">
<img style="width:100px; margin-left:-10px;margin-top:10px;" src="images/download.jpg">
</a>
</div>
</div>
</div>'; // if results are available then display to screen
}
if ( $hasprintedrecords == false) // if there are no results then function below is run
{
$box .='<div id=\"video\" style=\" border-style:solid; border-color:#000000; border-width:1px;\"> <div style="border-style:dashed; border-color:#f90;" id="text"> no media found for this selection.</div></div>'; // returns html message to screen
}
return $box; // returns results to the screen
}
public function ShowJobRole() {
$sql = "SELECT jobrole_id,description
FROM jobrole ";
$res = mysql_query($sql,$this->conn);
$jobrole = '<option value="%">Job role</option>';
while($row = mysql_fetch_array($res))
{
$jobrole .= '<option value="' . $row['jobrole_id'] . '">' . $row['description'] . '...('.$row['media_count'].'</option>';
}
return $jobrole;
}
public function ShowCareer() {
$sql = "SELECT career_id,description FROM career WHERE jobrole_id={$_POST['id']}";
$res = mysql_query($sql,$this->conn);
$career = '<option value="%">Career</option>';
while($row = mysql_fetch_array($res))
{
$career .= '<option value="' . $row['career_id'] . '">' . $row['description'] . '</option>';
}
return $career;
}
public function get_job () {
//$vars1 = $_POST["comboboxselections1"]; // this gets comboboxselections from index.php
list($jobroleID, $careerID) = explode('#', $_POST["comboboxselections1"]);
$res = mysql_query($sql,$this->conn);
$box = ""; // placeholder for the html results to be returned to
$sql = "SELECT title,blurb,m.media_id
FROM media_career_crossref mcc
INNER JOIN media m ON m.media_id = mcc.media_id
WHERE mcc.jobrole_id = $jobroleID AND mcc.career_id = $careerID";
$hasprintedrecords = false; // capture records if there are no records printed to screen
$res = mysql_query($sql,$this->conn); // connection to database and also getting the results from query
while($row = mysql_fetch_array($res)) // the loop while there are results within the array run the function
{
$hasprintedrecords = true;// if there are records this equals true if not equals false
$box .= '
<div style="margin-top:5px;height:120px;padding:0px;"id="Video">
<div style="width:185px;height:105px;float:left;" id="VideoImage">
<img style="width:185px;"class="partimg1" src="images/thumbnails/'.$row['media_id'].'.png" />
</div>
<div style="float:right;padding-left:5px;width:72%;font-size:15px;padding-top:0px;font:verdana,sans-serif;" id="text">
<div style="color:#0099CC;font-weight:bold;" id="Title">'.$row['title'].'</div>
<a style="color:#000000;text-decoration:none;padding:0px;margin:0px;font-size:12px;" href="http://www.thomasdudley.co.uk/" target="_blank">By Thomas Dudley</a>
<div style="font-size:13.4px;"id="Blurb">'.$row['blurb'].'</div>
<div id="Downloads">
<a style="width:100px; margin-left:-10px;margin-top:10px;" href="http://thor/classroom/Downloads/'.$row['media_id'].''.$row['title'].'.exe" target="_blank">
<img style="width:110px;" src="images/download.jpg">
</a>
</div>
</div>
</div>'; // if results are available then display to screen
}
if ( $hasprintedrecords == false) // if there are no results then function below is run
{
$box .='<div id=\"video\" style=\" border-style:solid; border-color:#000000; border-width:1px;\"> <div style="border-style:dashed; border-color:#f90;" id="text"> no media found for this selection.</div></div>'; // returns html message to screen
}
return $box; // returns results to the screen
}
public function Unverified()
{
$unverified = "";
$sql = "SELECT *
FROM media
WHERE verified = 0 "; // sql query
$box = "";
$hasprintedrecords = false; // capture records if there are no records printed to screen
$res = mysql_query($sql,$this->conn); // connection to database and also getting the results from query
while($row = mysql_fetch_array($res)) // the loop while there are results within the array run the function
{
$hasprintedrecords = true;// if there are records this equals true if not equals false
$unverified .= '
<div style="margin-top:5px;height:120px;padding:0px;"id="Video">
<div style="width:185px;height:105px;float:left;" id="VideoImage">
<img style="width:185px;"class="partimg1" src="images/thumbnails/'.$row['media_id'].'.png" />
</div>
<div style="float:right;padding-left:5px;width:72%;font-size:12px;padding-top:0px;font:verdana,sans-serif;" id="text">
<div style="color:#0099CC;font-weight:bold;" id="Title">'.$row['title'].'</div>
<a style="color:#000000;text-decoration:none;padding:0px;margin:0px;font-size:12px;" href="http://www.thomasdudley.co.uk/" target="_blank">By Thomas Dudley</a>
<div style="font-size:13.4px;"id="Blurb">'.$row['blurb'].'</div>
<div id="Downloads">
<a id="Download" href="http://thor/classroom/Downloads/'.$row['media_id'].''.$row['title'].'.exe" target="_blank">Download</a>
</div>
</div>
</div>'; // if results are available then display to screen
}
if ( $hasprintedrecords == false) // if there are no results then function below is run
{
$unverified .='<div id=\"video\" style=\" border-style:solid; border-color:#000000; border-width:1px;\"> <div style="border-style:dashed; border-color:#f90;" id="text"> no media found for this selection.</div></div>'; // returns html message to screen
}
return $unverified; // returns results to the screen
}
public function addNewMediaRecord($Subject, $Section, $Principle, $Title, $Blurb, $Uniq_id) {
$sql = "INSERT INTO media (media_id, subject_id, section_id, principle_id, title, blurb, verified, media_uniqid)
VALUES ('NULL', '".$Subject."', '".$Section."', '".$Principle."', '".$Title."', '".$Blurb."', '0', '".$Uniq_id."')";
$this->addMediaCrossRef($Job, $Career, $Uniq_id); // You don't have this vars initilized in the current method?
mysql_query($sql, $this->conn);
(return mysql_affected_rows($this->conn) > 0);
}
public function addMediaCrossRef($Job, $Career, $Uniq_id) {
$sql = "INSERT INTO media_career_crossref (media_id, jobrole_id, career_id, verified, media_uniqid)
VALUES (NULL, '".$Job."', '".$Career."', '0', '".$Uniq_id."')";
mysql_query($sql, $this->conn);
(return mysql_affected_rows($this->conn) > 0);
}
}
$opt = new SelectList();
?>
above is the full code that I have currently got for this web page the latest functions are the last on the page.
this is how the functions are being called from a different page
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile))
{
echo "File is valid, and was successfully uploaded.\n";
include "select.class.php";
/*$opt->addNewMediaCrossRef($Job, $Career, $Uniq_id);*\ /* me trying to call both functions at once this didnt work either*/
$opt->addNewRecord($Subject, $Section, $Principle, $Title, $Blurb, $Uniq_id);
}
any help would be much appreciated

The other answer might have stated that you can use MySQLi's multiquery option, and also as I commented you can use *_query() once for the first statement and second time for the second statement. However, you are braking the single responsibility principle of the method. If you want to chain to actions within one, separate them in different methods and call inwithin.
public function addNewMediaRecord($Subject, $Section, $Principle, $Title, $Blurb, $Uniq_id) {
$sql = "INSERT INTO media (media_id, subject_id, section_id, principle_id, title, blurb, verified, media_uniqid)
VALUES ('NULL', '".$Subject."', '".$Section."', '".$Principle."', '".$Title."', '".$Blurb."', '0', '".$Uniq_id."')";
$this->addMediaCrossRef($Job, $Career, $Uniq_id); // You don't have this vars initilized in the current method?
return yourQueryFunction($sql, $this->conn);
}
public function addMediaCrossRef($Job, $Career, $Uniq_id) {
$sql = "INSERT INTO media_career_crossref (media_id, jobrole_id, career_id, verified, media_uniqid)
VALUES (NULL, '".$Job."', '".$Career."', '0', '".$Uniq_id."')";
return yourQueryFunction($sql, $this->conn);
}
And normally methods do not return the query() return value, especially when they are insert/update
I would prefer:
public function addNewMediaRecord($all_the_params) {
$sql = ".....";
yourQueryFunction($sql);
$this->chainedMethod($params);
return yourFunctionforAFFECTED_ROWS() > 0;
}
So it will return boolean if affected rows are more than zero (successful insert).
Also you'd better wrap the database functions in order to have easier switch between libraries, when you need to.
E.g.:
class Database {
private $_host;
private $_user;
private $_pass;
private $_db;
private $_conn;
public function __construct($host, $user, $pass, $db) {
$this->_host = $host;
$this->_user = $user;
$this->_pass = $pass;
$this->_db = $db;
$this->connect();
}
private function connect() {
$this->_conn = mysqli_connect($this->_host, $this->_user, $this->_pass, $this->_db)
or die(mysqli_error($this->_conn));
}
public function query($query) {
return mysqli_query($this->_conn, $query);
}
public function affectedRows() {
return mysqli_affected_rows($this->_conn);
}
class TheClassWhereYourMethodsYouHaveShownAre {
protected $_db;
public function __construct() {
$this->_db = new Database('host', 'user', 'pass', 'db');
}
public function addNewMediaRecord($Subject, $Section, $Principle, $Title, $Blurb, $Uniq_id) {
$sql = "INSERT INTO media (media_id, subject_id, section_id, principle_id, title, blurb, verified, media_uniqid)
VALUES ('NULL', '".$Subject."', '".$Section."', '".$Principle."', '".$Title."', '".$Blurb."', '0', '".$Uniq_id."')";
$this->addMediaCrossRef($Job, $Career, $Uniq_id); // You don't have this vars initilized in the current method?
$this->_db->query($sql);
return $this->_db->affectedRows > 0;
}

mysql_query() sends a unique query
You can use mysqli_multi_query function but with PHP mysqli extension.
but, if you are dead set to use mysql_query then try this-
<?php
$str="query1;query2;"; //
$query = explode(';',$str);
// Run the queries
foreach($query as $index => $sql)
{
$result = mysql_query($sql);
// Perform an additional operations here
}
?>

Related

OOP PHP - proper way to pass $_POST values from form to database_write function

I have trouble understanding OOP...
Lets say I wanted to create a page that adds a new user to a database and wanted to work with classes.
For that scenario i'd create a form with a function.
There are forms for each CRUD functionality - renderHTMLFormAddUser() :
...
<form action="" method="POST" >;
<label>Shopname*</label><br>;
<input type="text" name="shopname" class="input_wide" required><br>;
<label>Username*</label><br>;
<input type="text" name="username" class="input_wide" required><br>;
<input type="submit" value="add" name="submit" >
...
a DataBaseConnector class:
class DataBaseConnector
{
protected $con;
public function __construct()
{
$this->con=mysqli_connect('mariaDB','root','123456','produktmuster');
}
public function getConnection()
{
return $this->con;
}
public function __destruct()
{
$this->con->close();
}
}
and a QueryDatabase class that requires the DataBaseConnector connection as a transfer parameter in its constructor:
class QueryDatabase
{
private $con;
public function __construct(DataBaseConnector $con)
{
$this->con = $con;
}
public function addUser($shopname,$username)
{
$sql = "INSERT INTO `brandportal_manager`( `Shopname`, `Username`) VALUES ($shopname,$username)";
$result = mysqli_query($this->con->connect(), $sql);
return $result;
}
To get the $_POST values in the QueryDatabase add User function, i'd need to declare variables like so:
$shopname= $_POST['shopname'];
$username= $_POST['username'];
But is there a better way to do so?
Like maybe renderHTMLFormAddUser()->'shopname'.
Im just trying to understand what is the cleanest way to code in this scenario.
Because using a function to render the forms the adduser.php would look something like this:
$createuserform=new Forms();
$createuserform->renderHTMLFormAddUser();
$shopname= $_POST['shopname']; // this is what confuses me, you'd have to look into the
$username= $_POST['username']; // renderHTMLFormAddUser() function to see the code
$db = new DataBaseConnector();
$query= new QueryDatabase();
$query->addUser($shopname,$username)
Should I just create an own page that posts the form to a page that then uses the data?
In the beginning i simply used no transfer parameters with the addUser function, and it started with declaring the $_POSTs:
$shopname= $_POST['shopname'];
$username= $_POST['username'];
$sql = "INSERT INTO `brandportal_manager`( `Shopname`, `Username`) VALUES ($shopname,$username)";
...
But I was told it was unsafe to do so - in that regard, I sanitize my data but for the sake of easier example i stripped away all the unnecessary code.
Should I take a completely different approach, just would like to know the cleanest way to add form input data into a database.
Well, there are many approaches to do this. You can also do my OOPs approach:
Make a define.php to set the constant variables & database connection variables:
define.php
define("DB_HOSTNAME", "localhost");
define("DB_USERNAME", "your_username");
define("DB_PASSWORD", "your_password");
define("DB_NAME", "your_databasename");
define("custom_variable", "custom_variable_value");
define("baseurl", "https://localhost/myproject/");
Then, make dbase.php, to create a dynamic SQL function:
You don't need to change this file. You just need to call this class. This file work as the core file of the system.
Dbase.php
<?php session_start();
date_default_timezone_set("Asia/Karachi");
require_once("define.php");
Class Dbase
{
private $Host = DB_HOSTNAME;
private $UserName = DB_USERNAME;
private $Password = DB_PASSWORD;
private $DBname = DB_NAME;
private $connDb = false;
public $LastQuery = null;
public $AffectedRows = 0;
public $InsertKey = array();
public $InsertValues = array();
public $UpdateSets = array();
public $id;
public function __construct()
{
$this->connect();
}
protected function connect()
{
$this->connDb = #mysqli_connect($this->Host, $this->UserName, $this->Password);
if (!($this->connDb)) {
die('Database Connection Failed.<br>' . mysql_error($this->connDb));
} else {
$Select = mysqli_select_db($this->connDb,$this->DBname);
if (!$Select) {
die('Database Selection Failed.<br>' . mysql_error($this->connDb));
}
}
mysqli_set_charset($this->connDb,'utf8');
}
public function close()
{
if (!mysqli_close($this->connDb)) {
die('Closing Connection Failed.<br>');
}
}
public function escape($value)
{
if (function_exists('mysql_real_escape_string')) {
if (get_magic_quotes_gpc()) {
$value = stripslashes($value);
}
$value = mysql_real_escape_string($value);
} else {
if (!get_magic_quotes_gpc()) {
$value = addcslashes($value);
}
}
return $value;
}
public function query($sql)
{
$query = $sql;
$result = mysqli_query($this->connDb,$sql);
// $this->displayQuery($result);
return $result;
}
public function displayQuery($result)
{
if (!$result) {
$output = 'Database Query Failed' . mysql_error($this->connDb) . '<br>';
$output .= 'Last Query was' . $this->LastQuery;
die($output);
} else {
$this->AffectedRows = mysqli_affected_rows($this->connDb);
}
}
public function fetchAll($sql)
{
$result = $this->query($sql);
$output = array();
while ($row = mysqli_fetch_assoc($result)) {
$output[] = $row;
}
// mysql_free_result($result);
return $output;
}
public function fetchOne($sql)
{
$output = $this->fetchAll($sql);
return $output;
// return array_shift($output);
}
public function prepareInsert($array = null)
{
if (!empty($array)) {
foreach ($array as $key => $value) {
$this->InsertKey[] = $key;
$this->InsertValues[] = $this->escape($value);
}
}
}
public function insert($table = null)
{
if (!empty($table) && !empty($this->InsertKey) && !empty($this->InsertValues)) {
$sql = "insert into '{$table}' ('";
$sql .= implode("','", $this->InsertKey);
$sql .= "') values ('";
$sql .= implode("','", $this->InsertValues);
$sql .= "')";
if ($this->query($sql)) {
$this->id = $this->lastId();
return true;
}
return false;
} else {
return false;
}
}
public function prepareUpdate($array = null)
{
if (!empty($array)) {
foreach ($array as $key => $value) {
$this->UpdateSets[] = "`{$key}` = '" . $this->escape($value) . "'";
}
}
}
public function update($table = null, $id = null, $whereId)
{
if (!empty($table) && !empty($id) && !empty($this->UpdateSets)) {
$sql = "update `{$table}` set";
$sql .= implode(",", $this->UpdateSets);
// $sql.="where id='".$this->escape($id)."'";
$sql .= "where '" . $whereId . "'='" . $this->escape($id) . "'";
return $this->query($sql);
} else {
return false;
}
}
public function lastId()
{
return mysqli_insert_id($this->connDb);
}
public function TotalNumberOfRecords($sql)
{
$result = $this->query($sql);
$output = mysqli_num_rows($result);
return $output;
}
public function GetServerInfo()
{
return mysqli_get_server_info();
}
}
Create a Query.php file. This file work as your model file as in MVC.
Query.php
<?php include "Dbase.php";
Class Query extends Dbase
{
public function __construct()
{
$this->connect();
date_default_timezone_set("Asia/Karachi");
}
public function getData($idlevelOne)
{
$sql = "SELECT * FROM `table` where level_one_id=$idlevelOne ORDER BY `sorting` ASC";
$result = $this->fetchAll($sql);
return $result;
}
/*For Insert & Edit, use this fucntion*/
public function editMember($email, $phone, $address, $city, $country, $zipcode, $id)
{
$sql = "UPDATE `members` SET `email` = '" . $email . "', `phone` = '" . $phone . "', `address` = '" . $address . "'
, `city` = '" . $city . "', `country` = '" . $country . "', `zip_code` = '" . $zipcode . "'
WHERE `id` = '$id'";
$result = $this->query($sql);
return $result;
}
}
Now, you just need to call the Query class in your PHP files to get the data.
<?php
include "Query.php";
$ObjQuery = new Query();
$ObjQuery->getData(1);

Value of $_GET Superglobal Not Being Passed To Processing Page

Ultimately I am trying to delete an admin by id. I know the id of the admins are making it to the list admins page because I am printing the admin id in the table next to each admin username and seeing the id. But when the delete admin link is clicked, the delete admin page is not receiving the id from the GET superglobal.
Why not?
Thanks,
CM
list_admins.php (contains the delete button at the bottom for deleting an admin)
<?php require_once("../../includes/initialize.php"); ?>
<?php //if (!$session->is_logged_in()) {redirect_to("login.php");} ?>
<?php confirm_logged_in(); ?>
<?php
$admin_set = User::find_all();
$message = "";
?>
<?php $layout_context = "admin"; ?>
<?php include("../layouts/admin_header.php"); ?>
<div id="main">
<div id="navigation">
<br />
« Main menu<br />
</div>
<div id="page">
<?php echo output_message($message); ?>
<h2>Manage Admins</h2>
<table style="border: 1px solid #000; color:#000;">
<tr>
<th style="text-align: left; width: 200px;">Username</th>
<th style="text-align: left; width: 200px;">User Id</th>
<th colspan="2" style="text-align: left;">Actions</th>
</tr>
<?php foreach($admin_set as $admin) : ?>
<tr>
<td><?php echo $admin->username; ?></td>
<td><?php echo $admin->id; ?></td>
<td>Edit</td>
<td>Delete</td>
</tr>
<?php endforeach ?>
</table>
<br />
Add new admin
</div>
</div>
<?php include("../layouts/footer.php"); ?>
delete_admin.php
<?php require_once("../../includes/initialize.php"); ?>
<?php if (!$session->is_logged_in()) { redirect_to("login.php"); } ?>
<?php
//$admin_set = User::find_all();//This works, var_dump shows me the users are
//being returned
//var_dump($admin_set);
$admin = User::find_by_id($_GET['id']);//This returns database query failed.
var_dump($admin);
?>
user.php
<?php
// If it's going to need the database, then it's
// probably smart to require it before we start.
require_once(LIB_PATH.DS.'database.php');
class User extends DatabaseObject {
protected static $table_name="admins";
protected static $db_fields = array('id', 'username', 'password', 'first_name', 'last_name');
public $id;
public $username;
public $password;
public $first_name;
public $last_name;
public function full_name() {
if(isset($this->first_name) && isset($this->last_name)) {
return $this->first_name . " " . $this->last_name;
} else {
return "";
}
}
public static function authenticate($username="", $password="") {
global $database;
$username = $database->escape_value($username);
$password = $database->escape_value($password);
$sql = "SELECT * FROM users ";
$sql .= "WHERE username = '{$username}' ";
$sql .= "AND password = '{$password}' ";
$sql .= "LIMIT 1";
$result_array = self::find_by_sql($sql);
return !empty($result_array) ? array_shift($result_array) : false;
}
// Common Database Methods
public static function find_all() {
return self::find_by_sql("SELECT * FROM ".self::$table_name);
}
public static function find_by_id($id=0) {
$result_array = self::find_by_sql("SELECT * FROM ".self::$table_name." WHERE id={$id} LIMIT 1");
return !empty($result_array) ? array_shift($result_array) : false;
}
public static function find_by_sql($sql="") {
global $database;
$result_set = $database->query($sql);
$object_array = array();
while ($row = $database->fetch_array($result_set)) {
$object_array[] = self::instantiate($row);
}
return $object_array;
}
public static function count_all() {
global $database;
$sql = "SELECT COUNT(*) FROM ".self::$table_name;
$result_set = $database->query($sql);
$row = $database->fetch_array($result_set);
return array_shift($row);
}
private static function instantiate($record) {
// Could check that $record exists and is an array
$object = new self;
// Simple, long-form approach:
// $object->id = $record['id'];
// $object->username = $record['username'];
// $object->password = $record['password'];
// $object->first_name = $record['first_name'];
// $object->last_name = $record['last_name'];
// More dynamic, short-form approach:
foreach($record as $attribute=>$value){
if($object->has_attribute($attribute)) {
$object->$attribute = $value;
}
}
return $object;
}
private function has_attribute($attribute) {
// We don't care about the value, we just want to know if the key exists
// Will return true or false
return array_key_exists($attribute, $this->attributes());
}
protected function attributes() {
// return an array of attribute names and their values
$attributes = array();
foreach(self::$db_fields as $field) {
if(property_exists($this, $field)) {
$attributes[$field] = $this->$field;
}
}
return $attributes;
}
protected function sanitized_attributes() {
global $database;
$clean_attributes = array();
// sanitize the values before submitting
// Note: does not alter the actual value of each attribute
foreach($this->attributes() as $key => $value){
$clean_attributes[$key] = $database->escape_value($value);
}
return $clean_attributes;
}
public function save() {
// A new record won't have an id yet.
return isset($this->id) ? $this->update() : $this->create();
}
public function create() {
global $database;
// Don't forget your SQL syntax and good habits:
// - INSERT INTO table (key, key) VALUES ('value', 'value')
// - single-quotes around all values
// - escape all values to prevent SQL injection
$attributes = $this->sanitized_attributes();
$sql = "INSERT INTO ".self::$table_name." (";
$sql .= join(", ", array_keys($attributes));
$sql .= ") VALUES ('";
$sql .= join("', '", array_values($attributes));
$sql .= "')";
if($database->query($sql)) {
$this->id = $database->insert_id();
return true;
} else {
return false;
}
}
public function update() {
global $database;
// Don't forget your SQL syntax and good habits:
// - UPDATE table SET key='value', key='value' WHERE condition
// - single-quotes around all values
// - escape all values to prevent SQL injection
$attributes = $this->sanitized_attributes();
$attribute_pairs = array();
foreach($attributes as $key => $value) {
$attribute_pairs[] = "{$key}='{$value}'";
}
$sql = "UPDATE ".self::$table_name." SET ";
$sql .= join(", ", $attribute_pairs);
$sql .= " WHERE id=". $database->escape_value($this->id);
$database->query($sql);
return ($database->affected_rows() == 1) ? true : false;
}
public function delete() {
global $database;
// Don't forget your SQL syntax and good habits:
// - DELETE FROM table WHERE condition LIMIT 1
// - escape all values to prevent SQL injection
// - use LIMIT 1
$sql = "DELETE FROM ".self::$table_name;
$sql .= " WHERE id=". $database->escape_value($this->id);
$sql .= " LIMIT 1";
$database->query($sql);
return ($database->affected_rows() == 1) ? true : false;
// NB: After deleting, the instance of User still
// exists, even though the database entry does not.
// This can be useful, as in:
// echo $user->first_name . " was deleted";
// but, for example, we can't call $user->update()
// after calling $user->delete().
}
}
?>
database.php
<?php
require_once(LIB_PATH.DS."config.php");
class MySQLDatabase{
private $connection;
function __construct(){
$this->open_connection();
}
public function open_connection(){
$this->connection = mysqli_connect(DB_SERVER, DB_USER, DB_PASS,DB_NAME);
if(mysqli_connect_errno()) {
die("Database connections failed: " .
mysqli_connect_error() .
" (" . mysqli_connect_errno() . ")"
);
}
}
public function close_connection(){
if(isset($this->connection)){
mysqli_close($this->connection);
unset($this->connection);
}
}
public function query($sql){
$result = mysqli_query($this->connection, $sql);
$this->confirm_query($result);
return $result;
}
private function confirm_query($result_set) {
if (!$result_set) {
die("Database query failed yo.");
}
}
public function escape_value($string) {
$escaped_string = mysqli_real_escape_string($this->connection, $string);
return $escaped_string;
}
//database neutral functions
public function fetch_array($result_set){
return mysqli_fetch_array($result_set);
}
public function num_rows($result_set){
return mysqli_num_rows($result_set);
}
public function insert_id(){
return mysqli_insert_id($this->connection);
}
public function affected_rows(){
return mysqli_affected_rows($this->connection);
}
}//End class MySQLDatabase
$database = new MySQLDatabase();
?>
Simple answer on this one ;)
You have:
<a href="edit_admin.php?id=<?php $admin->id; ?>"> ...
<a href="delete_admin.php?id=<?php $admin->id; ?>" ...
When it should be:
<a href="edit_admin.php?id=<?php echo $admin->id; ?>">...
<a href="delete_admin.php?id=<?php echo $admin->id; ?>" ...
^^^^

OOP PHP PDO, Page function doesn't work (UserCake)

I'm doing my own little project converting UserCake (latest) to OOP with PDO, i've finalised a lot of features already. But right now i've been stuck for awhile on this Page functionality. So according to the code it's suppose to read the root folder for PHP files and add them to DB table (uc_pages) if they don't already exist. And if there's pages in the DB that doesn't exist in the root folder to delete those from the db.
I get no errors at all which is kinda interesting... but i'll post the code if anyone would be kind to give me a hand on this one.
Pages.php
<?php
require_once("resources/database.php");
$website_pages = new dbPages($db);
// set number of records per page
$records_per_page = 6;
// calculate for the query LIMIT clause
$from_record_num = ($records_per_page * $page) - $records_per_page;
$website_pages->getPageFiles();
//Retrieve list of pages in root usercake folder
$website_pages->fetchAllPages();
//Retrieve list of pages in pages table
$creations = array();
$deletions = array();
//Check if any pages exist which are not in DB
foreach ($website_pages->getPageFiles() as $web_page){
if(!isset($website_pages->readOne()[$web_page])){
$creations[] = $web_page;
}
}
//Enter new pages in DB if found
if (count($creations) > 0) {
$website_pages->create($creations);
}
if (count($website_pages->fetchAllPages()) > 0){
//Check if DB contains pages that don't exist
foreach ($website_pages->readOne() as $web_page){
if(!isset($website_pages->fetchAllPages()[$web_page['page']])){
$deletions[] = $web_page['id'];
}
}
}
//Delete pages from DB if not found
if (count($deletions) > 0) {
$website_pages->delete($deletions);
}
//Update DB pages
$website_pages->readAll($from_record_num, $records_per_page);
// header settings
$page_url="pages.php?";
$page_title = "UNFINISHED: All pages";
include_once "./resources/header.php";
?>
<div class='container'>
<div class='page-header'>
<h1><?php echo"{$page_title}";?></h1>
</div>
</div>
<div class="jumbotron">
<div class="container">
<?php
// query products
$stmt = $website_pages->readAll($from_record_num, $records_per_page);
$num = $stmt->rowCount();
// display the products if there are any
if($num>0){
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
extract($row);
echo "<div class='col-xs-12 col-md-6'>
<div class='btn-group btn-group-justified' role='group'
aria-label='Justified button group'>
<a href='page.php?id={$id}' class='btn btn-warning' role='button'>
<span class='glyphicon glyphicon-edit'></span> Edit</a>
</div>";
echo "
<div class='panel panel-primary'>
<div class='panel-heading'>
<h3 class='panel-title'>{$page_name}</h3>
</div>
<div class='panel-footer'>";
//Show public/private setting of page
if($private == 0){
echo "This page is Public";
}
else {
echo "This page is Private";
}
echo "</div></div></div>";
}
echo "</div>";
// needed for paging
$total_rows=0;
if($page_url=="pages.php?"){
$total_rows=$website_pages->countAll();
}
// paging buttons
include_once './resources/paging.php';
}
// tell the user there are no products
else{
echo "<div class=\"alert alert-danger alert-dismissable\">";
echo "<button type=\"button\" class=\"close\" data-
dismiss=\"alert\" aria-hidden=\"true\">×</button>";
echo "No pages found.";
echo "</div>";
}
echo "</div>";
?>
</div>
</div>
<?php require("./resources/footer.php")?>
Database.php
<?php
class Database{
// specify your own database credentials
private $host = "###########";
private $db_name = "website";
private $username = "###########";
private $password = "###########";
public $conn;
// get the database connection
public function getConnection(){
$this->conn = null;
try{
$this->conn = new PDO(
"mysql:host=" . $this->host . ";dbname=" . $this->db_name,
$this->username, $this->password);
}catch(PDOException $exception){
echo "Connection error: " . $exception->getMessage();
}
return $this->conn;
}
}
// instantiate database and product object
$database = new Database();
$db = $database->getConnection();
require_once './resources/functions.php';
$website = new Configuration($db);
$website->readConfig();
?>
The part from functions.php that is struggling
class dbPages {
// database connection and table names
private $conn;
private $table_name = "uc_pages";
private $table_name2 = "uc_permission_page_matches";
// object properties
public $id;
public $page_id;
public $permission_id;
public $page_name;
public $private;
public $pages;
public $row;
public function __construct($db){
$this->conn = $db;
}
//Retrieve a list of all .php files in root files folder
function getPageFiles() {
$directory = "";
$pages = glob($directory . "*.php");
//print each file name
foreach ($pages as $web_page){
$row[$web_page] = $web_page;
}
return $row;
}
//Fetch information on all pages
function fetchAllPages() {
$query = "SELECT
id,
page_name,
private
FROM
" . $this->table_name . " ";
// prepare query statement
$stmt = $this->conn->prepare( $query );
$stmt->execute();
while ($stmt->fetch(PDO::FETCH_ASSOC)){
$row[$web_page] = array(
'id' => $id, 'page_name' => $page_name, 'private' => $private);
}
if (isset($row)){
return ($row);
}
}
// read products
function readAll($from_record_num, $records_per_page){
// select query
$query = "SELECT
id,
page_name,
private
FROM
" . $this->table_name . "
ORDER BY
page_name ASC
LIMIT
?, ?";
// prepare query statement
$stmt = $this->conn->prepare( $query );
// bind variable values
$stmt->bindParam(1, $from_record_num, PDO::PARAM_INT);
$stmt->bindParam(2, $records_per_page, PDO::PARAM_INT);
// execute query
$stmt->execute();
// return values from database
return $stmt;
}
// used for paging products
public function countAll(){
$query = "SELECT COUNT(*) as total_rows
FROM " . $this->table_name . "";
$stmt = $this->conn->prepare( $query );
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
return $row['total_rows'];
}
// used when filling up the update product form
function readOne(){
$query = "SELECT
id,
page_name,
private
FROM
" . $this->table_name . "
WHERE
page_name = ?
LIMIT
0,1";
$stmt = $this->conn->prepare( $query );
$stmt->bindParam(1, $this->id);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$this->id = $row['id'];
$this->page_name = $row['page_name'];
$this->private = $row['private'];
}
// create product
function create($pages){
//write query
$query = "INSERT INTO
" . $this->table_name . "
SET
id = ?,
page_name = ?,
private = ?";
$stmt = $this->conn->prepare($query);
$stmt->bindParam(1, $this->id);
$stmt->bindParam(2, $this->page_name);
$stmt->bindParam(3, $this->private);
foreach($pages as $page_name){
if($stmt->execute()){
return true;
}else{
return false;
}
}
}
// delete the product
function delete($pages){
$query = "DELETE FROM " . $this->table_name . " WHERE id = ?";
$stmt = $this->conn->prepare($query);
$stmt->bindParam(1, $this->id);
foreach($pages as $id){
if($result = $stmt->execute()){
return true;
}else{
return false;
}
}
$query2 = "DELETE FROM " . $this->table_name2 . "
WHERE page_id = ?";
$stmt2 = $this->conn->prepare($query);
$stmt2->bindParam(1, $this->page_id);
foreach($pages as $id){
if($result = $stmt2->execute()){
return true;
}else{
return false;
}
}
}
}

PHP Class not Returning Result

I am working on an Item Inventory Web App. I want users should be able to add and assign item to a user. Each user is entitled to one item at a time. If, say, user a already has an item assigned and you want to add more item, the system should lodge an error that will tell you
to withdraw the item be issuing a new one but the errors are not getting lodged in the error[] array even though it shows that the array is not empty. It only echo out the serial number a = 1 and a++ but the text is not there.
class.inc.php
class Summary {
public $result;
public $conn;
public $SQ;
public $q;
public $updateDB;
public $checkDB;
public $returned_result;
public $a;
public $data;
public $col;
public function __construct(){
$this->conn = new PDO('mysql:host=localhost; dbname=dB', 'root', '');
$this->conn->setAttribute(PDO:: ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
public function updateDB($coloumn, $data, $id){
$SQ = "UPDATE mytable SET $coloumn = ? WHERE staffID = ?";
$q = $this->conn->prepare($SQ) or die("ERROR: " . implode(":", $this->conn->errorInfo()));
$q->bindParam(1, $data);
$q->bindParam(2, $id);
if ($q->execute()){
$success = 'Record updated successfully';
};
return $success;
}
public function checkDB($col, $data){
$status = 'Active';
$SQ = "SELECT surname FROM mytable WHERE $col = ? AND status = ?";
$q = $this->conn->prepare($SQ) or die("ERROR: " . implode(":", $this->conn->errorInfo()));
$q->bindParam(1, $data);
$q->bindParam(2, $status);
$q->execute();
if($result = $q->fetch(PDO::FETCH_BOTH)){
$a = $result[0];
if ($a == ''){
$this->returned_result = 'N';
}
else {
$this->returned_result = "This item (". $data . ") is in use by ". $a . ". Please widthraw the item";
}
}
return $this->returned_result;
}
}
index.php:
include('class.inc.php');
$summary = new Summary;
$error = array();
if(isset($_POST['saveRecord']) ) {
$system_name = strtoupper ( $_POST['system_name'] );
$result =$summary->checkDB('systemName', $system_name); //check if the item is in use
if ( $result == 'N' ){
$summary->updateDB('systemName', $system_name, $id);
$update = $summary->updateDB;
}
else $error[] = $result;
$system_serial_number = strtoupper ( $_POST['system_serial_number'] );
$result =$summary->checkDB('CPUSerial', $system_serial_number); //check if the item is in use
if ( $result == 'N' ){
$summary->updateDB('CPUSerial', $system_serial_number, $id);
$update = $summary->updateDB;
}
else $error[] = $result;
}
if(isset($_POST['saveRecord']) && !empty( $error ) ) {
echo "<div class = 'text-error'>";
$a = 1;
foreach ($error as $err){
echo '<p>' . $a . '. ' .$err . '</p>';
$a++;
}
echo "</div>";
}
Any help will be greatly appreciated. And what am I doing wrong with regards to OOP way of programming?

Why do I get a SQL error when preparing a statement in mysqli?

I have the following query:
INSERT INTO ipi_messages (Message_userID, Message_fromName, Message_fromEmail, Message_subject, Message_body) VALUES(0, 'hope', 'thisworks#gmail.com', 'i hope', 'this works')
And I get the following MySQL error:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '0' at line 1
Here's my table schema:
Here is my main PHP code:
<?php
require 'lib/class.Database.php';
require 'lib/class.Messages.php';
$messageDatabase = new Database('ipi2');
$messageDatabase->newDatabaseUsers([
['Query','ipi_query','k2QvHmtxGhVN'],
['admin','ipi_admin','r0HHRsQ76kS2']
]);
$messageDatabase->makeConnection('admin');
var_dump($_POST);
if(array_key_exists('sendMessage', $_POST)){
// $query = "INSERT INTO ipi_messages (Message_userID, Message_fromName, Message_fromEmail, Message_subject, Message_body) VALUES(?,?,?,?,?)";
// $result = $messageDatabase->query($query, $_POST['to'], $_POST['fromName'], $_POST['fromEmail'], $_POST['subject'], $_POST['message']);
$messages = new Messages($messageDatabase);
$messages->postMessage([
'Message_userID' => (int)$_POST['to'],
'Message_fromName' => $_POST['fromName'],
'Message_fromEmail' => $_POST['fromEmail'],
'Message_subject' => $_POST['subject'],
'Message_body' => $_POST['message']
]);
}
if(array_key_exists('getMessages', $_POST)){
$query_get = "SELECT * FROM ipi_messages WHERE Message_userID = ?";
$result_get = $messageDatabase->query($query_get, $_POST['user']);
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Messages</title>
<style type="text/css">h5, h6{margin: 0;padding: 0;}</style>
</head>
<body>
<h3>Send Message</h3>
<form name="sendMessage" method="post" action="">
<h5>To:</h5>
<select name="to">
<option value=""></option>
<option value="0">Fillip Peyton</option>
<option value="1">Fillswitch</option>
</select>
<br/>
<h5>Name:</h5>
<input type="text" name="fromName">
<h5>Email:</h5>
<input type="text" name="fromEmail">
<h5>Subject:</h5>
<input type="text" name="subject">
<h5>Message:</h5>
<textarea name="message"></textarea>
<br/>
<input type="submit" name="sendMessage" value="Send">
</form>
<h3>Your Messages:</h3>
<form name="getMessages" method="post" action="">
<select name="user">
<option value=""></option>
<option value="0">Fillip Peyton</option>
<option value="1">Fillswitch</option>
</select>
<input type="submit" name="getMessages" value="Get Messages">
<?php
if (isset($result_get)) {
foreach ($result_get as $result) {
?>
<p>
<b><?php echo $result['Message_fromName']; ?></b><br/>
<?php echo $result['Message_fromEmail']; ?><br/>
<i><?php echo $result['Message_subject']; ?></i><br/>
<?php echo $result['Message_body']; ?>
</p><hr>
<?php
}
}
?>
</form>
</body>
</html>
class.Messages.php:
<?php
require_once 'lib/classFunctions.php';
class Messages
{
protected $database;
protected $userID = -1;
public function __construct(Database $messageDatabase) {
$this->database = $messageDatabase;
}
public function getMessages($userID = null){
}
public function postMessage(Array $columnsValues){
// $query = "INSERT INTO ipi_messages (Message_userID, Message_fromName, Message_fromEmail, Message_subject, Message_body) VALUES(?,?,?,?,?)";
$columns = '';
$values = '';
$queryParams = array();
foreach ($columnsValues as $column => $value) {
$columns .= "$column, ";
$values .= is_int($value) ? "$value, " : "'$value', ";
$queryParams[] = $value;
}
$columns = substr($columns, 0, strlen($columns) - 2);
$values = substr($values, 0, strlen($values) - 2);
$query = "INSERT INTO ipi_messages ($columns) VALUES($values)";
// array_unshift($queryParams, $query);
// $result = $messageDatabase->query($query, $_POST['to'], $_POST['fromName'], $_POST['fromEmail'], $_POST['subject'], $_POST['message']);
echo $query . '<br/>';
return $result = call_user_func_array(array($this->database,'query'), refValues($queryParams));
}
public function deleteMessage(){}
}
class.Database.php:
<?php
require_once 'lib/classFunctions.php';
class Database
{
protected $DATABASE = 'database';
protected $SERVER = 'localhost';
protected $DATABASEUSERS;
protected $CONNECTION;
public function __construct($database, $server = 'localhost'){
$this->DATABASE = $database;
$this->SERVER = $server;
}
public function makeConnection($userType){
$user = $this->DATABASEUSERS[strtolower($userType)];
$this->CONNECTION = new mysqli($this->SERVER, $user->getUsername(), $user->getPassword(), $this->DATABASE) or die('Cannot make connection to database...');
}
public function escapeSpecialChars($string){
return $this->CONNECTION->real_escape_string($string);
}
public function newDatabaseUser($userType, $username, $password){
$userType = strtolower($userType);
$this->DATABASEUSERS[$userType] = new DatabaseUser($userType, $username, $password);
}
public function newDatabaseUsers($usersCollection){
foreach ($usersCollection as $user) {
$userType = strtolower($user[0]);
$username = $user[1];
$password = $user[2];
$this->DATABASEUSERS[$userType] = new DatabaseUser($userType, $username, $password);
}
}
public function closeConnection(){
if($this->CONNECTION)
$this->CONNECTION->close();
else
throw new Exception("No connection available.", 1);
}
public function query($query, $vars = null){
$stmt = $this->CONNECTION->stmt_init();
$args = func_get_args();
if($stmt->prepare($query)){
if($vars != null){
$queryParams = array();
$queryTypes = '';
$argsCount = count($args);
for( $i = 1 ; $i < $argsCount ; $i++ ){
$var = $args[$i];
$varType = gettype($var);
switch ($varType) {
case 'string':
$queryTypes .= 's';
break;
case 'integer':
$queryTypes .= 'i';
break;
case 'double':
$queryTypes .= 'd';
break;
case 'blob':
$queryTypes .= 'b';
break;
default:
throw new Exception("Could not bind parameter of type: " . $varType, 1);
break;
}
}
$queryParams[] = $queryTypes;
for( $i = 1 ; $i < $argsCount ; $i++ )
$queryParams[] = $args[$i];
// $stmt->bind_param($queryParams);
call_user_func_array(array($stmt,'bind_param'), refValues($queryParams));
}
$isExecuted = $stmt->execute();
if($isExecuted)
return $result = $stmt->get_result();
else
die("Could not execute query($query):" . $this->CONNECTION->error);
}else{
die("Could not prepare statement: " . $this->CONNECTION->error);
}
$stmt->reset();
}
}
class DatabaseUser
{
protected $USERTYPE = 'query';
protected $USERNAME = 'username';
protected $PASSWORD = 'password';
public function __construct($userType, $username, $password) {
$this->USERTYPE = $userType;
$this->USERNAME = $username;
$this->PASSWORD = $password;
}
public function getUserType(){ return $this->USERTYPE; }
public function getUsername(){ return $this->USERNAME; }
public function getPassword(){ return $this->PASSWORD; }
}
classFunctions.php:
<?php
function refValues($arr){
if (strnatcmp(phpversion(),'5.3') >= 0) //Reference is required for PHP 5.3+
{
$refs = array();
foreach($arr as $key => $value)
$refs[$key] = &$arr[$key];
return $refs;
}
return $arr;
}
EDIT: I have added the PHP classes and scripts I am using along with updated my SQL query to make the 0 an int instead of a string.
Why am I getting a SQL error when I prepare my mysqli statement? I tried taking just the SQL query and running it on the database, and the row inserted just fine.
The error is not on the cited part, but before it. So, despite of many comments, there is nothing wrong with '0' itself.
There is no error visible at glance - so, you have to debug your code.
first of all you have to make sure that cited query is the same query with error. you have to always put file name and line number along with error message. To do this, instead of usual useless die($mysqli->error) it have to be trigger_error($myqli->error."[$sql]")
it would be also a good idea to split the query into multiple lines to make error message more informative.
I finally figured out what I was doing wrong. I was getting that error because I was placing the actual values into the VALUES() portion of my sql. This way, when my bind_param method was trying to bind values, it didn't have the ? markers to bind to, rather, it saw the actual values.
My new class.Messages.php looks like:
<?php
require_once 'lib/classFunctions.php';
class Messages
{
protected $database;
protected $userID = -1;
public function __construct(Database $messageDatabase) {
$this->database = $messageDatabase;
}
public function getMessages($userID = null){
}
public function postMessage(Array $columnsValues){
$columns = '';
$values = '';
$queryParams = array();
foreach ($columnsValues as $column => $value) {
$columns .= "$column, ";
$values .= "?, ";
$queryParams[] = $value;
}
$columns = substr($columns, 0, strlen($columns) - 2);
$values = substr($values, 0, strlen($values) - 2);
$query = "INSERT INTO ipi_messages ($columns) VALUES($values)";
array_unshift($queryParams, $query);
return $result = call_user_func_array(array($this->database,'query'), refValues($queryParams));
}
public function deleteMessage(){}
}
Thanks everyone for your help!
I recreated your schema and inserted two rows using your query, one from the MySQL command line and the other from PhpMyAdmin. Screenshot is here: . Your query seems to be valid so the problem lies elsewhere (probably in your PHP code).
This is not your problem but as others have mentioned, the datatype of Message_userID is INT and you have 0 in quotes which represents a string.

Categories