How to declare multiple where condition for a table - php

hi guy's i have a question.
how to declare a multiple where clause condition inside one php only.
i have try to make my project has a minimum of a php file. i want to make my where clause inside one php file only.
this is the problem i mean. i want to put my code into one php file or inside one <?php ?>. the php code like this
<?php
include("../../Connections/koneksi.php");
$date1= $_POST['date1'];
// Data for Titik1
$sql = "SELECT * FROM termocouple where tanggal='$date1' AND silo='Silo 1'";
$query = mysqli_query($db,$sql);
$rows = array();
while($tmp= mysqli_fetch_assoc($query)) {
$rows[] = $tmp;
}
echo json_encode($rows);
mysqli_close($db);
?>
on the code above the query has select table termocouple and the filter of where condition is tanggal and silo. now the problem is i have 12 php file like that. and the different of every php is from the selecting silo, i put Silo 1,Silo 2,Silo 3, ....Silo 12.
please someone help me with this. i want to make it simple in one php file. im really appreciated when you give me an example

In order to minimize your code, if you are using the same query or code more than one time in the same project, it is more recommended to create a function, that you will call anytime you need to execute the code.
So here, since you are using the same query 12 times, you will have to create a function that executes this query, and then call this function every time you want to execute the query.
The function takes parameters, so you will have to give the function the database connection parameter $db in order to connect to the database since you are using this connection inside the function, and then you have to add the values of the where clause to the parameters also.
So your function here will take the database connection $db, $date1 fetched from $_POST, and $silo fetched from $_POST
At the end of the function, you can return any value you wish to return, so in your case, you will have to return the $rows array fetched from the query
Create a common php fileand create a function in it.
Lets say the file name is libraries.php
in this file write the following code:
<?php
function getRows($db, $date, $silo) {
$sql = "SELECT * FROM termocouple where tanggal='$date' AND silo='$silo'";
$query = mysqli_query($db, $sql);
$rows = array();
while($tmp= mysqli_fetch_assoc($query)) {
$rows[] = $tmp;
}
return json_encode($rows);
}
?>
And in each of the files where you are calling the query you will remove the php code and replace it with the following:
<?php
include("../../Connections/koneksi.php");
include("{path-to-file}/libraries.php");
$date1= $_POST['date1'];
$silo = $_POST['silo'];
$rows = getRows($db, $date1, $silo) ;
?>

I am assuming these 12 PHPs are called in diff scenarios. Why dont you pass some param from client side so that the PHP knows which scenario to execute.
$date1= $_POST['date1'];
$silo= $_POST['silo'];//This could be 'Silo 1 OR 'Silo 2' etc.
// Data for Titik1
$sql = "SELECT * FROM termocouple where tanggal='$date1' AND silo='$silo'";
$query = mysqli_query($db,$sql);

Related

I want to take the variable that contains a mysql query from one php file, and write the loop that will print the query contents in another php file

I am a beginner trying to make a webpage where a schedule of reservations is being retrieved from the database. In a php file I have a class that has a function that creates a query using a SELECT statement, here is the function
public function getDTodayScheduleDB(){
$session=Modulator::getSession();
$session->start();
$currentdrID=$_SESSION['userID'];
$todayDate = date("Y/m/d");
$getTSchedule = "SELECT time, user.name FROM reservation FULL JOIN user ON childID = user.ID AND doctorID = '$currentdrID' AND date = '$todayDate'";
$result = Modulator::getDb()->query($getTSchedule);
return $result;
}
I am not sure if this is the right way to do it or not but I read this when I tried googling it. the $result variable is returned in a php file and used like this
<?php
include realpath($_SERVER['DOCUMENT_ROOT'] . '/Classes/Models/DoctorModel.php');
$scheduleResult = DoctorModel::getDTodayScheduleDB();
while($row = mysqli_fetch_assoc($scheduleResult)){
$appTime = $row['time'];
$childName = $row['name'];
echo"<tr>";
echo"<td>".$appTime."</td>";
echo"<td>".$childName."</td>";
echo"</tr>";
}
?>
However I do not know why it is not working although I tested the query elsewhere and it works so he problem is with the variable passing from the function to the other page I guess.
Using the :: operator, you are calling a non static (i.e instance method) function as if it was a static function. Assuming that your getDTodayScheduleDB is inside a DoctorModel class, you have to define it this way:
public static function getDTodayScheduleDB(){
//your code here
}

What kind of object can I send to this view in order to get this PHP code to work?

I am terrible at PHP and I need to retrieve data from a database and give it to an index.php view. The view is pre-made and has this code:
//This is simplified - it has error handling that is not shown
$results = getAll($tableName);
//This is the line where it is failing
//Undefined Offset
$columns = empty($results) ? array() : array_keys($results[0]);
$idColumn = $columns[0];
There is all the rest of it but I just need to know what on earth it is that this bit of code is expecting. I have not even got the first clue what is supposed to be sent to this thing. I just need to get it to work.
This is what I have tried so far:
function getAll($tablename)
{
$mysqlConnection = getDbConnection();//Just the normal PDO db connection
$sql = "SELECT * FROM ".$tablename;
$sth = $mysqlConnection->prepare($sql);
$sth->execute();
$resultSet = $sth->fetch(PDO::FETCH_ASSOC);
return $resultSet;
}
I have tried various different PDO::FETCH_... types but nothing is working. There is no information about what it is that I am supposed to send that part of the view.
If you want all the rows from fetch(), you will need to loop through the result set because it will return a single row. In the loop you can place them in an array.
You can use fetchAll() instead. It will return all the results as an array.

Inserts about 30 times MYSQL

This php is supposed to insert into "d2" based on if that day is selected in "d1". It inserts about 30 times for each row in "d1". I use While all the time and never run into this problem, any idea why this would happen?
$query = mysqli_query($connection, 'SELECT * FROM '.$SETTINGS["d1"]);
while($query_array = mysqli_fetch_array($query)){
$connection_main = mysqli_connect($SETTINGS["hostname"], $SETTINGS["mysql_user"], $SETTINGS["mysql_pass"], 'u_db_main_'.$query_array['id']);
$dayofweek = strtolower(date('l'));
$query2 = mysqli_query($connection_main, 'SELECT * FROM '.$SETTINGS_MAIN["d1"].' WHERE '.$dayofweek.' ="1"');
while($query2_array = mysqli_fetch_array($query2)){
mysqli_query($connection_main, "INSERT INTO ".$SETTINGS_MAIN["d2"]." (c1) VALUE ('".$query2_array['data_1']."')");
$id = mysqli_insert_id($connection_main);
calc_function($id);
}
}
The function calc_function has NO INSERTS in it but does use a global to get the same variables, could that be recalling the insert?
function calc_function($id){
global $connection_main;
global $SETTINGS_MAIN;
//rest of function below
I have been working at this for a week and tested everything! Any help would be appreciated!
Your problem is that you are trying to use the same connection resource to both fatch and insert. As soon as you run another query on that connection you will lose the previous results. Use mysqli_fetch_all() to get all of the results from $query2, then itterate the array and run the insert query.

php function save result at array

hello i want to create function with returning data, for example when i have the function advert i want to make it every time show what i need, i have the table id, sub_id, name, date, and i want to create the function that i can print every time what i need advert(id), advert(name), i want to make it to show every time what i need exactly and i want to save all my result in array, and every time grab the exactly row that i want
<?php
function advert($data){
$id = $_GET['id'];
$query = mysql_query("SELECT *FROM advertisement WHERE id = $id");
while($row = mysql_fetch_assoc($query)){
$data = array(
'id' => $row['id']
);
}
return $data;
}
echo advert($data['id']);
?>
but my result every time is empty, can you help me please?
There are so many flaws in this short piece of code that the only good advice would be to get some beginners tutorial. But i'll put some effort into explaining a few things. Hopefully it will help.
First step would be the line function advert($data), you are passing a parameter $data to the method. Now later on you are using the same variable $data in the return field. I guess that you attempted to let the function know what variable you wanted to fill, but that is not needed.
If I understand correctly what you are trying to do, I would pass in the $id parameter. Then you can use this function to get the array based on the ID you supplied and it doesnt always have to come from the querystring (although it could).
function advert($id) {
}
Now we have the basics setup, we want to get the information from the database. Your code would work, but it is also vulnerable for SQL injection. Since thats a topic on its own, I suggest you use google to find information on the subject. For now I'll just say that you need to verify user input. In this case you want an ID, which I assume is numeric, so make sure its numeric. I'll also asume you have an integer ID, so that would make.
function advert($id) {
if (!is_int($id))
return "possible SQL injection.";
}
Then I'll make another assumption, and that is that the ID is unique and that you only expect 1 result to be returned. Because there is only one result, we can use the LIMIT option in the query and dont need the while loop.
Also keep in mind that mysql_ functions are deprecated and should no longer be used. Try to switch to mysqli or PDO. But for now, i'll just use your code.
Adding just the ID to the $data array seems useless, but I guess you understand how to add the other columns from the SQL table.
function advert($id) {
if (!is_int($id))
return "possible SQL injection.";
$query = mysql_query("SELECT * FROM advertisement WHERE id = $id LIMIT 1");
$row = mysql_fetch_assoc($query);
$data = array(
'id' => $row['id']
);
return $data;
}
Not to call this method we can use the GET parameter like so. Please be advised that echoing an array will most likely not give you the desired result. I would store the result in a variable and then continue using it.
$ad = advert($_GET['id']);
if (!is_array($ad)) {
echo $ad; //for sql injection message
} else {
print_r($ad) //to show array content
}
Do you want to show the specific column value in the return result , like if you pass as as Id , you want to return only Id column data.
Loop through all the key of the row array and on matching with the incoming Column name you can get the value and break the loop.
Check this link : php & mysql - loop through columns of a single row and passing values into array
You are already passing ID as function argument. Also put space between * and FROM.
So use it as below.
$query = mysql_query("SELECT * FROM advertisement WHERE id = '".$data."'");
OR
function advert($id)
{
$query = mysql_query("SELECT * FROM advertisement WHERE id = '".$id."'");
$data = array();
while($row = mysql_fetch_assoc($query))
{
$data[] = $row;
}
return $data;
}
Do not use mysql_* as that is deprecated instead use PDO or MYSQLI_*
try this:
<?php
function advert($id){
$data= array();
//$id = $_GET['id'];
$query = mysql_query("SELECT *FROM advertisement WHERE id = $id");
while($row = mysql_fetch_assoc($query)){
array_push($data,$row['id']);
}
return $data;
}
var_dump($data);
//echo advert($data['id']);
?>

Strange error "sqlsrv_fetch_array(): 16 is not a valid ss_sqlsrv_stmt resource" since ReturnDatesAsStrings

I am using the sqlsrv driver for IIS so I can connect to a MS SQL server in PHP.
I've managed to convert a lot of my original mysql_ code and all going well, until I tried to SELECT some DateTime fields from the database. They were coming back as Date objects in PHP rather than strings, I found the fix which is adding this to the connection array:
'ReturnDatesAsStrings'=>1
Since doing that though my code is broken when trying to populate my recordset:
function row_read($recordset) {
if (!$recordset) {
die('<br><br>Invalid query :<br><br><bold>' . $this->sql . '</bold><br><br>' . sqlsrv_error());
}
$rs = sqlsrv_fetch_array($recordset);
return $rs;
}
The error is: sqlsrv_fetch_array(): 16 is not a valid ss_sqlsrv_stmt resource
There is such little amount of help on that error in Google so this is my only shot! I just don't get it.
row_read is called from within a While: while ($row = $db->row_read($rs)) {
Any ideas?
Just to add more code and logic - I do a simple SELECT of all my orders, then as it loops through them, I do another 2 SELECT's on the orders table then the customer table. It's falling down when I try these extra 2 'gets':
$this->db->sql = "SELECT * FROM TicketOrders";
$rs = $this->db->query($this->db->sql);
$this->htmlList->path("skin/search.bookings");
if ($this->db->row_count != 0) {
while ($row = $this->db->row_read($rs)) {
// Load the order row
$this->TicketOrders->get($this->db, $row['Id']);
// Load the customer row
$this->Customers->get($this->db, $row['CustomerId']);
Did you pass this resource variable by another function? If yes, you can try by executing the sqlsrv_query and executing sqlsrv_fetch_array in one function; don’t pass the ss_sqlsrv_stmt resource by another function. Hope that it will help.
Does your program involves a nested query function?
If so, the next question is: are you opening the same database in the inner query function?
Try these changes:
comment out the lines that open the database, including the { and } that enclose the function,
change the name of connection and array variables between the outer loop and the inner loop.
In other words, the outer loop may have:
$tring = sqlsrv_query($myConn, $dbx_str1);
while( $rs_row1 = sqlsrv_fetch_array($tring, SQLSRV_FETCH_ASSOC))
and the inner loop would have:
$tring2 = sqlsrv_query($myConn, $dbx_str2);
while( $rs_row2 = sqlsrv_fetch_array($tring2, SQLSRV_FETCH_ASSOC))
sqlsrv_fetch_array need a ss_sqlsrv_stmt resource. There must be something wrong with your SQL.

Categories