mysqli query not working when variable inserted - php

I need an extra pair of eyes! I have a super-simple query:
$result = $mysqli->query("SELECT post_id FROM blog_posts WHERE post_uri = 'the-test-post' LIMIT 1");
$row = $result->fetch_array();
and this gives me the post_id. However, if I insert a variable for post_uri, the result is empty. Ways I tried of which none worked:
$result = $mysqli->query("SELECT post_id FROM blog_posts WHERE post_uri = '".$post_uri."' LIMIT 1");
$result = $mysqli->query("SELECT post_id FROM blog_posts WHERE post_uri = ".$post_uri." LIMIT 1");
$result = $mysqli->query("SELECT post_id FROM blog_posts WHERE post_uri = $post_uri LIMIT 1");
I have similar query on another page working just right, so that confuses me even more. Help appreciated.

You are slapping a variable directly into a query. This is error prone (as you are discovering) and has a high risk that you'll fail to sufficiently sanitise it (and thus cause an SQL injection vulnerability).
Use the PDO layer and bound variables.

If you put that query in a string and echo it, you can check what happens. There might be something wrong with that variable!
echo "SELECT post_id FROM blog_posts WHERE post_uri = '".$post_uri."' LIMIT 1";
And so on. I'll bet there's either nothing, or something you're not expecting in that $post_uri, because it shouldn't matter to mysql how you've build your query.

I had a similar problem. Your syntax looks fine. Try to use a simple version of the
db connection call. Below are compared the version that worked (above) to the one
that failed (below).
$sqli = new mysqli('localhost', 'my_user', 'my_password', 'my_db');
$mysqli->real_connect('localhost', 'my_user', 'my_password', 'my_db')
I had use a variable in my query and had a $mysqli->real_connect db connection.
That would not work. But when I switched to the new mysqli type I was surprised
that the variable query did work.
I hope that works out for you.

Related

select sql row using pdo with where statement

This is my first time to try PDO and still learning it. I am more familiar in using mysql or mysqli in developing php system.
After deep searching and searching I still can't seem to understand how to query using PDO
In my code I used mysqli inside a function to be called in index.php
function getUsery(){
$ip = getIPAddress();
$query = mysqli_query("select userID from tblUsers where logged='1' AND ip='$ip'");
$row = mysqli_fetch_array($query);
$emp = $row['userID'];
$logged = $row['logged'];
$userlvl = $row['userLevel'];
$_SESSION['logged'] = $logged;
$_SESSION['userLevel'] = $userlvl;
return $emp;
}
I don't really know how to select sql query using PDO with 'where' statement. Most of what I found is using array with no 'where' statement
How can I select the userID where logged is equal to '1' and ip is equal to the computer's ip address and return and display the result to the index.php
There's SQL statement with WHERE in PDO
$sql = "SELECT * FROM Users
WHERE userID = ?";
$result = $pdo->prepare($sql);
$result->execute([$id]);
Assuming that you know how to connect database using PDO, here is how to select SQL with PDO.
$stmt = $db->prepare("select userID from tblUsers where logged = '1' AND ip = :ip");
$stmt->execute(array('ip' => $ip));
$listArray = $stmt->fetchAll();
Notice the :ip at the end of SELECT. If you don't use ? as a parameters, the prefix : is mandatory and the word after that should be the same as the key in the execute function.
EDIT
In case that the above code is inside the function and $db is outside the function, declare $db as global variable inside the function.
This one is imo one of best guides on PDO and how to use it:
https://phpdelusions.net/pdo
WHERE is a part of query and queries in PDO are not much different from pure *sql queries, just there is going on a bit filtering on execution. Read the guide carefully and you will be able to execute any query you need to.

SQL and PHP brief explain

$id=$_GET['previd'];
$SQL = "select * from pro where prId=".$id;
I am new to PHP. Can anyone explain what happens here?
This is taking the value of the GET (url) passed variable "previd".
Something like http://example.com/page.php?previd=123 would set
previd to 123.
Next it sets the variable $id to 123.
Next $SQL gets set to select * from pro where prId=123
Next a nefarious person can go to http://example.com/page.php?previd=;DROP TABLE pro and your database has now been deleted.
This is why people use sanitization and prepared statements.
// PDO + MySQL
$pdo = new PDO('mysql:host=example.com;dbname=database', 'user', 'password');
$statement = $pdo->query("SELECT some_field FROM some_table");
$row = $statement->fetch(PDO::FETCH_ASSOC);
echo htmlentities($row['some_field']);
More Info

How to prepare statement with mysqli for select query

I am very worried about sql injection. I have been reading up about it and been trying to prepare the following query:
$query_AcousticDB = "SELECT * FROM products WHERE Category = 'Acoustic ' ORDER BY RAND()";
$AcousticDB = mysqli_query($DB, $query_AcousticDB) or die(mysqli_connect_error());
$row_AcousticDB = mysqli_fetch_assoc($AcousticDB);
$totalRows_AcousticDB = mysqli_num_rows($AcousticDB);
which works great.
I thought that I only have to change to the following:
$query_AcousticDB = prepare("SELECT * FROM products WHERE Category = 'Acoustic ' ORDER BY RAND()");
However this doesn't work. I get the following error:Call to undefined function prepare()
I still would like to get my values as:<?php echo $row_AcousticDB['what ever']; ?>
Can somebody point me into the right direction?
How about this?
$category = "Acoustic";
$sql = "SELECT * FROM products WHERE Category = ? ORDER BY RAND()";
$stmt = $DB->prepare($sql);
$stmt->bind_param('s', $category);
$stmt->execute();
$row_AcousticDB = $stmt->get_result(); // altenative: $stmt->bind_result($row_AcousticDB);
$row_AcousticDB->fetch_array(MYSQLI_ASSOC)
If you let the user enter any data (in text boxes on website) or you pull anything out of database for use (risk of second order injection) make sure you sanitize it (cleanse it of any nasty tags like < or >) by using htmlspecialchars($category) or htmlentities($category).
With this method implemented into your code, you will be reasonably safe from SQL Injection :)
Try to make this variable global: Put this on the upper part of your script global $acousticDB; or else you may try this $acoustic='';

mysqli prepared statement without bind_param

I have this code for selecting fname from the latest record on the user table.
$mysqli = new mysqli(HOST, USER, PASSWORD, DATABASE);
$sdt=$mysqli->('SELECT fname FROM user ORDER BY id DESC LIMIT 1');
$sdt->bind_result($code);
$sdt->fetch();
echo $code ;
I used prepared statement with bind_param earlier, but for now in the above code for first time I want to use prepared statement without binding parameters and I do not know how to select from table without using bind_param(). How to do that?
If, like in your case, there is nothing to bind, then just use query()
$res = $mysqli->query('SELECT fname FROM user ORDER BY id DESC LIMIT 1');
$fname = $res->fetch_row()[0] ?? false;
But if even a single variable is going to be used in the query, then you must substitute it with a placeholder and therefore prepare your query.
However, in 2022 and beyond, (starting PHP 8.1) you can indeed skip bind_param even for a prepared query, sending variables directly to execute(), in the form of array:
$query = "SELECT * FROM `customers` WHERE `Customer_ID`=?";
$stmt = $db->prepare($query);
$stmt->execute([$_POST['ID']]);
$result = $stmt->get_result();
$row = $result->fetch_assoc();
The answer ticked is open to SQL injection. What is the point of using a prepared statement and not correctly preparing the data. You should never just put a string in the query line. The point of a prepared statement is that it is prepared. Here is one example
$query = "SELECT `Customer_ID`,`CompanyName` FROM `customers` WHERE `Customer_ID`=?";
$stmt = $db->prepare($query);
$stmt->bind_param('i',$_POST['ID']);
$stmt->execute();
$stmt->bind_result($id,$CompanyName);
In Raffi's code you should do this
$bla = $_POST['something'];
$mysqli = new mysqli(HOST, USER, PASSWORD, DATABASE);
$stmt = $mysqli->prepare("SELECT `fname` FROM `user` WHERE `bla` = ? ORDER BY `id` DESC LIMIT 1");
$stmt->bind_param('s',$_POST['something']);
$stmt->execute();
$stmt->bind_result($code);
$stmt->fetch();
echo $code;
Please be aware I don't know if your post data is a string or an integer. If it was an integer you would put
$stmt->bind_param('i',$_POST['something']);
instead. I know you were saying without bind param, but trust me that is really really bad if you are taking in input from a page, and not preparing it correctly first.

What should we use object scope like "--->" in PHP?

I am following through this tutorial
http://www.1stwebdesigner.com/tutorials/infinite-scrolling-tutorial/
And it contains this code snippet:
<!--?php
$con = mysql_connect("localhost", "username", "password");
mysql_select_db("database_name");
$result = mysql_query("select SQL_CALC_FOUND_ROWS * from scroll_images order by id asc limit 12");
$row_object = mysql_query("Select Found_Rows() as rowcount");
$row_object = mysql_fetch_object($row_object);
$actual_row_count = $row_object--->rowcount;
?>
The line $actual_row_count = $row_object--->rowcount; confuses me, what is --->rowcount supposed to do? When I have it in my PHP, I receive errors.
<?php
$sql_fetch = "SELECT * FROM articles ORDER BY time DESC limit 4;";
$dbresult = mysqli_query( $db, $sql_fetch );
$row_object = mysqli_query( $db, "Select Found_Rows() as rowcount" );
$row_object = mysqli_fetch_object( $row_object );
$actual_row_count = $row_object--->rowcount;
?>
Parse error: syntax error, unexpected T_OBJECT_OPERATOR in /Applications/MAMP/htdocs/index.php on line 14
<!-- Comment --> is the way you comment out things in HTML. That line is indeed not correct (stop reading the article this instant).
I would imagine that he meant
<?php
$con = mysql_connect("localhost", "username", "password");
mysql_select_db("database_name");
$result = mysql_query("select SQL_CALC_FOUND_ROWS * from scroll_images order by id asc limit 12");
$row_object = mysql_query("Select Found_Rows() as rowcount");
$row_object = mysql_fetch_object($row_object);
$actual_row_count = $row_object->rowcount;
?>
On a different note:
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
I imagine it is suppose to be
$actual_row_count = $row_object->rowcount;
But that's not how you get the number of rows for mysqli.
So what ever that code is, it is pretty much 100% wrong.
It is just a mistake. Replace <!--?php with <?php and $row_object--->rowcount; with $row_object->rowcount;
---> itself doenst do anything.
--> is used to close HTML comment (that you start on row1 with
-> is used to get the instance of an object (in your case, $row_object->rowcount)
---> is not an actual operator. The actual operator you need is -> lamely called, the "arrow operator", or T_OBJECT_OPERATOR.
Evaluating that php would result in -
$actual_row_count = $rowobject-- (which means decrement by 1)->rowcount;
which is not correct PHP as you can only use the arrow operator on an object, not an integer, which is what the "$rowobject--" would evaluate to. This explains your unexpected "T_OBJECT_OPERATOR".
What you are experiencing is poor php engineering. Change it to
$actual_row_count = $rowobject->rowcount
and your PHP will be set. Refer to other answers for the rest
It's trying to get an instance of an object, just not correctly. Try this instead:
$row_object->rowcount
Its just wrong by user instead of
$rowobject--->rowcount;
Replace to
$rowobject->rowcount

Categories