Related
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);
Warning: mysqli_real_escape_string() expects exactly 2 parameters, 1
given in C:\xampp\htdocs\swift\core\functions\general.php on line 49
Notice: Undefined variable: conn in
C:\xampp\htdocs\swift\core\functions\users.php on line 85
Warning: mysqli_query() expects parameter 1 to be mysqli, null given
in C:\xampp\htdocs\swift\core\functions\users.php on line 85
Fatal error: Uncaught Error: Call to undefined function
mysqli_result() in C:\xampp\htdocs\swift\core\functions\users.php:86
Stack trace: #0 C:\xampp\htdocs\swift\loginact.php(14): f_exists('')
#1 {main} thrown in C:\xampp\htdocs\swift\core\functions\users.php on line 86
I keep on getting those errors but i cant find a way, i already tried everything.. Hopefully someone can help me as I am new to php.
Ive been doing this for almost like a day now and i cannot figure out the answer.
This is the General.php.
<?php
$connect_error = 'Sorry, there was some connectivity issue!';
$conn = mysqli_connect('localhost','root','');
$db = mysqli_select_db($conn, 'swift');
function activation($to, $subject, $body) {
mail($to, $subject, $body, 'From: swift#srikanthnatarajan.com');
}
function recovery_user_pass($to, $subject, $body) {
mail($to, $subject, $body, 'From: swift#srikanthnatarajan.com');
}
function f_protect_page() {
if(f_logged_in() === false) {
header('Location: flogin.php');
exit();
}
}
function user_protect_page() {
if(f_logged_in() === false) {
header('Location: fprotect.php');
exit();
}
}
function use_protect_page() {
if(f_logged_in() === true) {
header('Location: fprotect.php');
exit();
}
}
function f_logged_in_redirect() {
if(f_logged_in() === true) {
header('Location: index.php');
exit();
}
}
function array_sanitize($item) {
$item = htmlentities(strip_tags(mysqli_real_escape_string($item)));
}
function sanitize($data) {
return htmlentities(strip_tags(mysqli_real_escape_string($data)));
}
function output_errors($errors) {
return '<ul><li>' . implode('</li><li>', $errors) . '</li></ul>';
}
?>
this is the USERS.PHP can someone please check this.
<?php
$connect_error = 'Sorry, there was some connectivity issue!';
$conn = mysqli_connect('localhost','root','');
$db = mysqli_select_db($conn, 'swift');
function f_recover($mode, $f_mailid) {
$mode = sanitize($mode);
$f_mailid = sanitize($f_mailid);
$f_data = f_data(f_id_from_email($f_mailid),'f_id','f_fname','f_uname');
if ($mode == 'f_uname') {
recovery_user_pass($f_mailid, 'Recovery: Your username', "Hello " . $f_data['f_fname'] . ",\n\nYour username is: " . $f_data['f_uname'] . "\n\n-Swift Airlines");
}
else if($mode == 'f_password') {
$generated_password = substr(md5(rand(999, 999999)), 0, 8);
f_change_password($f_data['f_id'], $generated_password);
update_f($f_data['f_id'], array('f_passrec' => '1'));
recovery_user_pass($f_mailid, 'Recovery: Your password', "Hello " . $f_data['f_fname'] . ",\n\nYour new password is: " . $generated_password . "\n\n-TOFSIS");
}
}
function f_activate($f_mailid, $f_mailcode) {
$f_mailid = mysqli_real_escape_string($_POST['f_mailid']);
$f_mailcode = mysqli_real_escape_string($_POST['f_mailcode']);
if(mysqli_result(mysqli_query("SELECT COUNT(`f_id`) FROM `flight_users` WHERE `f_mailid` = '$f_mailid' AND `f_mailcode` = '$f_mailcode' AND `f_active` = 0"), 0) == 1) {
mysqli_query("UPDATE `flight_users` SET `f_active` = 1 WHERE `f_mailid` = '$f_mailid' ");
return true;
}
else {
return false;
}
}
function update_f($f_id, $update_data) {
$update = array();
array_walk($update_data, 'array_sanitize');
foreach ($update_data as $field => $data) {
$update[] = '`' . $field . '` = \'' . $data . '\'';
}
mysqli_query("UPDATE `flight_users` SET " . implode(', ',$update) . "WHERE `f_id` = $f_id") or die(mysqli_error($conn));
}
function f_change_password($f_id, $f_password) {
$f_id = (int)$f_id;
$f_password = md5($f_password);
mysqli_query("UPDATE `flight_users` SET `f_password` = '$f_password', `f_passrec` = 0 WHERE `f_id` = $f_id");
}
function register_f($register_data) {
array_walk($register_data, 'array_sanitize');
$register_data['f_fname'] = ucwords(strtolower($register_data['f_fname']));
$register_data['f_lname'] = ucwords(strtolower($register_data['f_lname']));
$register_data['f_password'] = md5($register_data['f_password']);
$register_data['f_uname'] = strtolower($register_data['f_uname']);
$fields = '`' . implode('`, `', array_keys($register_data)) . '`';
$data = '\'' . implode('\', \'', $register_data) . '\'';
mysqli_query("INSERT INTO `flight_users` ($fields, `f_regdate`) VALUES ($data, NOW())");
activation($register_data['f_mailid'], 'Swift Airlines: Activate your account', "Hello " . $register_data['f_fname'] . ", \n\nYou need to activate your account in order to use the features of Swift Airlines. Please click the link below: \n\nhttp://srikanthnatarajan.com/swift/activate.php?f_mailid=" . $register_data['f_mailid'] . "&f_mailcode=" . $register_data['f_mailcode'] . " \n\n-Swift Airlines");
}
function f_data($f_id){
$data = array();
$f_id = (int)$f_id;
$func_num_args = func_num_args();
$func_get_args = func_get_args();
if($func_num_args > 1) {
unset($func_get_args[0]);
$fields = '`'. implode('`, `', $func_get_args) . '`';
$data = mysqli_fetch_assoc(mysqli_query("SELECT $fields FROM `flight_users` WHERE `f_id` = $f_id"));
return $data;
}
}
function f_logged_in() {
return (isset($_SESSION['f_id'])) ? true : false;
}
function f_exists($f_uname) {
$f_uname = sanitize($f_uname);
$query = mysqli_query($conn, "SELECT COUNT(`f_id`) FROM `flight_users` WHERE `f_uname`= '$f_uname'");
return (mysqli_result($conn, $query, 0) == 1) ? true : false;
}
function f_email_exists($f_mailid) {
$f_mailid = sanitize($f_mailid);
$query = mysqli_query($conn, "SELECT COUNT(`f_id`) FROM `flight_users` WHERE `f_mailid`= '$f_mailid'");
return (mysqli_result($conn, $query, 0) == 1) ? true : false;
}
function f_regid_exists($f_regid) {
$f_regid = sanitize($f_regid);
$query = mysqli_query($conn, "SELECT COUNT(`f_id`) FROM `flight_users` WHERE `f_regid`= '$f_regid'");
return (mysqli_result($conn, $query, 0) == 1) ? true : false;
}
function f_active($f_uname) {
$f_uname = sanitize($f_uname);
$query = mysqli_query($conn, "SELECT COUNT(`f_id`) FROM `flight_users` WHERE `f_uname`= '$f_uname' AND `f_active` = 1");
return (mysqli_result($conn, $query, 0) == 1) ? true : false;
}
function f_id_from_username($f_uname) {
$f_uname = sanitize($f_uname);
$query = mysqli_query($conn, "SELECT `f_id` FROM `flight_users` WHERE `f_uname` = '$f_uname'");
return mysqli_result($conn, $query, 0, 'f_id');
}
function f_id_from_email($f_mailid) {
$f_mailid = sanitize($f_mailid);
$query = mysqli_query($conn, "SELECT `f_id` FROM `flight_users` WHERE `f_mailid` = '$f_mailid'");
return mysqli_result($conn, $query, 0, 'f_id');
}
function f_login($f_uname, $f_password) {
$f_id = f_id_from_username($f_uname);
$f_uname = sanitize($f_uname);
$f_password = md5($f_password);
$query = mysqli_query($conn, "SELECT COUNT(`f_id`) FROM `flight_users` WHERE `f_uname`= '$f_uname' AND `f_password` = '$f_password'");
return (mysqli_result($conn, $query, 0) == 1) ? $f_id : false;
}
?>
and this is the Loginact.php------------------
<?php
$title = 'Swift Airlines | Login Error';
include $_SERVER["DOCUMENT_ROOT"].'/swift/core/init.php';
if(empty($_POST) === false) {
$f_uname = $_POST['f_uname'];
$f_password = $_POST['f_password'];
if(empty($f_uname) === true || empty($f_password) === true){
$errors[] = 'You need to enter both, the username and the password!';
}
else if (f_exists($f_uname)===false) {
$errors[] = 'No such user exists! Please register!';
}
else if(f_active($f_uname)===false) {
$errors[] = 'Please activate your account!';
}
else {
if(strlen($f_password)>32) {
$errors[] = 'Password too long!';
}
$f_login = f_login($f_uname, $f_password);
if($f_login===false) {
$errors[] = 'Username and Password do not match!';
}
else {
$_SESSION['f_id'] = $f_login;
header('Location: http://localhost/swift/index.php');
exit();
}
}
}
else {
$errors[] = 'No Log In credentials received!';
}
include $_SERVER["DOCUMENT_ROOT"].'/swift/includes/overall/header.php';
if(empty($errors) === false) {
?>
<br/><h4>We tried to log you in, but : </h4><br/>
<?php
echo output_errors($errors);
}
include $_SERVER["DOCUMENT_ROOT"].'/swift/includes/overall/footer.php';
?>
I keep on getting those errors but i cant find a way, i already tried everything.. Hopefully someone can help me as I am new to php.
Ive been doing this for almost like a day now and i cannot figure out the answer.
i know php is kind of hard yea and ive been looking for the answer for almost a day now. Im just new to programming and im doing my best to study hard about these kind of things hopefully someone can help me.
And i hope i can learn more about php and other programming language here.. ill keep looking for the answer even if im asking right now.. big thanks though.
I doubt you tried everything!
It looks as if you are trying to migrate from mysql_ functions to mysqli_.
From the manual for mysqli_fetch_array:
$query = "SELECT Name, CountryCode FROM City ORDER by ID LIMIT 3";
$result = mysqli_query($link, $query);
/* numeric array */
$row = mysqli_fetch_array($result, MYSQLI_NUM);
printf ("%s (%s)\n", $row[0], $row[1]);
$link is your mysqli connection. In your code it is $conn.
Within your functions you have a scope issue. $conn is in the global scope, so is not set within the function's scope.
Break it down, start with something like your f_id_from_email function, and follow and try to translate the manual's examples.
The error messages are actually quite helpful if read. But you are likely overwhelmed, as you are faced with many.
Call to undefined function mysqli_result()
That's because there is no mysqli_result function.
1- general.php line 49: look at mysqli_real_escape_string, in procedural code, you must specify 2 arguments, the link (or connection) and the string.
function array_sanitize($conn,$item) {
$item = htmlentities(strip_tags(mysqli_real_escape_string($conn,$item)));
}
function sanitize($conn,$data) {
return htmlentities(strip_tags(mysqli_real_escape_string($conn,$data)));
}
2- users.php, both on line 85, the $conn does not exist in the scope of the function. Pass $conn as an argument to the function and call it with ($conn,$f_uname).
function f_exists($conn,$f_uname) {
$f_uname = sanitize($f_uname);
$query = mysqli_query($conn, "SELECT COUNT(`f_id`) FROM `flight_users` WHERE `f_uname`= '$f_uname'");
return (mysqli_result($conn, $query, 0) == 1) ? true : false;
}
3- your question at line 86, it is the same as my #2 point.
I'm creating a web application that relies heavily upon getting data from MySQL using PHP. In ~50 functions I have very similar code requesting single data values from MySQL:
function get_profile_picture($whatmember) {
global $connection;
$whatmember = mysql_prep($whatmember);
$query = "SELECT picture_location FROM members WHERE member_id={$whatmember} LIMIT 1";
$returnval = mysqli_query($connection,$query);
if(!$returnval) {
return "Query failed: " . mysqli_error($connection);
}
if(mysqli_num_rows($returnval) > 0 ) {
$row = mysqli_fetch_assoc($returnval);
return $row["picture_location"];
}
return false;
}
So my question is this: is there a generic AND safe way to make the function so that I can just input "SELECT what-value FROM what-database.what-table WHERE what-criteria=what-value" that allows for arrays of results as well as single values? I made an attempt with the following, but it obviously is a hack and slash method that only gets single values:
function get_single_value($database_name,$column_name,$table_name,$criteria,$criteria_value) {
$database_name = mysql_prep($database_name);
$column_name = mysql_prep($column_name);
$table_name = mysql_prep($table_name);
$criteria = mysql_prep($criteria);
$criteria_value = mysql_prep($criteria_value);
if(!empty($column_name) && !empty($table_name) && !empty($criteria) && !empty($database_name)) {
global $connection;
global $gamesconnection;
global $locationconnection;
if($database_name=="connection") {
$database_connection = $connection;
} else if ($database_name=="games") {
$database_connection = $gamesconnection;
} else if ($database_name=="locations") {
$database_connection = $locationconnection;
} else {
die("Database connection doesn't exist for {$database_name}.");
}
$query = "SELECT {$column_name} FROM {$table_name} WHERE {$criteria}='{$criteria_value}' LIMIT 1";
$result = mysqli_query($database_connection,$query);
if(!$result) {
die("Unable to get {$column_name} from {$table_name}. Error: " . mysqli_error($database_connection) . " Query: " . $query);
}
if(mysqli_num_rows($result)>0) {
$row = mysqli_fetch_assoc($result);
return $row[$column_name];
}
}
return false;
}
And my get_profile_picture() function would then look more like this:
function get_profile_picture($whatmember) {
return get_single_value("connection","picture_location","members","member_id",$whatmember);
}
I'm still pretty new to PHP and MySQL so any pointers to improve my code would be great as well. Thanks in advance!
Alright I wrote my own. It might not have all the security of PDO, but I don't have the learn another framework in order to use it.
function get_from_database($database_variable) {
//PASS IN $database_variable WHICH IS AN OBJECT CONTAINING THE FOLLOWING POSSIBLE VALUES
$database_name = $database_variable["database_name"]; //DATABASE NAME
$column_name = $database_variable["column_name"]; //COLUMN(S) BEING REQUESTED
$table_name = $database_variable["table_name"]; //TABLE BEING SEARCHED
$criteria = $database_variable["criteria"]; // 'WHERE X'
$limit = $database_variable["limit"]; //ANY LIMITS, IF REQUIRED
$group_by = $database_variable["group_by"]; //ANY GROUPING, IF REQUIRED
$order_by = $database_variable["order_by"]; //ANY SORT ORDERING, IF REQUIRED
if(!empty($column_name) && !empty($table_name)&& !empty($database_name)) {
global $connection;
global $gamesconnection;
global $locationconnection;
global $olddataconnection;
if($database_name=="connection") {
$database_connection = $connection;
} else if ($database_name=="games") {
$database_connection = $gamesconnection;
} else if ($database_name=="locations") {
$database_connection = $locationconnection;
} else if ($database_name=="olddata") {
$database_connection = $olddataconnection;
} else {
error_log("\nDatabase connection doesn't exist for {$database_name}." . get_backtrace_info());
return false;
}
if(is_null($limit)) {
//IF LIMIT NOT SUPPLIED, MAKE LIMIT 0, IE NO LIMIT
$limit = 0;
}
if(is_int($limit)==false) {
//NOT AN INTEGER
error_log("\nError in limit provided: " . $limit . get_backtrace_info());
return false;
}
$query = " SELECT {$column_name}
FROM {$table_name} " . (!empty($criteria) /*CHECK IF CRITERIA WAS REQUIRED*/ ? "
WHERE {$criteria} " : "") . (!empty($group_by) /*CHECK IF GROUP BY WAS REQUIRED*/ ? "
GROUP BY {$group_by} " : "") . (!empty($order_by) /*CHECK IF ORDER BY WAS REQUIRED*/ ? "
ORDER BY {$order_by} " : "") . ($limit!==0 /*CHECK IF LIMIT WAS REQUIRED*/ ? "
LIMIT {$limit} " : "");
$result = mysqli_query($database_connection,$query);
if(!$result) {
error_log("\nUnable to process query, got error: " . mysqli_error($database_connection) . "\nQuery: " . $query . get_backtrace_info());
return false;
}
if(mysqli_num_rows($result)>0) {
//RESULT SUPPLIED
$row_array = array();
while($row = mysqli_fetch_assoc($result)) {
$row_array[] = $row;
}
mysqli_free_result($result);
return $row_array;
}
}
return false;
}
Function to trace function call back to source:
function get_backtrace_info(){
//GET INFORMATION ON WHICH FUNCTION CAUSED ERROR
$backtrace = debug_backtrace();
$backtrace_string = "";
for($i=0;$i<count($backtrace);$i++) {
$backtrace_string .= '\n';
if($i==0) {
$backtrace_string .= 'Called by ';
} else {
$backtrace_string .= 'Which was called by ';
}
$backtrace_string .= "{$backtrace[$i]['function']} on line {$backtrace[$i]['line']}";
}
return backtrace_string;
}
Now I can request data from MySQL as follows:
Single value requested:
function get_profile_picture($whatmember) {
$linked_member_code = get_linked_member_code($whatmember);
return get_from_database([ "database_name" => "connection",
"column_name" => "picture_location",
"table_name" => "members",
"criteria" => "linked_member_code='{$linked_member_code}' AND team_id=0",
"limit" => 1
])[0]["picture_location"];
}
2 values requested:
function get_city_and_region_by_id($whatid) {
$row = get_from_database([ "database_name" => "locations",
"column_name" => "city, region",
"table_name" => "cities",
"criteria" => "row_id={$whatid}",
"limit" => 1
]);
return $row[0]["city"] . ", " . $row[0]["region"];
}
Unknown number of rows:
function get_linked_teams($linkedmembercode) {
return get_from_database([ "database_name" => "connection",
"column_name" => "team_id",
"table_name" => "members",
"criteria" => "linked_member_code='{$linkedmembercode}' AND team_id!=0"
]);
}
I've got a php script as follows:
function addPost(BlogPost $item, $tags) {
$connection = mysql_connect('localhost', '***', '***') or die(mysql_error());
mysql_select_db('jschaible1') or die(mysql_error());
$queryString = "insert into BlogPost values ( null, '" . $item->Title . "', '" . $item->Body . "', " . "now());";
$result = mysql_query($queryString) or die(mysql_error());
$dbResult = mysql_query('select * from blogpost where Title = "' . $item->Title . '";') or die(mysql_error());
while ($row = mysql_fetch_array($dbResult)) {
$tableID = $row['BlogPostID'];
}
foreach($tags as $t) {
$queryString = "insert ignore into Tag values('" . strtolower($t) . "');";
mysql_query($queryString) or die(mysql_error());
$queryString = "insert into blogposttag values (" . $tableID . ", '" . strtolower($t) . "');";
mysql_query($queryString) or die(mysql_error());
}
echo $connection;
mysql_close($connection) or die(mysql_error());
}
The function is being called like this:
<?php
session_start();
$errors = '';
if (!isset($_SESSION['dadfg6d5f6df54']))
header('Location:admin.php');
else {
include('Classes.php');
include('mySql.php');
include('utils.php');
if(isset($_POST['Submit'])) {
if ($_POST['Title'] == '') {
$errors = 'Post must have a title!';
}
else if ($_POST['PostBody'] == '') {
$errors = 'Post must be something!';
}
else if (strlen($_POST['PostBody']) < 10) {
$errors = "Write something substantial, c'mon!";
}
else if ($_POST['Tags'] == '') {
$errors = "At least one tag must be entered";
}
else {
$newPost = new BlogPost(NULL, sanitize($_POST['Title']), sanitize($_POST['PostBody']), NULL);
$newPost->Title = addEmoticons($newPost->Title);
$newPost->Body = addEmoticons($newPost->Body);
$tags = str_replace(',', '', $_POST['Tags']);
$tags = str_replace(';', '', $tags);
$tags = explode(' ', $tags);
error_reporting(E_ALL); ini_set('display_errors', 1);
addPost($newPost, $tags) or die();
$errors = 'Post added successfully';
}
}
}
?>
When it gets to mysql_close(), the page just stops executing and I get a blank page. This is really frustrating me, I don't understand at all why it's happening, especially seeing as how the echo on the PREVIOUS line puts out "resource id#6". I get no error message, just a blank page! Please help!
Your function has no return value. It therefore returns NULL which evaluates as a "falsy" value. Since you follow it with an or die() call, the false evaluation triggers the or die() and terminates your script.
// Don't do this:
addPost($newPost, $tags) or die();
// Do this:
addPost($newPost, $tags);
In the end of your function, you could return TRUE, but it is entirely unnecessary unless you wish to return a value based on the success or failure of your post addition. The way you have it, the die() is just causing undue harm. Since all the potential failing points in your function are already going to terminate the script on error, there is no great purpose to returning TRUE. Just remove the die() after the function call.
Warning:mysql_fetch_array(): supplied argument is not a valid MySQL result resource in **/home/davzyco1/public_html/notes/functions.php** on line 43
was the error I got when I use the below class, even though the class works PERFECTLY with my old webhost. Here's my new hosts php info: http://davzy.com/notes/php.php
class mysqlDb
{
public $con;
public $debug;
function __construct($host,$username,$password,$database)
{
$this->con = mysql_connect($host,$username,$password);
if (!$this->con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db($database, $this->con);
}
function kill()
{
mysql_close($this->con);
}
function debugOn()
{
$this->debug = true;
}
function debugOff()
{
$this->debug = false;
}
function select($query,&$array)
{
$c = 0;
$result = mysql_query("SELECT ".$query);
if($this->debug == true)
echo "SELECT ".$query;
while($row = mysql_fetch_array($result))
{
foreach($row as $id => $value)
{
$array[$c][$id] = $value;
}
$c++;
}
}
function update($update, $where,$array)
{
foreach($array as $id => $value)
{
mysql_query("UPDATE {$update} SET {$id} = '{$value}'
WHERE {$where}");
if($this->debug == true)
echo "UPDATE {$update} SET {$id} = '{$value}'
WHERE {$where}<br><br>";
}
}
function updateModern($update, $where,$array)
{
foreach($array as $id => $value)
{
mysql_query("UPDATE {$update} SET `{$id}` = '{$value}'
WHERE {$where}");
if($this->debug == true)
echo "UPDATE {$update} SET {$id} = '{$value}'
WHERE {$where}<br>";
}
}
function delete($t, $w)
{
mysql_query("DELETE FROM `{$t}` WHERE {$w}");
if($this->debug == true)
echo "DELETE FROM `{$t}` WHERE {$w}<br><br>";
}
function insert($where, $array)
{
$sql = "INSERT INTO `{$where}` (";
$sql2 = " VALUES (";
foreach($array as $id => $value){
$sql .= "`{$id}`, ";
$sql2 .= "'{$value}', ";
}
mysql_query(str_replace(', )',')',$sql.")") . str_replace(', )',')',$sql2.");"));
if($this->debug == true)
echo str_replace(', )',')',$sql.")") . str_replace(', )',')',$sql2.");")."<br><br>";
}
}
This is because mysql_query() will return FALSE if an error occured, instead of returning a result resource. You can check the error by calling mysql_error(), as shown here:
function select($query,&$array)
{
$c = 0;
$result = mysql_query("SELECT ".$query);
if($this->debug == true)
echo "SELECT ".$query;
if (!$result) {
// an error occured, let's see what it was
die(mysql_error());
}
while($row = mysql_fetch_array($result))
{
foreach($row as $id => $value)
{
$array[$c][$id] = $value;
}
$c++;
}
}
Based on the error message, you can find out what the real problem is.
You should really test to see if $result is not false before using it with mysql_fetch_array. The error you're receiving is indicative that the query itself failed.
Have you configured your database with your new host? (do all the tables exist?)
As Mark said above, you really should check your result before trying mysql_fetch_array on a result set, and verify that all tables actually exist.
Without knowing how your original server was set up, I can only guess, but it may also be that your old server was set up to not display warnings.