SQL Variable Inserting INSIDE mysql_query - php

I am trying to make a price slider with PHP and SQL , but i have a problem when i have some problem in this code
$query = mysql_query("SELECT * FROM price WHERE phone_price BETWEEN" .$from. "AND" .$to. );
while($row = mysql_fetch_array($query)){
print $row['phone_name'];
print $row['phone_price'];
print '';
}
I want to run the SQL query like SELECT * FROM price WHERE phone_price BETWEEN 300 AND 500
I am making a beta version therefore i am accepting the $from and $to values from <input> , i think i am making the error in inserting the variable in mysql_query .
THE ERROR -Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\login\slide\slide.php on line 28

You have a mistake in your query. Spaces needed after BETWEEN and AND. Otherwise php reads your query like ...BETWEEN123AND1234.... And you should better use quotes to place vars:
$query = mysql_query("SELECT * FROM `price` WHERE `phone_price` BETWEEN '".$from."' AND '".$to."'");

Use PDO build-In object. mysql_ functions were deprecated.
Initialize connection.
$dsn = "mysql:host=localhost;dbname=my_database";
$pdo = new PDO($dsn, $login, $password);
Use prepare statement.
$sh = $pdo->prepare("SELECT * FROM price WHERE phone_price BETWEEN :from AND :to");
Bind values and value types.
$sh->bindParam(':from',$from,PDO::PARAM_INT);
$sh->bindParam(':to',$to,PDO::PARAM_INT);
Fetch results into assoc array.
$res = $sh->fetch_all(PDO::FETCH_ASSOC);
Good Luck

Related

Warning: mysqli_query() expects parameter 2 to be string, object given [duplicate]

This question already has answers here:
Warning: mysqli_query() expects parameter 2 to be string, object given in
(2 answers)
Closed 3 years ago.
Can anyone help me with this error:
Warning: mysqli_query() expects parameter 2 to be string, object given .. on line 25.
<?php
session_start();
include('includes/dbcon.php');
$query = mysqli_query($con, "SELECT * FROM reservation WHERE r_date='".$date."'
if (!mysqli_query($con,$query))
{
$query = mysqli_query($con, "SELECT * FROM combo where combo_id=1");
$row=mysqli_fetch_array($query);
$price=$row['combo_price'];
$payable=$pax*$price;
<?php
session_start();
include('includes/dbcon.php');
// you're missing some syntax here..
// also your $query IS your query so it should be $query = "SELECT * FROM ";
$query = mysqli_query($con, "SELECT * FROM reservation WHERE r_date='".$date."'
// you don't need this above line.. it does it all right here...
if (!mysqli_query($con,$query))
{
$query = mysqli_query($con, "SELECT * FROM combo where combo_id=1");
$row=mysqli_fetch_array($query);
$price=$row['combo_price'];
$payable=$pax*$price;
// missing closing brackets. }
Your code has multiple problems. Missing ;, repeated calls to mysqli_query, SQL injection and no error checking.
Instead of checking whether the query was successful with if enable exceptions at the top of your file. Use prepared statements, preferably in object-oriented way.
session_start();
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); // this line enables exceptions
include 'includes/dbcon.php';
$stmt = $con->prepare('SELECT * FROM reservation WHERE r_date=?'); // ? is a placeholder for binding data
$stmt->bind_param('s', $date); // bind data to SQL statement as a string(s)
$stmt->execute();
$reservations = $stmt->get_result();
// if your SELECT found some record then loop on the result set fetching each row one by one
while ($row = $reservations->fetch_assoc()) {
$combos = $con->query("SELECT * FROM combo where combo_id=1"); // if there is no data to be bound then we can use query
$row = $combos->fetch_assoc(); // fetch the matching combo row
$price = $row['combo_price'];
$payable = $pax * $price;
}
Your variable named query should only be your... query
$result = mysqli_query($con, "SELECT * FROM reservation WHERE r_date='".$date."'";
Also even if you think you will get back a record, function mysqli_fetch_array
will always return an array. So you need to select the first item in the array and then the key or index.
$price = $row[0]['combo_price'];
Some code practices. Don't put everything inside your IF. Because if it fails $payable will be undefined and throw an error. Initialize it on top of your script. Also you need to store the return value of mysqli_query as you need to free the memory used for it.
mysqli_free_result($result);

Using PHP variable in SQL query

I'm having some trouble using a variable declared in PHP with an SQL query. I have used the resources at How to include a PHP variable inside a MySQL insert statement but have had no luck with them. I realize this is prone to SQL injection and if someone wants to show me how to protect against that, I will gladly implement that. (I think by using mysql_real_escape_string but that may be deprecated?)
<?php
$q = 'Hospital_Name';
$query = "SELECT * FROM database.table WHERE field_name = 'hospital_name' AND value = '$q'";
$query_result = mysqli_query($conn, $query);
while ($row = mysqli_fetch_assoc($query_result)) {
echo $row['value'];
}
?>
I have tried switching '$q' with $q and that doesn't work. If I substitute the hospital name directly into the query, the SQL query and PHP output code works so I know that's not the problem unless for some reason it uses different logic with a variable when connecting to the database and executing the query.
Thank you in advance.
Edit: I'll go ahead and post more of my actual code instead of just the problem areas since unfortunately none of the answers provided have worked. I am trying to print out a "Case ID" that is the primary key tied to a patient. I am using a REDCap clinical database and their table structure is a little different than normal relational databases. My code is as follows:
<?php
$q = 'Hospital_Name';
$query = "SELECT * FROM database.table WHERE field_name = 'case_id' AND record in (SELECT distinct record FROM database.table WHERE field_name = 'hospital_name' AND value = '$q')";
$query_result = mysqli_query($conn, $query);
while ($row = mysqli_fetch_assoc($query_result)) {
echo $row['value'];
}
?>
I have tried substituting $q with '$q' and '".$q."' and none of those print out the case_id that I need. I also tried using the mysqli_stmt_* functions but they printed nothing but blank as well. Our server uses PHP version 5.3.3 if that is helpful.
Thanks again.
Do it like so
<?php
$q = 'mercy_west';
$query = "SELECT col1,col2,col3,col4 FROM database.table WHERE field_name = 'hospital_name' AND value = ?";
if($stmt = $db->query($query)){
$stmt->bind_param("s",$q); // s is for string, i for integer, number of these must match your ? marks in query. Then variable you're binding is the $q, Must match number of ? as well
$stmt->execute();
$stmt->bind_result($col1,$col2,$col3,$col4); // Can initialize these above with $col1 = "", but these bind what you're selecting. If you select 5 times, must have 5 variables, and they go in in order. select id,name, bind_result($id,name)
$stmt->store_result();
while($stmt->fetch()){ // fetch the results
echo $col1;
}
$stmt->close();
}
?>
Yes mysql_real_escape_string() is deprecated.
One solution, as hinted by answers like this one in that post you included a link to, is to use prepared statements. MySQLi and PDO both support binding parameters with prepared statements.
To continue using the mysqli_* functions, use:
mysqli_prepare() to get a prepared statement
mysqli_stmt_bind_param() to bind the parameter (e.g. for the WHERE condition value='$q')
mysqli_stmt_execute() to execute the statement
mysqli_stmt_bind_result() to send the output to a variable.
<?php
$q = 'Hospital_Name';
$query = "SELECT value FROM database.table WHERE field_name = 'hospital_name' AND value = ?";
$statement = mysqli_prepare($conn, $query);
//Bind parameter for $q; substituted for first ? in $query
//first parameter: 's' -> string
mysqli_stmt_bind_param($statement, 's', $q);
//execute the statement
mysqli_stmt_execute($statement);
//bind an output variable
mysqli_stmt_bind_result($stmt, $value);
while ( mysqli_stmt_fetch($stmt)) {
echo $value; //print the value from each returned row
}
If you consider using PDO, look at bindparam(). You will need to determine the parameters for the PDO constructor but then can use it to get prepared statements with the prepare() method.

Using a variable as parameter in mysql

I have written a method to get a value out of a database based on an id.
I would like to use the variable id as a parameter in mysql but I can't get it to work.
Here is my code:
function get_color_by_id($id) {
$mysqli = new mysqli("localhost", "root", "usbw", "ipadshop", 3307);
if($mysqli->connect_errno){
die("Connection error: " . $mysqli->connect_error);
}
set #id := $id;
$result = $mysqli->query('SELECT kleur FROM kleur WHERE id=',#id);
if(!$result){
die('Query error: ' . $mysqli->error);
}
while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
return $row;
}
}
PHP is not SQL; and SQL code should not be expected to work in a PHP context. The procedural SQLish syntax (set #id := $id) is thus invalid in context, as is the #id expression used later.
As shown here (and updated for this question), the correct way to use parameters in mysqli is with prepare, bind_param, and execute.
$stmt = $mysqli->prepare('SELECT kleur FROM kleur WHERE id = ?');
$stmt->bind_param('i', $id); // assuming $id represents an integer
$result = $stmt->execute();
Since bind_param uses reference calling semantics, the variables used should not be re-assigned once bound to avoid potential confusion.
Also, it can be confusing to give the same names to columns and tables; my preference is to use plural names for tables/relations, and to refine the column names more. Consider a query with different names chosen;
SELECT kleurNaam FROM kleuren WHERE id = ?
-- or in English
SELECT colorName FROM colors WHERE id = ?
Easier to read, no?

unable to execute update statement in while loop php mysqli

I have the following query
$products = $this->mysqliengine->query("select * from temp_all_product where download_status = 0") or die($this->mysqliengine->error());
$temp_status_update = $this->mysqliengine->prepare("update temp_all_product set download_status = ? where id = ?") or die($this->mysqliengine->error);
$temp_status_update->bind_result($download_status, $id);
while($product = $products->fetch_assoc()) {
$id = $product['id'];
$download_status = 1;
$temp_status_update->execute();
}
In the above statement I can select the values from temp table but unable to update the status. What is the problem here
You need to use bind_param in your update statement instead of bind_result.
$temp_status_update->bind_param('dd', $download_status, $id);
The 'dd' just tells the system that each input is a number.
http://www.php.net/manual/en/mysqli-stmt.bind-param.php
#eggyal was merely suggesting that you could replace all your code with a single update statement. Your remark about LIMIT does not make much sense.
Suggestion: If you don't have much invested in mysqli then switch to PDO. It allows using named parameters which can make your code more robust and easier to maintain:
$sql = "UPDATE temp_all_product SET download_status = :status where id = :id";
$stmt = $pdo->prepare($sql);
$stmt->execute(array('status' => 1, 'id' => $product['id']));
Plus you can configure it to throw exceptions so you don't need all this error checking.
http://www.php.net/manual/en/book.pdo.php
http://net.tutsplus.com/tutorials/php/pdo-vs-mysqli-which-should-you-use/

PDO Database access WHERE title = $title

I'm trying to learn to use PDO instead of MySQLi for database access and I'm having trouble selecting data from the database. I want to use:
$STH = $DBH->query('SELECT * FROM ratings WHERE title=$title ORDER BY date ASC');
$STH->setFetchMode(PDO::FETCH_ASSOC);
while($row = $STH->fetch()) {
echo $row['title'];
}
but I'm getting this error:
Fatal error: Call to a member function setFetchMode() on a
non-object in
/home/owencont/public_html/owenstest.com/ratemystudents/index.php
on line 6
If I take out the WHERE statement it works fine. How can I select a row based on if it's value matches a variable?
Thanks,
Owen
It's likely a SQL syntax error, because you forgot to quote $title. It ended up as bareword in the query (also not even interpolated as string), resulting in an error. And your PDO connection was not configured to report errors. Use ->quote() on arguments before the ->query():
$title = $DBH->quote($title);
$STH = $DBH->query("SELECT * FROM ratings WHERE title=$title ");
Or better yet, use parameterized SQL:
$STH = $DBH->prepare("SELECT * FROM ratings WHERE title=? ");
$STH->execute(array($title));
Take a look at PDO::prepare and PDOStatement::execute. The safest way to add user content to a query is to prepare a basic statement and bind the parameter to it. Example (note the question mark in the SQL statement):
$STH = $DBH->query('SELECT * FROM ratings WHERE title=? ORDER BY date ASC');
$STH->execute( array( $title ) );
while( $row = $STH->fetch( PDO::FETCH_ASSOC ) );
Make PDO throw errors so you can see what exactly goes wrong. See How to squeeze error message out of PDO?
You are probably missing quotes around $title but this scenario really calls for prepared statements instead.
remove the variable out of the sql statement because its a php variable
$STH = $DBH->query('SELECT * FROM ratings WHERE title=' . $title . 'ORDER BY date ASC');
Use double quotes instead of single quotes as a parameter of the query-method.
The reason you're getting this error is because the query-method fails and so the $STH object isn't created. You should implement some error handling.

Categories