PDO - passing a field name as a variable - php

I'm just migrating my code from mysql_query style commands to PDO style and I ran into a problem. THe old code looked like this :
$query_list_menu = "SELECT ".$_GET['section_name']." from myl_menu_hide_show WHERE id='".$_GET['id']."'";
And the updated code looks like below. Apparently it's not working. I store in $_GET['section_name'] a string that represents a field name from the database. But I think there is a problem when I pass it as a variable. Is the below code valid ? Thanks.
$query_list_menu = "SELECT :section_name from myl_menu_hide_show WHERE id=:id";
$result_list_menu = $db->prepare($query_list_menu);
$result_list_menu->bindValue(':section_name', $_GET['section_name'] , PDO::PARAM_STR);
$result_list_menu->bindValue(':id', $_GET['id'] , PDO::PARAM_INT);
$result_list_menu->execute();

If $_GET['section_name'] contains a column name, your query should be:
$query_list_menu = "SELECT " . $_GET['section_name'] . " from myl_menu_hide_show WHERE id=:id";
Giving:
$query_list_menu = "SELECT :section_name from myl_menu_hide_show WHERE id=:id";
$result_list_menu = $db->prepare($query_list_menu);
$result_list_menu->bindValue(':id', $_GET['id'] , PDO::PARAM_INT);
$result_list_menu->execute();
The reason is that you want the actual name of the column to be in the query - you'd changed it to be a parameter, which doesn't really make much sense.
I'll also add that using $_GET['section_name'] directly like this is a massive security risk as it allows for SQL injection. I suggest that you validate the value of $_GET['section_name'] by checking it against a list of columns before building and executing the query.

There is no good and safe way to select just one field from the record based on the user's choice. The most sensible solution would be to select the whole row and then return the only field requested
$sql = "SELECT * from myl_menu_hide_show WHERE id=?";
$stmt = $db->prepare($query_list_menu);
$stmt->execute([$_GET['id']]);
$row = $stmt->fetch();
return $row[$_GET['section_name']] ?? false;

Related

insert using a variable of a consult php and mysql

I am trying to perform an insert with the information of a query from another table, using php and mysql, I know that I have not done the protection part against sql injection correctly, I will solve that at the end, I tell you why then they only go to scold and do not contribute, would you be kind enough to tell me how to use the value obtained from the query, thank you.
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
include("conection.php");
$credits = mysqli_real_escape_string($con, $_POST['credits']);
$namesec = mysqli_real_escape_string($con, $_POST['namesec']);
$change = mysqli_real_escape_string($con, $_POST['change']);
$stmt = $con->prepare("UPDATE students
SET student_credits = (student_credits + ?)
WHERE student_qr = ?");
$stmt->bind_param("is", $_POST['credits'], $_POST['namesec']);
$stmt->execute();
$insert_query = $con->prepare("INSERT INTO historical_credits (id_students, credits_paid)
SELECT id_students, ?
FROM students
WHERE student_qr = ?"
);
$insert_query->bind_param("is", $_POST['credits'], $_POST['namesec']);
$insert_query->execute();
mysqli_close($con);
?>
I want to use the value of id_student obtained from the query to insert it into a new table
You forgot to call fetch_assoc() to get the row that the query returns.
You also didn't quote $namesec in the SELECT query, so it's getting an error. This wouldn't be a problem if you used a parameter instead of substituting the variable.
But there's no need to do this in two queries. You can give a SELECT query as the source of the data in INSERT.
$insert_query = $con->prepare("
INSERT INTO historical_credits (id_students, credits_paid)
SELECT id_students, ?
FROM students
WHERE student_qr = ?");
$insert_query->bind_param("is", $_POST['credits'], $_POST['namesec']);
$insert_query->execute();

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.

Getting the id of the last inserted record from an MSSQL table using PDO and PHP

I am trying to get the id of the last record inserted in an mssql database using pdo via php. I HAVE read many posts, but still can't get this simple example to work, so I am turning to you. Many of the previous answers only give the SQL code, but don't explain how to incorporate that into the PHP. I honestly don't think this is a duplicate. The basic insert code is:
$CustID = "a123";
$Name="James"
$stmt = "
INSERT INTO OrderHeader (
CustID,
Name
) VALUES (
:CustID,
:Name
)";
$stmt = $db->prepare( stmt );
$stmt->bindParam(':CustID', $CustID);
$stmt->bindParam(':Name', $Name);
$stmt->execute();
I have to use PDO querying an MSSQL database. Unfortunately, the driver does not support the lastinsertid() function with this database. I've read some solutions, but need more help in getting them to work.
One post here suggests using SELECT SCOPE_IDENTITY(), but does not give an example of how incorporate this into the basic insert code above. Another user suggested:
$temp = $stmt->fetch(PDO::FETCH_ASSOC);
But, that didn't yield any result.
If your id column is named id you can use OUTPUT for returning the last inserted id value and do something like this:
$CustID = "a123";
$Name="James"
$stmt = "INSERT INTO OrderHeader (CustID, Name)
OUTPUT INSERTED.id
VALUES (:CustID, :Name)";
$stmt = $db->prepare( stmt );
$stmt->bindParam(':CustID', $CustID);
$stmt->bindParam(':Name', $Name);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
echo $result["id"]; //This is the last inserted id returned by the insert query
Read more at:
https://msdn.microsoft.com/en-us/library/ms177564.aspx
http://php.net/manual/es/pdo.lastinsertid.php

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='';

MySQL Update gotcha? Is there something specific about UPDATE?

I have a really simple procedure I need to do, and no matter how much I debug or simplify, the record is not updating in the dbase. Assume everything is correct in terms of connection, etc. Pulling this from php and doing a MySQL call in PHPMyAdmin results in a correct record update on the table. I've tried using/not using quotes around adminId.
Any ideas?
$sampleString = "343r34c3cc43";
//Need to store the customer ID from sub system
$stmt2 = $mysqli->prepare("
UPDATE
admins
SET
chargebeeId = '?'
WHERE
adminId='22'
");
$stmt2->bind_param('s',
$mysqli->real_escape_string($sampleString)
);
$stmt2->execute();
For reference, adminId will be dynamic, with a bind_param 'i' in the application.
change this
chargebeeId = '?'
to
chargebeeId = ?
try this
$sampleString = "343r34c3cc43";
$sampleString = $mysqli->real_escape_string($sampleString) ;
$stmt2 = $mysqli->prepare("UPDATE admins
SET chargebeeId = ?
WHERE adminId='22' ");
$stmt2->bind_param('s', $sampleString);
$stmt2->execute();

Categories