Can't retrieve DB info - php

I need help figuring out why the following DB Query is not working. I know the DB connection is good. I also know the $referralname = $_SESSION['user_name']; is correctly rendering. It has to be something with my code.
I am getting the following errors. Maybe this will help to figure this out.
[12-Jun-2013 21:13:54 America/New_York] PHP Warning: mysql_query() expects parameter 1 to be string, object given in /x/x/public_html/americansolar/partner/classes/Referral.php on line 89
[12-Jun-2013 21:13:54 America/New_York] PHP Warning: mysql_num_rows() expects parameter 1 to be resource, null given in /x/x/public_html/americansolar/partner/classes/Referral.php on line 90
P.S. I am not sure if the while statement is necessary or not since it will always only return one result???
My Code:
// creating a database connection
$this->db_connection = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
// if no connection errors (= working database connection)
if (!$this->db_connection->connect_errno) {
$referralname = $_SESSION['user_name'];
// get the referrer's id
$query_get_referral_id = $this->db_connection->query("SELECT * From users WHERE user_name = '".$referralname."';");
$result = MYSQL_QUERY($query_get_referral_id);
$numberOfRows = MYSQL_NUM_ROWS($result);
$i = 0;
while ($i<$numberOfRows)
{
$thisId = MYSQL_RESULT($result,$i,"user_id");
$i++;
}
}
My Solution:
$query_get_referral_id = $this->db_connection->query("SELECT * From users WHERE user_name = '".$referralname."';");
while($row = mysqli_fetch_array($query_get_referral_id))
{
$thisId = $row['user_id'];
}

Youre mixing mysqli and mysql... they are two completely different and incompatible interfaces. Secondly, your $query_get_referral_id is not an id value... it is a mysqli_result object. You need to then extract the value from that object.
And lastly... DONT use mysql... stick with mysqli, or use PDO
Also you should use a prepared statement for this:
$stmt = $this->db_connection->query("SELECT user_id From users WHERE user_name = ?");
$stmt->bind_param('s', $referralname);
$stmt->execute();
if($stmt->num_rows) {
$stmt->bind_result($userId);
while($stmt->fetch()) {
// do something with $userId...
// each iteration of this loop is a
// row of the result set, it will automatically
// load the value of the user_id into $userId
}
}

I donot think you should query like
$query_get_referral_id = $this->db_connection->query("SELECT * From users WHERE user_name = '".$referralname."';");
$result = MYSQL_QUERY($query_get_referral_id);
Well, you should go
$result = $this->db_connection->query("SELECT * From users WHERE user_name = '".$referralname."';");

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);

MySQLi - Get table value as string instead of object

I'm trying to use php to retrieve both the name and userEmail values from my Users MySQL table seen here:
I'm using the following code in attempt to grab the currently logged-in user's name and userEmail:
<?php
session_start();
#connect to MySQL database
require_once("settings.php");
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
#get username of current session
$username = $_SESSION['username'];
#get userEmail of logged-in user from database
$sql = "SELECT userEmail from Users WHERE username LIKE '{$username}' LIMIT 1";
$result = $mysqli->query($sql);
$replyTo = mysqli_fetch_field($result);
#get name of logged-in user from database
$sql2 = "SELECT name from Users WHERE username LIKE '{$username}' LIMIT 1";
$result2 = $mysqli->query($sql2);
$name = mysqli_fetch_field($result2);
?>
Then I try passing the $replyTo and $name values into a function that only accepts strings (the setFrom() function from PHPmailer to be precise):
$mail->setFrom($replyTo, $name);
...and get the following errors:
Warning: trim() expects parameter 1 to be string, object given in /var/www/phpmailer/class.phpmailer.php on line 489 (this object was $replyTo)
Catchable fatal error: Object of class stdClass could not be converted to string in /var/www/phpmailer/class.phpmailer.php on line 490 (this object was $name)
Using Chrome Logger to debug, I found these to be the values of $userEmail and $name:
I think you can get email and name with single query - make use of prepared statement for security reason(SQLIA)
#get userEmail of logged-in user from database
$sql = "SELECT userEmail,name from Users WHERE username = ? LIMIT 1";
// this is prepared statement and prevent form sql injection attack
$statement = $mysqli->prepare($sql);
$statement->bind_param('s',$username);
$statement->execute();
$result = $statement->get_result();
// fetch first record in associative array
$userDetail = $result->fetch_assoc();
if($userDetail)
{
$replyTo = $userDetail['userEmail'];
$name = $uerDetail['name'];
$mail->setFrom($replyTo, $name);
}
else
{
echo 'user not found';
}

Error in connection database using pdo

I change the simple SQL query to pdo.now when I click on the log in button I got this error:
Undefined variable: row in /var/www/login.php on line 16
Notice: Undefined variable: result in /var/www/login.php on line 17
Warning: mysql_num_rows() expects parameter 1 to be resource, null given in /var/www/login.php on line 17 Your Login Name or Password is invalid
Code:
<?php
error_reporting(E_ALL);
ini_set('display_errors','5');
include("conn.php");
session_start();
if($_SERVER["REQUEST_METHOD"] == "POST")
{
// username and password sent from Form
$u_name=addslashes($_POST['username']);
$password=addslashes($_POST['password']);
$sql="SELECT id FROM admin WHERE username='$u_name' and password='$password'";
$q = $conn->query($sql) or die("failed!");
$r = $q->fetch(PDO::FETCH_ASSOC);
$active=$row['active'];
$count=mysql_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row
if($count==1)
{
session_register("u_name");
$_SESSION['login_user']=$u_name;
header("location: main.php");
}
else
{
echo ("Your Login Name or Password is invalid");
}
}
?>
mysql_num_rows is a function, that is a part of the deprecated mysql_* extension. Just check the PDO manual here, and see how you can get the num-rows using PDO. You simply cannot use PDO and mysql(i)_* all together willy-nilly
You have many, many other issues in your code, including the query itself: SELECT id FROM will return a resultset in which each row has but a single column, called ID, but you go on to access $row['active']; in your code. That will issue a notice, because the index cannot be found.
Change the query to select all fields you actually do require SELECT id, active FROM... is the bare minimum, based on your code here.
Besides that, you're also wildly inconsistent as far as variable names go. What you call $r changes to $row the very next line... that's what's causing the undefined variable notices, of course.
You also have an injection vulnerability that is quite substantial, Here's how I'd query your data:
$stmt = $conn->prepare('SELECT id, active FROM admin where username = :user AND password = :pass');
$stmt->execute(array(
':user' => $_POST['username'],
':pass' => $_POST['password']
));
//$rowCount = $stmt->rowCount(); <-- only for update, delete or insert queries
$rowCount = 0;
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
++$rowCount;//count while fetching
//process row
}
//or
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
$rowCount = count($rows);
foreach($rows as $row)
{
//process row
}
That said, you really should learn about prepared statements and hash your passwords
The $r = $q->fetch(PDO::FETCH_ASSOC); should be $row = $q->fetch(PDO::FETCH_ASSOC);
Also, the session_register() function is deprecated. You shouldn't be using that.

MySQL Query using escaped $_SESSION var returns boolean?

I'm having a little bit of trouble. I need to return a set of data in a table.
Quickly here is the table structure -
DB ->
users -> user_id , user_name , user_pass , user_email ;
urls -> user_id , url , title ;
On the page I have the currently logged in users, user_id inside a $_SESSION variable - SESSION 'user_id'. I need to return all the (url)s inside the urls table that have the same matching user_id as the one set in the SESSION variable. Here's the code I have and it almost works, but says when I'm trying to fetch an array it is getting a boolean from $results. Any help will be greatly appreciated! The last line print_r is there just to see what is being returned.
$mysqli = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME);
$sql = "SELECT * FROM url WHERE user_id = ";
$sql .= mysqli_real_escape_string($mysqli, $_SESSION['user_id']);
$result = mysqli_query($mysqli, $sql);
$row = mysqli_fetch_array($result, MYSQLI_NUM);
print_r($row);
Here is the error I am getting -
Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in C:\xampp\htdocs\practice\include\feed.php on line 10
Line 10 is this line...
$row = mysqli_fetch_array($result, MYSQLI_NUM);
Thanks again!
try
$mysqli = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME);
$escapedID = mysqli_real_escape_string($mysqli, $_SESSION['user_id']);
$sql = "SELECT * FROM url WHERE user_id = '".$escapedID."'";
$result = mysqli_query($mysqli, $sql);
$row = mysqli_fetch_array($result, MYSQLI_NUM);
print_r($row);
mysqli_query() returns FALSE on failure. See the documentation here. The query is might be failing because you've written "url" in the FROM clause; you have the table name listed as "urls" above.

MySQLi Query will not execute

I am playing around with this trying to pull some articles from a database.
Here is the code i have so far: ($host etc are defined in config)
include ("admin/config.php");
$mysqli = mysqli_connect($host, $user , $pass , $database);
$query = "SELECT * FROM articles ORDER BY date LIMIT 5";
$result = mysqli_query($mysqli,$query);
while($row = mysqli_fetch_array($result))
{
Some code to display results
}
This is the error that gets generated but i just cant see what i am doing wrong. Any help will be much appreciated.
Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in /website....
there is error in your query.
to get it always run all your queries this way
$result = mysqli_query($mysqli,$query) or trigger_error($mysqli->error."[$query]");

Categories