I was advised to update my code to prevent sql injections. So here is what I have.
VARIABLE FROM URL
$Idarticle = "5-6142-8906-6641";
THIS WORKS - OLD
$sql2 = "SELECT * FROM articles WHERE IDArticle IN ('{$Idarticle}')";
$results2 = $conn->query($sql2);
$row2 = $results2->fetch_assoc();
THIS DOES NOT WORK - NEW
$sql2 = "SELECT * FROM articles WHERE IDArticle IN ( ? )";
if ($stmt = $conn->prepare($sql2)) {
$stmt->bind_param("s", $Idarticle);
$stmt->execute();
$row2 = $stmt->fetch();
}
MY CONNECTION SCRIPT
$conn = new mysqli($servername, $username, $password, $db);
In the second example I get no results(no errors either) verses in the first it finds the correct row. I have read numerous similar questions previously asked and while there may be an answer out there, I did not find it. I also tried some of those answers without any success. I appreciate any help.
UPDATED CODE PER COMMENTS
$sql2 = "SELECT * FROM articles WHERE IDArticle = ?";
if (!$stmt = $conn->prepare($sql2)) {
if (!$stmt->bind_param("s", $Idarticle));
echo "error: " . $stmt->error;
if (!$stmt->execute());
echo "error: " . $stmt->error;
$row2 = $stmt->fetch();
}
Still not finding the record / no errors being reported
MY SOLUTION
Having spent close to two days researching and trying to solve this issue, I decided mysqli was at the heart of the problem. Why I am sure this issue does have a solution with mysqli, I ended up moving to PDO. I resisted doing this initially but after a few hours of study, it is in my opinion, as well as many others, far better. Bottom line it now works flawlessly with very few changes. My recommendation, If you are struggling with mysqli, switch to PDO.
A BIG THANK YOU TO THOSE WHO TRIED TO HELP
BTW: Is there any special reason for using IN?
"SELECT * FROM articles WHERE IDArticle = ?"
This is your problem:
$row2 = $stmt->fetch();
mysqli_stmt::fetch returns boolean true/false on success, and you're trying to use it as an array for row2
You must bind your results first with mysqli_stmt::bind_result, and then fetch
See this creative answer for how to get an associative array from bind_result
Preferably, if you have the MySQL native driver installed, then you can extract this directly with mysqli_stmt::get_result
Also, you're not checking for statement errors.
if ( !$stmt->bind_param("s", $Idarticle) )
echo "error: " . $stmt->error;
if ( !$stmt->execute() )
echo "error: " . $stmt->error;
And you should make sure you're using PHP error reporting.
If $results1/$results2 is not a typo, then the new code is very different, because there must be two independent queries.
$sql2 = "SELECT * FROM articles WHERE IDArticle IN ( ? )";
if ($stmt = $conn->prepare($sql2)) {
$stmt->bind_param("s", $Idarticle);
$stmt->execute();
}
But it's not clear then what was done with $results2 later in the code. row2 might be totally unrelated to
$row2 = $results1->fetch_assoc();
Related
This question already has answers here:
Retrieve the ID of an inserted record: Php & MS SQL SERVER
(4 answers)
Closed 2 years ago.
I know there are similar questions to this, and I've tried various examples but I seem to be missing something.
I'm using PHP to insert a record in a MS SQL table, code as follows...
$sql = "Insert into MyTable (column1,column2,column3) VALUES (? , ? , ?);";
$params = array($value1,$value2,$value3);
$stmt = sqlsrv_query( $conn, $sql, $params);
if( $stmt === false ) {
Echo "Error writing new application to table";
}
This works fine and my records is added, but i need to grab the 'id' of the last inserted record.
Looking at some of the previous questions on this, I tried several different ways, most recently this...
$sql = "Insert into MyTable (column1,column2,column3) VALUES (? , ? , ?);";
$params = array($value1,$value2,$value3);
$stmt = sqlsrv_query( $conn, $sql, $params);
sqlsrv_next_result($stmt);
sqlsrv_fetch($stmt);
$lastInsertedId = lastId($stmt);
echo "RECORD INSERTED WITH ID: " . $lastInsertedId . "<BR>";
if( $stmt === false ) {
Echo "Error writing new application to table";
}
but 'lastInsertedId' comes back blank.
When i've done similar things in the past, albeit not in PHP, I've had an additional command on the end of my insert command and used a different function than query, but I cant seem to find any examples of this.
Can anyone point me in the right direction?
Many thanks in advance!
EDIT / SOLUTION:
So i finally got this working... the other examples provided all returned a null value except one which returned an array, so i tried throwing ["id"] at the end of that and boom... there it is!
$sql = "Insert into MyTable(column1,column2,column3) VALUES (? , ? , ?); SELECT ##IDENTITY as id;";
$params = array($value1,$value2,$value3);
$stmt = sqlsrv_query( $conn, $sql, $params);
$next_result = sqlsrv_next_result($stmt);
$row = sqlsrv_fetch_array($stmt);
echo "ROW INSERTED WITH ID : " . $row["id"];
if( $stmt === false ) {
Echo "Error writing new application to table";
}
Hopefully this may help someone in future if you come across the same annoyingly simple issue.
Looking into online documentation it looks like lastId() is not a PHP method. You should try something like mysql_insert_id() which:
Retrieves the ID generated for an AUTO_INCREMENT column by the previous query (usually INSERT).
Unfortunately according to the official documentation this extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used.
My question supposed to be simple! although, I couldn't find the correct answer!
I need to retrieve the "hashed password" for the giving "username" from mySql database with php, then I need to store it in a variable, how could I do that?
All what I get is "Resource id #5"!
This is my code:
$query = "SELECT hashed_password ";
$query .= "FROM users ";
$query .= "WHERE username = '{$username}' ";
$query .= "AND hashed_password = '{$hashed_password}' ";
$query .= "LIMIT 1";
$result_set = mysql_query($query);
echo "$result_set";
echo '</br>';
To start off, let's use a MySQL library that supports prepared statements - otherwise, we'll run into SQL Injection issues in the future. Now, back to the actual question / answer.
If we use MySQLi, we have a few functions that will help us. Here's an example of an answer to your question w/ code comments to help walk through it:
// create our db connection
$mysqli = new mysqli('localhost', 'db_username', 'db_password', 'db_table');
// create a Prepared Statement to query to db
$stmt = $mysqli->prepare('SELECT hashed_password FROM users WHERE username = ? LIMIT 1');
// dynamically bind the supplied "username" value
$stmt->bind_param('s', $username);
// execute the query
$stmt->execute();
// get the first result and store the first column in the `$hashed_password` variable
$stmt->bind_result($hashed_password);
$stmt->fetch();
// close our Prepared Statement and the db connection
$stmt->close();
$mysqli->close();
echo $hashed_password;
Check out the PHP Doc for mysqli::prepare() for more examples =]
Note: I highly recommend avoiding the mysql_query() (and family) functions. They are not only deprecated, but they are quite insecure to use.
You need to fetch the data out of the mysql-resource that is returned by a query.
Just pass it through mysql_fetch_assoc($result_set). It will return your data in a nice and ordered arraay, moving ahead one row every call.
Meaning you can do
while ($row = mysql_fetch_assoc($result_set).
Also, please use mysqli. Its basically the same just with mysqli instead of mysql in commands. See the docs here for more info: http://php.net/manual/en/book.mysqli.php
I am so sorry mybe it is a silly question but as I am new in web language and php I dont know how to solve this problem.
I have a code which is getting ID from user and then connecting to MySQL and get data of that ID number from database table and then show on webpage.
But I would like to what should I add to this code if user enter an ID which is not in table of database shows a message that no data found.
Here is my code:
<?php
//connect to the server
$connect = mysql_connect ("localhost","Test","Test") ;
//connection to the database
mysql_select_db ("Test") ;
//query the database
$ID = $_GET['Textbox'];
$query = mysql_query (" SELECT * FROM track WHERE Code = ('$ID') ");
//fetch the results / convert results into an array
$ID = $_GET['Textbox'];
WHILE($rows = mysql_fetch_array($query)) :
$ID = 'ID';
echo "<p style=\"font-color: #ff0000;\"> $ID </p>";
endwhile;
?>
Thank You.
Sorry if it is so silly question.
You should use PDO (great tutorial here: http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers ). This way, you can develop safer applications easier. You need to prepare the ID before inserting it to the query string, to avoid any user manipulation of the mysql query (it is called sql injection, guide: http://www.w3schools.com/sql/sql_injection.asp ).
The main answer to your question, after getting the results, you check if there is any row in the result, if you got no result, then there is no such an ID in the database. If you use PDO statements $stmt->rowCount();.
$db = new PDO('mysql:host=localhost;dbname=testdb;charset=utf8', 'username', 'password');
$stmt = $db->prepare("SELECT * FROM table WHERE Code=?");
$stmt->bindValue(1, $id, PDO::PARAM_INT); // or PDO::PARAM_STR
$stmt->execute();
$row_count = $stmt->rowCount();
if ($row_count > 0) {
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
//results are in $results
} else {
// no result, no such an ID, return the error to the user here.
}
Another reason to not use mysql_* functions: http://php.net/manual/en/migration55.deprecated.php
This question already has answers here:
How do I loop through a MySQL query via PDO in PHP?
(3 answers)
Closed 9 years ago.
I am currently using MySQL with PHP but am looking to start MySQLi or PDO
I have while loops like:
$sql="select from ... ";
$rs=mysql_query($sql);
while($result=mysql_fetch_array($rs))
{
$sql2="select from table2 where id = $result["tbl1_id"] ";
}
If I put my MySQLi or PDO queries into a function how can I run things like the above? Doing while loops with queries inside the while loops?
Or is if easier to not do the functions at all and just run the prepared statements as normal?
You wouldn't. And to be honest.. Even in the old days you would not do it this way, but like this:
$sql="select from ... ";
$rs=mysql_query($sql);
$ids = array()
while($result=mysql_fetch_array($rs))
{
$ids[] = $result["tbl1_id"];
}
$sql2="select from table2 where id in ".implode(',', $ids) .";
Or even better, you use a join to run the query just once, on all the tables that need to provide info.
In PDO you can do the same thing. Get all the ID's and the execute a query
I usually take the approach of preparing the query and not using a function. Also I am not clear as to what exactly it is that you want. You want to make your queries as quick and efficient as possible so you should not look to run a while look within another while loop.
This is how my PDO queries usually look
My connection:
$host = "localhost";
$db_name = "assignment";
$username = "root";
$password = "";
try {
$connection = new PDO("mysql:host={$host};dbname={$db_name}", $username, $password);
}catch(PDOException $exception){ //to handle connection error
echo "Connection error: " . $exception->getMessage();
}
MY query:
$query = "SELECT * FROM Table";
$stmt = $connection->prepare( $query );
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
extract($row);
}
It's a duplication question like oGeez say, you have to learn how to code PDO in PHP and other before asking question,
this is the answer:
$dbh = new PDO("mysql:host=" . HOST . ";dbname=" . BASE, USER, PASS, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query = 'SELECT * FROM table';
$stmt = $dbh->query($query);
$items = $stmt->fetchAll(PDO::FETCH_OBJ);
foreach($items as $item {
print_r($item);
}
the main reason to put it in a function would be if you use the query in multiple files. i have a web app with many queries and i like to keep them in a separate file so that they're easier to track down if i need to make changes. the main thing is that you 1) have to pass your database as a parameter and 2) return the results
function pdoquery($db, $parameter){
$query = "SELECT * FROM table WHERE column=?";
$stmt = $db->prepare($query);
$stmt->bindValue(1, $parameter, PDO::PARAM_STR); //or PARAM_INT
if (!$stmt->execute()) {
echo "Could not get results: (" . $stmt->errorCode . ") " . $stmt->errorInfo;
exit;
}
else
$result = $stmt->fetch();
$db = null;
return $result;
}
but as others have mentioned, if its only used once, there's no need for a function, and looping through the results is best done outside of the function as well. however, it is possible to do it inside the function if you want to.
Here is my problem,
Not using prepared statements I can do it just fine, for example,
$qry = "SELECT * FROM accounts WHERE email = '$email'";
$result = mysql_query($qry);
$account = mysql_fetch_assoc($result);
echo '<p>Welcome <strong>' . $account['username'] . '</strong>, Have a good day! And dont forgot your id ' . $account['id'] . '.</p>';
Considering an email does match a row on the mysql database, then I can with ease echo any other column where the email matches by simply doing $account['gender'], $account['age'] for example.
I am having alot of trouble doing it OO, here is my attempt;
$q = $dbc -> prepare ("SELECT * FROM accounts WHERE email = ?");
$q -> bind_param ('s', $email);
$q -> execute();
$q -> bind_result();
$info = $q -> fetch();
echo '<p>Welcome ' . $info['username'] . '.</p>';
Doing it with the first method I can display any information from any column where the email matches for that row, I switched to prepared statements for security, but I am thinking of switching back with the hassle it is causing!
bind_result takes parameters. You pass it the variables you want it to set, then you call fetch.
$q->bind_result($username);
$q->fetch();
echo $username;
For this to work, you need to change SELECT * to the fields you want, ie SELECT username.
If you still need to use SELECT *, you can do this:
$q->execute();
$r = $q->get_result();
while($row = $r->fetch_array(MYSQLI_ASSOC)){
}
Good old MySQL extension does not support prepared statements so you must have switched to another extension you don't mention. If it happens to be mysqli, you're out of luck: it only supports associative arrays when you don't use prepared statements.
My advise is to try out PDO. The MySQL driver is stable and it has a great API you can reuse for other DBMS engines.