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);
Related
This question already has an answer here:
PDO fetch returns only first row
(1 answer)
Closed 2 years ago.
A table called "checks" has fields ID;email;pass;entered;firstname;lastname;trading.
The only code in this test is the DB connection and the new PDO connection made prior to these snippets. The following snippet reports correctly that there are 5 users in the table "checks".
$sql = "SELECT COUNT(*) AS num FROM checks";
$stmt = $conn->prepare($sql);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
echo '<br>' . $row['num'] . ' users exist.';
This snippet which follows immediately after the above doesn't show the expected result.
$sql = "SELECT * FROM checks";
$stmt = $conn->prepare($sql);
$stmt->execute($id);
$users = $stmt->fetch(PDO::FETCH_ASSOC);
print_r($users);
The print_r statement results in the first array being printed correctly with all fields/contents correctly displayed.
On the next line it prints only the email field contents from each row as a single string!
I'm probably missing something obvious but I just can't spot it. Help please?
PDO::fetch() returns a single row from the result set. You need PDO::fetchAll() instead.
$sql = "SELECT * FROM checks";
$stmt = $conn->prepare($sql);
$stmt->execute();
$users = $stmt->fetchAll(PDO::FETCH_ASSOC); // <--- here
This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Closed 3 years ago.
I tried various ways to get the id from database but I can't get that Please help me!
Below is my query :
$username = $_POST['username'];
$query = "SELECT id FROM wp_users WHERE user_login ='".$username."'";
$result=mysqli_query($conn, $query);
if(mysqli_num_rows($result) == 1)
{
while($row = mysqli_fetch_array($result))
{
$id = $row['id'];
}
}
echo $id;
Also I tried this:
$query = "SELECT id FROM wp_users WHERE user_login ='$username'";
You should, at the very least, be using prepared statements in your queries if you're passing them user-supplied data.
use prepared statements ? and bind_param
use bind_result to bind the column to a variable. This variable is now bound by reference which means it will be updated on every iteration of the loop.
it is important to realize that you want to access the $id variable inside the loop as you're iterating over the dataset. If you use it outside/below the loop you are only working with the final row of data because it is being overwritten on every iteration.
turn on error reporting
Finally, I left your loop in place but usually, you'd only have a single user for a given username so you could use mysqli_fetch_assoc - Single Result from Database by using mySQLi
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$username = $_POST['username'];
$query = "SELECT id FROM wp_users WHERE user_login = ?";
$stmt = $conn->prepare($query);
$stmt->bind_param('s', $username);
$stmt->execute();
$stmt->bind_result($id);
while ($stmt->fetch()) {
echo "ID: $id\n";
}
$stmt->close();
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.
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
This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 9 years ago.
Trying to get the data from a table in my database and store it into a textfield named "about"
however i keep getting an error:
Warning: mysql_fetch_assoc() expects parameter 1 to be resource, object given in
<?php
require("common.php");
$query = $db->prepare("SELECT * FROM about");
$result = $query or die(mysql_error()); // run the query
$row = mysql_fetch_assoc($result); // fetch a result row
echo $row['about'];
?>
thats because you are not executing your query.after Prepare use Execute().your code will look something like this
<?php
require("common.php");
$query = $db->prepare("SELECT * FROM about");
$query->execute();
$result = $query->fetch(PDO::FETCH_ASSOC);
print_r($result);//to check the elements of the array
echo $row['content'];
?>
Remember
PDO::prepare() - Prepares a statement for execution and returns a statement object
PDOStatement::execute() - Executes a prepared statement
You are missing mysql_query();. This to execute your sql query.
$query = "SELECT * FROM about";
$result = mysql_query($query) or die(mysql_error());