Passing an array in function to a query using a WHERE clause - php

Hello every body is it possible to pass an array containing some data to a function and put this array of data in a WHERE condition of a mysql query?
Please, take a look to my code if it's correct. Anyway it is not working at the moment, it prints "No results" ...
public function target_query($ids_array){
include_once 'connection.php';
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$ids = join("','",$ids_array);
$sql = "SELECT codice_target FROM customer WHERE id_customer IN ('$ids')";
$result = $conn->query($sql);
$arraytoclass = array();
if ($result->num_rows > 0) {
// output data of each row
//echo "tutto ok";
while($row = $result->fetch_row()) {
//echo "Codice target: " . $row["codice_target"]."<br>";
$arraytoclass[] = $row;
//echo "codice target:".$arraytoclass[$i]['codice_target'];
}
//print_r($arraytoclass);
return $arraytoclass;
//print_r($arraytoclass);
} else {
echo "NO results";
}
return $arraytoclass;
$conn->close();
}
The result of the query will be passed inside another function here below:
public function fputToFile($file, $allexportfields, $object, $ae)
{
if($allexportfields && $file && $object && $ae)
{
//one ready for export product
$readyForExport = array();
//put in correct sort order
foreach ($allexportfields as $value)
{
$object = $this->processDecimalSettings($object, $ae, $value);
$readyForExport[$value] = iconv("UTF-8", $ae->charset, $object[$value]);
}
$arraytoclass = $this->target_query($readyForExport['id_customer']);
print_r ($arraytoclass);
// and so on...
// and so on...
Many thanks in advance.

Related

SQL connection dies after one call

I have a custom class that takes a sql connection as a parameter. I use that to populate the class, and then I'm trying to use it again to modify the results on screen. But after the first use, I can't use it anymore.
connection.php:
$conn = new mysqli('localhost', 'root', '', 'loveConnections');
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
personalityProfile.php (front end)
if (!isset($_SESSION['interests'])) {
$interests = new Interests($conn, $_SESSION['id']);
$_SESSION['interests'] = $interests;
} else {
$interests = $_SESSION['interests'];
}
interestsObject.php
class Interests {
// properties
public $conn;
public $id;
public $interestsArray = [];
public function __construct($conn, $memberId = null, $intArray = [
'basketball' => false,
'bowling' => false,
'movies' => false,
]) {
$this->conn = $conn;
$this->id = $memberId;
$this->interestsArray = $intArray;
$this->popArraySql();
}
public function popArraySql() {
$memInterests = [];
$sql = "SELECT i.interest
FROM memberInfo m
Join MemberInterestLink mi on (mi.memberID_FK = m.memberID_PK)
Join interests i on (mi.interestID_FK = i.interestID_PK)
WHERE memberID_PK = $this->id";
$result = $this->conn->query($sql);
$this->conn works perfectly here
foreach ($result as $row) {
array_push($memInterests, $row['interest']);
}
foreach ($this->interestsArray as $key => $value) {
for ($i=0; $i<sizeof($memInterests); $i++) {
if ($memInterests[$i] === $key) {
$this->interestsArray[$key] = true;
}
}
}
}
public function insertUpdateQuery() {
var_dump($this->conn);
foreach ($this->interestsArray as $key => $val) {
echo $key . "<br>";
$select = "SELECT interestID_PK from interests where interest = '" . $key . "'";
echo $select;
$result = $this->conn->query($select);
when I try and use it later though, I get a Warning: mysqli::query(): Couldn't fetch mysqli. Additionally, if I try and var_dump it, I get Warning: var_dump(): Property access is not allowed yet
var_dump($result);
if ($val === true) {
$insert = "INSERT INTO MemberInterestLink (memberID_FK, interestID_FK) VALUES ($this->id, $interestKey)";
$this->conn->query($insert);
} else {
$delete = "DELETE FROM MemberInterestLink WHERE interestID_FK = $interestKey";
$this->conn->query($delete);
}
}
}
}
I never close the connection, which is what most of the related answers suggested the cause may be. It's like my $conn variable just stops working after the first use.

Fatal Error while running a CMS program

i get this error while running my program.
Fatal error: Uncaught Error: Call to undefined method
CarModel::InsertCar() in
C:\xampp\htdocs\CoffeeWebsite\Controller\CarController.php:119 Stack
trace: #0 C:\xampp\htdocs\CoffeeWebsite\CarAdd.php(43):
CarController->InsertCar() #1 {main} thrown in
C:\xampp\htdocs\CoffeeWebsite\Controller\CarController.php on line 119
//Source code for CarModel and CarController
<?php
require ("Entities/CarEntity.php");
//Contains database related code for the Car page.
class CarModel {
//Get all car types from the database and return them in an array.
function GetCarTypes() {
require 'Credentials.php';
//Open connection and Select database.
$con = mysqli_connect($host, $user, $passwd) or die(mysqli_error($con));
$sql = mysqli_select_db($con,$database);
$result = mysqli_query($con,"SELECT DISTINCT type FROM car") or die(mysqli_error($con));
$types = array();
//Get data from database.
while ($row = mysqli_fetch_array($result)) {
array_push($types, $row[0]);
}
//Close connection and return result.
mysqli_close($con);
return $types;
}
//Get carEntity objects from the database and return them in an array.
function GetCarByType($type) {
require 'Credentials.php';
//Open connection and Select database.
$con = mysqli_connect($host, $user, $passwd) or die(mysqli_error($con));
$sql = mysqli_select_db($con,$database);
$query = "SELECT * FROM car WHERE type LIKE '$type'";
$result = mysqli_query($con,$query) or die(mysqli_error($con));
$carArray = array();
//Get data from database.
while ($row = mysqli_fetch_array($result)) {
$name = $row[1];
$type = $row[2];
$price = $row[3];
$colour = $row[4];
$details = $row[5];
$image = $row[6];
$review = $row[7];
//Create car objects and store them in an array.
$car = new CarEntity(-1, $name, $type, $price, $colour, $details, $image, $review);
array_push($carArray, $car);
}
//Close connection and return result
mysqli_close($con);
return $carArray;
}
function GetCarByID($id)
{
require 'Credentials.php';
//Open connection and Select database.
$con = mysqli_connect($host, $user, $passwd) or die(mysqli_error($con));
$sql = mysqli_select_db($con,$database);
$query = "SELECT * FROM car WHERE id=$id";
$result = mysqli_query($con,$query) or die(mysqli_error($con));
//Get data from database.
while ($row = mysqli_fetch_array($result)) {
$name = $row[1];
$type = $row[2];
$price = $row[3];
$colour = $row[4];
$details = $row[5];
$image = $row[6];
$review = $row[7];
//Create car
$car = new CarEntity($id, $name, $type, $price, $colour, $details, $image, $review);
}
//Close connection and return result
mysqli_close($con);
return $car;
}
}
function InsertCar(CarEntity $car) {
$query = sprintf("INSERT INTO car
(name, type, price,colour,details,image,review)
VALUES
('%s','%s','%s','%s','%s','%s','%s')",
mysqli_real_escape_string($car->name),
mysqli_real_escape_string($car->type),
mysqli_real_escape_string($car->price),
mysqli_real_escape_string($car->colour),
mysqli_real_escape_string($car->details),
mysqli_real_escape_string("Images/Coffee/" . $car->image),
mysqli_real_escape_string($car->review));
$this->PerformQuery($query);
}
function UpdateCar($id, CarEntity $car) {
$query = sprintf("UPDATE car
SET name = '%s', type = '%s', price = '%s', colour = '%s',
details = '%s', image = '%s', review = '%s'
WHERE id = $id",
mysqli_real_escape_string($car->name),
mysqli_real_escape_string($car->type),
mysqli_real_escape_string($car->price),
mysqli_real_escape_string($car->colour),
mysqli_real_escape_string($car->details),
mysqli_real_escape_string("Images/Coffee/" . $car->image),
mysqli_real_escape_string($car->review));
$this->PerformQuery($query);
}
function DeleteCar($id) {
$query = "DELETE FROM car WHERE id = $id";
$this->PerformQuery($query);
}
function PerformQuery($query) {
require ('Credentials.php');
$con=mysqli_connect($host, $user, $passwd) or die(mysqli_error($con));
mysqli_select_db($con,$database);
//Execute query and close connection
mysqli_query($query) or die(mysqli_error($con));
mysqli_close($con);
}
?>
<?php
require ("Model/CarModel.php");
//Contains non-database related function for the Coffee page
class CarController {
function CreateCarDropdownList() {
$carModel = new CarModel();
$result = "<form action = '' method = 'post' width = '200px'>
Please select a type:
<select name = 'types' >
<option value = '%' >All</option>
" . $this->CreateOptionValues($carModel->GetCarTypes()) .
"</select>
<input type = 'submit' value = 'Search' />
</form>";
return $result;
}
function CreateOptionValues(array $valueArray) {
$result = "";
foreach ($valueArray as $value) {
$result = $result . "<option value='$value'>$value</option>";
}
return $result;
}
function CreateCarTables($types)
{
$carModel = new CarModel();
$carArray = $carModel->GetCarByType($types);
$result = "";
//Generate a carTable for each carEntity in array
foreach ($carArray as $key => $car)
{
$result = $result .
"<table class = 'carTable'>
<tr>
<th rowspan='6' width = '150px' ><img runat = 'server' src = '$car->image' /></th>
<th width = '75px' >Name: </th>
<td>$car->name</td>
</tr>
<tr>
<th>Type: </th>
<td>$car->type</td>
</tr>
<tr>
<th>Price: </th>
<td>$car->price</td>
</tr>
<tr>
<th>Colour: </th>
<td>$car->colour</td>
</tr>
<tr>
<th>Details: </th>
<td>$car->details</td>
</tr>
<tr>
<th>Review: </th>
<td colspan='2' >$car->review</td>
</tr>
</table>";
}
return $result;
}
function GetImages() {
//Select folder to scan
$handle = opendir("Images/Coffee");
//Read all files and store names in array
while ($image = readdir($handle)) {
$images[] = $image;
}
closedir($handle);
//Exclude all filenames where filename length < 3
$imageArray = array();
foreach ($images as $image) {
if (strlen($image) > 2) {
array_push($imageArray, $image);
}
}
//Create <select><option> Values and return result
$result = $this->CreateOptionValues($imageArray);
return $result;
}
//<editor-fold desc="Set Methods">
function InsertCar() {
$name = $_POST["txtName"];
$type = $_POST["ddlType"];
$price = $_POST["txtPrice"];
$colour = $_POST["txtColour"];
$details = $_POST["txtDetails"];
$image = $_POST["ddlImage"];
$review = $_POST["txtReview"];
$car = new CarEntity(-1, $name, $type, $price, $colour, $details, $image, $review);
$carModel = new CarModel();
$carModel->InsertCar($car);
}
function UpdateCar($id) {
}
function DeleteCar($id) {
}
//</editor-fold>
//<editor-fold desc="Get Methods">
function GetCarById($id) {
$carModel = new CarModel();
return $carModel->GetCarById($id);
}
function GetCarByType($type) {
$carModel = new CarModel();
return $carModel->GetCarByType($type);
}
function GetCarTypes() {
$carModel = new CarModel();
return $carModel->GetCarTypes();
}
//</editor-fold>
}
?>
To elaborate on my comment.
First you want to use Prepared statements. Here is an example:
/* Connection */
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* Check connection */
if ($mysqli->connect_errno)
{
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
if($stmt = $mysqli->prepare("UPDATE..."))
{
/* Bind your params */
$stmt->bind_param('ss', $username, $password);
/* Error handling if execute failed */
if (!$stmt->execute())
{
die('execute() failed: ' . htmlspecialchars($stmt->error));
}
}
else
{
/* Error handling if Prepare failed */
die('prepare() failed: ' . htmlspecialchars($DBConnect->error));
}
$stmt->close();
Read more about returning result here
Now since you want to pass in args from your functions which are unknown to the PerformQuery function, you'll want to dynamically generate the Bind Params for use of using prepared statements. I've done something similar for dynamically generating the Bind Params using Reflection.
If you pass an Args value into the PerformQuery function you could have a function that looks like this:
public function PerformQuery($sql, $args = null)
{
/* Connection */
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* Check connection */
if ($mysqli->connect_errno)
{
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
if($stmt = $mysqli->prepare($sql))
{
/* Bind your params dynamically */
if (isset($args))
{
$method = new \ReflectionMethod('mysqli_stmt', 'bind_param');
$method->invokeArgs($stmt, $this->refValues($args));
}
/* Error handling if execute failed */
if (!$stmt->execute())
{
die('execute() failed: ' . htmlspecialchars($stmt->error));
}
}
else
{
/* Error handling if Prepare failed */
die('prepare() failed: ' . htmlspecialchars($mysqli->error));
}
$stmt->close();
}
For the dynamic binding to work you'll also need the following function
private 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;
}
Now from your other methods, for example DeleteCar you'd pass in the query and args as follows:
public function DeleteCar($id)
{
$query = "DELETE FROM car WHERE id = ?"; // ? to show where mysqli will bind
$args = array('i', $id); // i means an int
$this->PerformQuery($query, args);
}
Using prepared statements will make your code much more secure and dynamically binding the variants in the Preform Query function means that you don't have to completely refactor your code to pass a connection around so you can use mysqli_real_escape_string.
Good luck :)

setting php boolean to FALSE not working

I have no records in a table called assessment
I have a function:
function check_assessment_record($p_id, $a_id, $c){
$dataexistsqry="SELECT * FROM assessments WHERE (pupil_id=$p_id && assessblock_id=$a_id)" ;
$resultt = $c->query($dataexistsqry);
if ($resultt->num_rows > 0) {
echo '<p>set $de = true</p>';
$de=TRUE;
}else{
echo '<p>set $de = false</p>';
$de=FALSE;
}
return $de;
$dataexists->close();
}; //end function
I call the function thus:
$thereisdata = check_assessment_record($pupil_id, $assessblock_id, $conn);
However my function is printing out nothing when I was expecting FALSE. It prints out true when there's a record.
When I get the result in $thereisdata I want to check for if its TRUE or FALSE but its not working.
I looked at the php manual boolean page but it didn't help
It seems that you are passing the database connection as an object using the variable $c in your function parameter. This tells me that you would greatly benefit by creating a class and using private properties/variables. Also, there are many errors in your code that shows me what you are trying to achieve, some errors are the way you are closing your db connection using the wrong variable, or how you place the close connection method after the return, that will never be reached.
Anyway, I would create a database class where you can then call on specific functions such as the check_assessment_record() as you wish.
Here's how I would redo your code:
<?php
class Database {
private $conn;
function __construct() {
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "test";
// Create connection
$this->conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($this->conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
}
function check_assessment_record($p_id, $a_id) {
$sql = "SELECT * FROM assessments WHERE (pupil_id=$p_id && assessblock_id=$a_id)";
$result = $this->conn->query($sql);
if ($result->num_rows > 0) {
echo '<p>set $de = true</p>';
$de = TRUE;
} else {
echo '<p>set $de = false</p>';
$de = FALSE;
}
return $de;
}
function __destruct() {
$this->conn->close();
}
}
$p_id = 1;
$a_id = 2;
$db = new Database();
$record = $db->check_assessment_record($p_id, $a_id);
var_dump($record);
?>
are you using PDO's correctly?
A call for me would normally look like;
$aResults = array();
$st = $conn->prepare( $sql );
$st->execute();
while ( $row = $st->fetch() ) {
//do something, count, add to array etc.
$aResults[] = $row;
}
// return the results if there is, else returns null
if(!empty($aResults)){return $aResults;}
if you didnt want to put the results into an array you could just check if a column is returned;
$st = $conn->prepare( $sql );
$st->execute();
if(! $st->fetch() ){
echo 'there is no row';
}
Here is the code
function check_assessment_record($p_id, $a_id, $c){
$dataexistsqry="SELECT * FROM assessments WHERE (pupil_id=$p_id && assessblock_id=$a_id)" ;
$resultt = $c->query($dataexistsqry);
if ($resultt->num_rows > 0) {
echo '<p>set $de = true</p>';
$de=TRUE;
}else{
echo '<p>set $de = false</p>';
$de=FALSE;
}
return $de;
$dataexists->close();
}; //end function
You can check the return value using if else condition as
$thereisdata = check_assessment_record($pupil_id, $assessblock_id, $conn);
if($thereisdata){ print_f('%yes data is present%'); }
else{ print_f('% no data is not present %'); }
The reason is , sometime function returning Boolean values only contain the true value and consider false value as null , that's why you are not printing out any result when data is not found.
Hope this will help you. Don't forget to give your review and feedback.

Warning: mysqli_query(): Couldn't fetch mysqli in my code

I know this question has been asked many times , I tried lot of other answers but it didn't work for me
Here is my class
<?php
class saveexceltodb
{
var $inputFileName;
var $tableName;
var $conn;
var $allDataInSheet;
var $arrayCount;
/**
* Create a new PHPExcel with one Worksheet
*/
public function __construct($table=0)
{
$this->initiatedb();
}
private function initiatedb(){
//var_dump($allDataInSheet);
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "xyx";
// Create connection
$this->conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$this->conn) {
die("Connection failed: " . mysqli_connect_error());
}
}
public function updateIntermidiate(){
$allocationeventwise=array();
mysqli_query($this->conn,"DELETE FROM `allocationeventwise` WHERE 1");
$sql = "INSERT INTO `allocationeventwise` (`empid`, `event1`, `event2`, `event3`, `event4`, `event5` `event6`, `event7`) VALUES ";
$result = mysqli_query($this->conn, "SELECT usdeal.empid , usdeal.event1 , usdeal.event2, usdeal.event3, usdeal.event4, usdeal.event5, usdeal.event6, usdeal.event7 , salary.salary from usdeal INNER JOIN salary ON usdeal.empid = salary.empid where usdeal.allocated=0");
$i=0;
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$i++;
$totaleventDays = $row["event1"]+$row["event2"]+$row["event3"]+$row["event4"]+$row["event5"]+$row["event6"]+$row["event7"];
$allocationeventwise[$row["empid"]]['event1']=($row['salary']/$totaleventDays)*$row["event1"];
$allocationeventwise[$row["empid"]]['event2']=($row['salary']/$totaleventDays)*$row["event2"];
$allocationeventwise[$row["empid"]]['event3']=($row['salary']/$totaleventDays)*$row["event3"];
$allocationeventwise[$row["empid"]]['event4']=($row['salary']/$totaleventDays)*$row["event4"];
$allocationeventwise[$row["empid"]]['event5']=($row['salary']/$totaleventDays)*$row["event5"];
$allocationeventwise[$row["empid"]]['event6']=($row['salary']/$totaleventDays)*$row["event6"];
$allocationeventwise[$row["empid"]]['event7']=($row['salary']/$totaleventDays)*$row["event7"];
$sql .='("'.$row["empid"].'",
'.$allocationeventwise[$row["empid"]]["event1"].',
'.$allocationeventwise[$row["empid"]]["event2"].',
'.$allocationeventwise[$row["empid"]]["event3"].',
'.$allocationeventwise[$row["empid"]]["event4"].',
'.$allocationeventwise[$row["empid"]]["event5"].',
'.$allocationeventwise[$row["empid"]]["event6"].',
'.$allocationeventwise[$row["empid"]]["event7"].',)';
if($i<mysqli_num_rows($result))
$sql .=",";
else
$sql .=";";
}
echo $sql;
if (mysqli_query($this->conn, $sql)) {
echo "New record created successfully<br/>";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($this->conn);
}
} else {
echo "0 results";
}
}
}
When I use it like this
include('saveexceltodb.php');
$obj = new saveexceltodb(0);
$obj->updateIntermidiate();
I get following error .
Warning: mysqli_query(): Couldn't fetch mysqli in C:\xampp\htdocs\import-excel\saveexceltodb.php
You should follow below steps
Check database connection
Check query syntax
You have to pass connection object in mysqli_query function in you case it is ' $this->conn '
Hope, It may help you.

How to separate mysql row values by comma using php?

I have tried the following code to output each student father_contact by firstly merging them and secondly separating each number by comma and could not make it working. Please help me.
$sql = "SELECT Fathers_Contact FROM student WHERE Class ='$class' AND Section='$s' and Year='$y'";
$result = mysql_query($sql);
if (!$result) {
die("Query not working");
}
$mbno_arr = array();
while ($row = mysql_fetch_array($result)) {
$mbno_arr[] = $row[0];
}
$mbno_list = implode(',', $mbno_arr);//expect here is: 9867656543,9867656443,9867654543
if(empty($mbno_list)){
echo "No number is there";
exit;
}
if(empty($msg)){
echo "Message empty!";
exit;
}
Father_contact is ten digit mobile no.
// Escapes special characters in a string for use in an SQL statement
$SQL = sprintf(
"SELECT Fathers_Contact
FROM student
WHERE Class = '%s' AND Section = '%s' and Year = '%s'",
mysql_real_escape_string($class),
mysql_real_escape_string($s),
mysql_real_escape_string($y)
);
// Result or die (print mysql error)
$result = mysql_query($SQL) or die( mysql_error() );
// Check if result has rows
if( mysql_numrows($result) > 0 )
{
$mbno_arr = array();
while ( $row = mysql_fetch_array($result) )
$mbno_arr[] = $row[0];
if( count($mbno_arr) > 0)
echo implode(',', $mbno_arr);
else
echo 'No number is there';
}
else
{
echo 'No result for query';
}
// free result
mysql_free_result($result);
NB use PDO or mysqli. mysql_* is deprecated
Firstly, mysql_* is now officially deprecated. Please use PDO or MySQLi.
Can you try this:
<?php
// Connect
$mysqli = new mysqli("localhost", "my_user", "my_password", "my_database");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
// Query
$query = "SELECT Fathers_Contact FROM student WHERE Class = ? AND Section = ? and Year = ?";
if ($stmt = $mysqli->prepare($query)) {
{
// Bind params
$stmt->bind_param("sss",
$class,
$s,
$y);
// Execute statement
$stmt->execute();
// fetch associative array
$mbno_arr = array();
$result = $stmt->fetch_result();
while ($row = $result->fetch_assoc())
{
// Build data
$mbno_arr[] = $row['Fathers_Contact'];
}
// close statement
$stmt->close();
// Debug?
$mbno_list = implode(',', $mbno_arr);
if (empty($mbno_list)) {
echo "No number is there";
} else {
echo "Query Results: $mbno_list";
}
}
// Close Connection
$mysqli->close();
?>

Categories