how to send object/database connection to function in php - php

i open a sql connection and try to send it to another function and it doesnt work .
its probbably something with sintax ,
i search all over the internet and couldnt find it .
my code :
$mainDataBase = mysqli_connect(/...../);
if ($mainDataBase->connect_errno) {
printf("Connect failed: %s\n", $mainDataBase->connect_error);
die;
}
/**
* 1 -> logIn && getInformation
*
* */
switch ($whichOperation){
case 1:
$gettingPlayerNumber = checkIfPlayerExist($mainDataBase, $playerName, $playerPass);
if($gettingPlayerNumber == 0){
echo "F";
die;
}
... keep going ...
function ::
function checkIfPlayerExist($dataBase ,$playerName ,$pass ){
$result = $dataBase->query("select playerNumber from PlayerInformation where (playerAccount = '" . $playerName ."') && (playerPass = " . $playerPass .")");
$row = $result->fetch_assoc();
if($row != null)
return $row['playerNumber'];
return 0;
}
its says:
Call to a member function fetch_assoc() on a non-object.
thank you for your time.
after some of the answer i checked and $result is null , but i checked the query before and now and it works!.
pass is int so it doesnt need any '' around it in the query.*
its connected succsesfully to the database - i checked this too

there seems to be a bug in your query,near password,missing quotes:
change,
$result = $dataBase->query("select playerNumber from PlayerInformation where (playerAccount = '" . $playerName ."') && (playerPass = " . $playerPass .")");
to
$result = $dataBase->query("select playerNumber from PlayerInformation where (playerAccount = '" . $playerName ."') && (playerPass = '" . $playerPass ."')");

Related

How can i execute a program if the monster id doesnt exist?

This is my current code.
$monster_result = mysql_query("SELECT * FROM xx_monsters WHERE MonsterId = '$monster_id'") or die(mysql_error());
$char_result = mysql_query("SELECT * FROM xx_characters WHERE id = '" . $char_id . "'") or die(mysql_error());
$char = mysql_fetch_assoc($char_result);
if (mysql_num_rows($monster_result) > 0) {
$monster_result = mysql_query("SELECT * FROM xx_monsters WHERE MonsterId = " . $monster_id) or die(mysql_error());
//I tried adding this, but for some reason it messed up the entire thing
//exec("/usr/local/bin/lostID $monster_id");
} else {
$level = $char['level'] + 1;
$level2 = $char['level'] - 10;
$monster_result = mysql_query("SELECT * FROM xx_monsters WHERE Level < " . $level . " AND Level > " . $level2 . " AND ExtraData != 'trainer' AND ExtraData != 'starter' ORDER BY RAND() LIMIT 1") or die(mysql_error());
}
$monster = mysql_fetch_assoc($monster_result);
I tried to add it under else too, but it renders the page totally blank, there are echo statements after this. Whats wrong?
Try the function isset($variable_name)
I would suggest to use
if(!empty($monster_id)) {
// your code here
}
Empty function will also make sure that variable value should not be null or empty string.

PHP MySQL result issue when using a variable in the WHERE Clause

I am having a pretty weird problem with my PHP MySQL Query, I am trying to return rows that have the correct rname, rcity, and rstate values.
$sql = "SELECT * FROM `images` WHERE rname = '" . $rname . "' AND rcity = '" . $rcity . "' AND rstate = '" . $rstate . "'";
When I run that query, it only returns 0 results. However after some playing around with it, If I only use rname and rstate in the WHERE Clause it returns results.
$sql = "SELECT * FROM `images` WHERE rname = '" . $rname . "' AND rstate = '" . $rstate . "';
That works perfect. So when i tried just useing rcity in the WHERE Clause.
$sql = "SELECT * FROM `images` WHERE rcity = '" . $rcity . "'";
0 results return. So something is wrong with the rcity portion of the query. If I hard write the value into the query instead of the $rcity variable, it pulls up results. I doubled checked to make sure $rcity was declared, it has the correct value, etc.
I also created another test table in the database to check to see if it was a problem on the db side. Which the problem still existed.
Here is the full code of the getQuery() Function
private function getQuery($data){
// Takes raw data and creats image(s) query to search for listing resort...
$listing = $data['listing'];
$rname = $data['rname'];
$rcity = $data['rcity'];
$rstate = $data['rstate'];
$query = "SELECT * FROM `test` WHERE rname = '" . $rname . "' AND rcity = '" . $rcity . "' AND rstate = '" . $rstate ."'";
return $query;
}
And Here is my database class
class db {
public function __construct(){
$this->server = DB_SERVER;
$this->user = DB_USER;
$this->Pass = DB_PASS;
$this->Database = DB_Database;
}
protected function connect(){
return mysqli_connect($this->server, $this->user, $this->Pass, $this->Database);
}
public function query($sql){
$conn = $this->connect();
$query = $conn->query($sql);
if($query == false) {
throw new Exception("Query failed:".PHP_EOL.$conn->error.PHP_EOL.$sql);
}
if($query->num_rows == 0) {
// need E_NOTICE errors enabled to see this,
// on screen if display_errors is on, else in PHP error log
trigger_error("Query returned 0 rows:".PHP_EOL.$sql);
}
$result = array();
while ($row = $query->fetch_assoc()){
$result[] = $row;
}
return $result;
}
}
I call the query in a class __construct function like so
$con = new db;
$sql = $this->getQuery($data);
$result = $con->query($sql);
I think problem can be with syntax or mysql screening. Try to use PDO with bindParam method
$sql = "SELECT * FROM `images` WHERE rname = '$rname' AND rcity = '$rcity' AND rstate = '$rstate'";
Try to implement this i.e. using variable directly between ' (apostrophe), It should work perfect

php/SQL function not working? trying to get the membership_id from a database

function get_user_id()
{
global $db;
$userid = NULL;
if (!empty($_COOKIE['PHPSESSID']))
{
$result = $db->execute("
SELECT profile_id
FROM " . TABLE_PREFIX . "profile_online
WHERE hash = '" . $db->escape_string($_COOKIE['PHPSESSID']) . "'
");
if ($row = $db->fetch_array($result))
{
$userid = $row[0];
}
}
return $userid;
}
function get_membership_id($userid)
{
global $db;
$result = $db->execute("
SELECT * FROM date_profile WHERE profile_id = '" . $db->escape_string($userid) . "'");
$mem = $db->fetch_array($result)
$membership = $mem[17];
return $membership;
}
the get_user_id is functioning fine... but the membership part i just can't get it to work..
I am trying to take the membership ids.. and make it so certain code will not run for them.
with an : if ($membership != 18 )
so it shows all everyone except the membership 18 people...
also tried this:
function get_membership_id($userid)
{
global $db;
$membership = $db->execute("SELECT `membership_type_id` FROM `date_profile` WHERE `profile_id`= '" . $db->escape_string($userid) . "'");
return $membership;
}
any help would be appreciated greatly.
missed ; here
$mem = $db->fetch_array($result);
^
You're missing semicolon after $mem = $db->fetch_array($result).
forgot to use TABLE_PREFIX constant.
SELECT * FROM " . TABLE_PREFIX . "date_profile WHERE profile_id ...

Building an array from two tables (getting images from one table for a product from the other)

OK I know this should be easy but i'm going round in circles. I have two tables, and two functions each running a query, the first function gets a product, the second one gets images for a product
I want to get an array which is the product, and it's images...
here's my code...
/**
* Gets the requested product from the DB
*
* #param string $productUrl
* #param string $productID
*/
private function _db_get_product($productUrl = null, $productID = null) {
if (empty($productUrl) && empty($productID))
return;
$db = $this->getConnection();
$q = "SELECT " . $this->_leaf_sql_fields() .
" FROM content_products_items pr WHERE pr.productStatus >= "
. menuMachine::getMinimumStatus() . " ";
if (!empty($productUrl))
$q .= " AND productUrl = '" . $productUrl . "'";
if (!empty($productID))
$q .= " AND productID = '" . $productID . "'";
if ($res = $db->recordsetSingle($q))
$this->_product = $res;
return $res;
}
/**
* Get the images for the product
* #return array
*/
private function _db_get_product_images($productID) {
$db = $this->getConnection();
$q = "SELECT * FROM content_products_images WHERE productID = '" . $productID . "'";
$this->_productImages = $db->recordset($q);
}
Are you just looking for a query to combine the two within the same function?
//Basic query, improve it according to your needs
SELECT
*
FROM
content_products_items as p,
content_products_images as i
WHERE
p.productID = $productId AND
i.productID = p.productID;
Or for a way to call both functions and combine the results in a array?
$myProduct = array(
'productData' => $this->_db_get_product($productUrl, $productID),
'productImages' => $this->_db_get_product_images($productID),
);
Both should guide you into a working direction.
My first attempt at answering someone here on StackOverflow, so bear with me ... but I think the below is what you are looking for?
$product = array('product' => _db_get_product($URL, $ID), 'images' => _db_get_product_images($ID));
Alternately, if you want it all in one go and don't need the two separate methods for anything else, you could rewrite your _db_get_product method as follows:
private function _db_get_product($productUrl = null, $productID = null) {
if (empty($productUrl) && empty($productID))
return;
$output = array();
$db = $this->getConnection();
$q = "SELECT " . $this->_leaf_sql_fields() .
" FROM content_products_items pr WHERE pr.productStatus >= "
. menuMachine::getMinimumStatus() . " ";
if (!empty($productUrl))
$q .= " AND productUrl = '" . $productUrl . "'";
if (!empty($productID))
$q .= " AND productID = '" . $productID . "'";
if ($res = $db->recordsetSingle($q))
array_push($output, $res);
$q2 = "SELECT * FROM content_products_images WHERE productID = '" . $productID . "'";
array_push($output, $db->recordset($q2));
return $output;
}

php mysql adding values to array based on IF statements

Using Joomla, having issues trying to build a mySQL query based on URL arguments. The code I have looks like this:
$db =& JFactory::getDBO();
$hpprice = JRequest::getVar('hprice');
$lprice = JRequest::getVar('lprice');
$city = JRequest::getVar('city');
$zip = JRequest::getVar('zip');
$bdrms = JRequest::getVar('bdrms');
$bths = JRequest::getVar('bths');
$query = "SELECT * FROM " . $db->nameQuote('#__mls') . " WHERE 1=1";
$clauses = array();
if ($zip != null) {
$clauses[] = $db->nameQuote('MSTZIP') . " = " . $db->quote($zip);
}
if ($city != null) {
$clauses[] = $db->nameQuote('MSTCITY') . " = '" . $db->quote($city) . "'";
}
if ($bdrms != null){
$clauses[] = $db->nameQuote('MSTBDRMS')." >= ".$db->quote($bdrms);
}
if ($bths != null){
$clauses[] = $db->nameQuote('MSTBATHS') . " >= " . $db->quote($bths);
}
if ($lprice != null){
$clauses[] = $db->nameQuote('MSTLISTPRC') . " BETWEEN " . $db->quote($lprice) . " AND " . $db->quote($hprice);
}
$query .= implode(" AND ", $clauses);
$db->setQuery($query);
$table = $db->loadRowList();
return $table;
So, as you can see it, adds arguments to the mySQL query based on whether or not arugments exist in the URL. What I can't wrap my head around is building the array and imploding it.
Whenever I put an argument in the URL, all the table items populate. When I try to pass an argument, it comes up null. You can see this in action here. If you add another argument like zip to the URL, everything comes up NULL.
I think the problem is this " WHERE 1=1".try to change this to this-" WHERE 1=1 ".
Because the final query will be appended to this and you'll not get the desire result.For confirmation also echo $query see if it's a correct query.one more thing is '" . $db->quote($city) . "'".remove '' as you are already adding this by a function.
//Update:
Better to use where method
Let me know if this does not work.
Not sure how this is diffent than your previous question.
$query->select('*");
$query->from($db->nameQuote('#__mls'));
$query->where('1 = 1', AND);
if ($zip != null)
{
$query->where (.$db->nameQuote('MSTZIP')." = ".$db->quote($zip));
}
if ($city != null)
{
$query->where($db->nameQuote('MSTCITY')." = '".$db->quote($city));
}
Etc
There is no need for you to build any array; that it the whole point of having a databasequery api.
Final script ended up looking like this:
$db =& JFactory::getDBO();
$hprice = JRequest::getVar('hprice');
$lprice = JRequest::getVar('lprice');
$city = JRequest::getVar('city');
$zip = JRequest::getVar('zip');
$bdrms = JRequest::getVar('bdrms');
$bths = JRequest::getVar('bths');
$query = "SELECT * FROM " . $db->nameQuote('#__mls') . " WHERE 1=1 AND ";
$clauses = array();
if ($zip != null) {
$clauses[] = "MSTZIP = " . $zip;
}
if ($city != null) {
$clauses[] = "MSTCITY = " . $db->quote($city);
}
if ($bdrms != null){
$clauses[] = "MSTBDRMS >= " . $bdrms;
}
if ($bths != null){
$clauses[] = "MSTBATHS >= " . $bths;
}
if ($lprice != null){
$clauses[] = "MSTLISTPRC BETWEEN " . $lprice . " AND " . $hprice;
}
$query .= implode(" AND ", $clauses) . ";";
$db->setQuery($query);
$table = $db->loadRowList();
return $table;
I ended up getting rid of nameQuote and quote except where needed/applicable. The script model I was working off of was from some tutorial. It worked for what I was doing previously, but not now for some reason. Last step would be to make the initial AND conditional, but that shouldn't take much. At least the framework is there now. Thanks to all who helped.

Categories