getting single cell from database using PDO - php

I am trying to get a piece of data from my database but would like to only get one cell using the PDO statement if this is possible.
Below is a screenshot of the table
The table name is called heating
I am trying to get the data from column called 'garage' and row id = 3
I have tried many ways but keep failing. The following is what I have so far but only returns the column name garage for some reason.
I am using the following which gives me the name garage
$room = 'garage';
require_once "connect.php";
$sql = 'SELECT :name FROM heating WHERE id = 3';
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':name', $room);
$stmt->execute();
$sw = $stmt->fetch();
echo $sw[0];
If I do the following I gives me the correct outcome but I would like to replace garage with a variable
$sql = 'SELECT garage FROM heating WHERE id = 3';
$stmt = $pdo->prepare($sql);
$stmt->execute();
$sw = $stmt->fetch();
echo $sw[0];

You can create a white list of your column names and use it to select the right column. You can check the column against a white list with the help of in_array. The third parameter is very important as it checks that string is a string. You can only then safely concatenate the SQL with your PHP variables using PHP concatenation operator. For the good measure, the column names should be enclosed in backticks `, in case any of your column names is a reserved word or contains special characters.
$whiteListOfHeating = [
'keyName',
'den',
'WC1',
'hallway',
'garage'
];
$room = 'garage';
if (in_array($room, $whiteListOfHeating, true)) {
$sql = 'SELECT `'.$room.'` FROM heating WHERE id = 3';
$stmt = $pdo->prepare($sql);
// ...
} else {
echo 'Invalid column name specified!';
}

Sometimes simplest solutions are best.
require_once "connect.php";
$room = 'garage';
$sql = 'SELECT * FROM heating WHERE id = ?';
$stmt = $pdo->prepare($sql);
$stmt->execute([3]);
$sw = $stmt->fetch();
echo $sw[$room];
Besides, every time you need such a functionality, in means that most likely your database structure is wrong. A room should be a row, not column
require_once "connect.php";
$room = 'garage';
$sql = 'SELECT value FROM heating_room WHERE heating_id=3 and room = ?';
$stmt = $pdo->prepare($sql);
$stmt->execute([$room]);
$sw = $stmt->fetchColumn();
echo $sw;
will make it straight

Related

Results UNDEFINED in SQL query and php

I am new when it comes to php, SQL and still learning, I am trying to get the last 4 string value of my column where the value is a telephone numbers: (7258787)
I am trying to display the last 4 string even the search query is full 7 string (8787) base on what i have read SUBSTRING(column_name, -4) will result the last 4 strings from the right.
my codes returns undefined, can you enlighten me with this?
if (isset($_GET['telephone'])) {
$data = "%".$_GET['telephone']."%";
$sql = 'SELECT telephone, SUBSTRING(telephone,-4)FROM employee';
Using this:
$sql = 'SELECT * FROM employee WHERE telephone like ?';
will result the correct value of 7258787 but it will result the whole string(telephone numbers) that i type on a search box
Thank you in advance
This is the whole code:
This is not the answer but the whole script, (credits to Israel Barragan)
In my database I have employee as table and the columns are 'ID', 'NAME', 'TELEPHONE', and 'EMAIL'
<?php
header('Content-Type: application/json');
require_once 'Connectiondb.php';
$conn = dbConnect();
$OK = true; // We use this to verify the status of the update.
if (isset($_GET['telephone'])) {
// Create the query
$data = "%".$_GET['telephone']."%";
$sql = 'SELECT * FROM employee WHERE telephone like ?';
// we have to tell the PDO that we are going to send values to the query
$stmt = $conn->prepare($sql);
// Now we execute the query passing an array toe execute();
$results = $stmt->execute(array($data));
// Extract the values from $result
$rows = $stmt->fetchAll();
$error = $stmt->errorInfo();
//echo $error[2];
}
// If there are no records.
if(empty($rows)) {
echo json_encode( array('error'=>'There were not records','0'=> 'There were not records'));
}
else {
echo json_encode($rows);
}
?>
sorry I am new to stackoverflow,
You can bind the result in your query, and then get the last 4 digits from that to display.
For instance, you can do this
(not you aren't binding your parameters. You need to do something like this)
$stmt->bind_param("s", $data);
and then execute it like this:
$stmt->execute();
In your query instead of using select *, name the specific keys and then you can bind the result like this (assuming all you need is the phone number:
$stmt->bind_result($telephone);
then get the result like so:
$stmt->fetch();
then you can just get a substring off of $telephone like so (in php it is substr())
echo substr($telephone,-4);
(oh yeah and don't forget to close your object with
$stmt->close();
after you are done)
Edit:
Here's your query put together to get the substring
$data = "%".$_GET['telephone']."%";
$stmt = $conn->prepare("SELECT telephone FROM employee WHERE telephone like ?");
$stmt->bind_param("s", $data);
$stmt->execute();
$stmt->bind_result($telephone);
$stmt->fetch();
echo substr($telephone,-4);
$stmt->close();

Unable to concatenate sql in pdo statement [duplicate]

This question already has answers here:
How to include a PHP variable inside a MySQL statement
(5 answers)
Closed 2 years ago.
I currently have a Get varible
$name = $_GET['user'];
and I am trying to add it to my sql statement like so:
$sql = "SELECT * FROM uc_users WHERE user_name = ". $name;
and run
$result = $pdo -> query($sql);
I get an invalid column name. But that doesn't make sense because if I manually put the request like so
$sql = "SELECT * FROM uc_users WHERE user_name = 'jeff'";
I get the column data, just not when I enter it as a get variable. What am I doing wrong. I am relatively new to pdo.
Update:
Now I have the following:
$name = $_GET['user'];
and
$sql = "SELECT * FROM uc_users WHERE user_name = :name";
//run the query and save the data to the $bio variable
$result = $pdo -> query($sql);
$result->bindParam( ":name", $name, PDO::PARAM_STR );
$result->execute();
but I am getting
> SQLSTATE[42000]: Syntax error or access violation: 1064 You have an
> error in your SQL syntax; check the manual that corresponds to your
> MySQL server version for the right syntax to use near ':name' at line
> 1
For your query with the variable to work like the one without the variable, you need to put quotes around the variable, so change your query to this:
$sql = "SELECT * FROM uc_users WHERE user_name = '$name'";
However, this is vulnerable to SQL injection, so what you really want is to use a placeholder, like this:
$sql = "SELECT * FROM uc_users WHERE user_name = :name";
And then prepare it as you have:
$result = $pdo->prepare( $sql );
Next, bind the parameter:
$result->bindParam( ":name", $name, PDO::PARAM_STR );
And lastly, execute it:
$result->execute();
I find this best for my taste while preventing SQL injection:
Edit: As pointed out by #YourCommonSense you should use a safe connection as per these guidelines
// $conn = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME);
$sql = 'SELECT * FROM uc_users WHERE user_name = ?';
$stmt = $conn->prepare($sql);
$stmt->bind_param('s', $name);
$stmt->execute();
$result = $stmt->get_result();
$stmt->close();
// perhaps you'll need these as well
$count = $result->num_rows;
$row = $result->fetch_assoc();
/* you can also use it for multiple rows results like this
while ($row = $result->fetch_assoc()) {
// code here...
} */
BTW, if you had more parameters e.g.
$sql = 'SELECT * FROM table WHERE id_user = ? AND date = ? AND location = ?'
where first ? is integer and second ? and third ? are string/date/... you would bind them with
$stmt->bind_param('iss', $id_user, $date, $location);
/*
* i - corresponding variable has type integer
* d - corresponding variable has type double
* s - corresponding variable has type string
* b - corresponding variable is a blob and will be sent in packets
*/
Source: php.net
EDIT:
Beware! You cannot concatenate $variables inside bind_param
Instead you concatenate before:
$full_name = $family_name . ' ' . $given_name;
$stmt->bind_param('s', $full_name);
Try this .You didn't put sigle quote against variable.
$sql = "SELECT * FROM uc_users WHERE user_name = '". $name."'";
Note: Try to use Binding method.This is not valid way of fetching data.
$sql = "SELECT * FROM 'uc_users' WHERE user_name = '". $name."' ";

Short code to get 2 values from one row with php pdo

Possibly stupid question, but can not find answer.
I need to get values from two columns of the same row.
And then set variables with each value.
Here I get one value from column Number and then define variable $NumberPostRegister1
$stmt = $db->prepare("SELECT Number FROM 2_1_journal WHERE Number = :Number1");
$stmt->bindParam(':Number1', $row_id1);
$stmt->execute();
$NumberPostRegister1 = $stmt->fetchColumn();
echo $NumberPostRegister1 .' NumberPostRegister1<br>';
Here I get second value from column IfDraft and then define variable $IfDraft1
$stmt = $db->prepare("SELECT IfDraft FROM 2_1_journal WHERE Number = :Number1");
$stmt->bindParam(':Number1', $row_id1);
$stmt->execute();
$IfDraft1 = $stmt->fetchColumn();
echo $IfDraft1 .' NumberPostRegister1<br>';
Two queries and rather long code.
How to do the same using one query and shorter/simpler code?
$stmt = $db->prepare("SELECT IfDraft, Number FROM 2_1_journal WHERE Number = ?");
$stmt->execute(array($row_id1));
list($IfDraft, $Numer) = $stmt->fetch();

PHP PDO Security

Im trying to work with PDO for the first time and I'm just wanting to know how secure what I'm doing is, I'm also new to PHP.
I have a query that when a user is passed ot my page, the page takes a variable using GET and then runs.
With PHP I've always used mysql_real_escape to sanitize my variables.
Can anybody see security flaws with this?
// Get USER ID of person
$userID = $_GET['userID'];
// Get persons
$sql = "SELECT * FROM persons WHERE id =$userID";
$q = $conn->query($sql) or die($conn->error());
while($r = $q->fetch(PDO::FETCH_LAZY)){
echo '<div class="mis-per">';
echo '<span class="date-submitted">' . $r['date_submitted'] . '</span>';
// MORE STUF
echo '</div>';
}
Don't use query, use prepare:
http://php.net/manual/de/pdo.prepare.php
$userID = $_GET['userID'];
$sql = "SELECT * FROM persons WHERE id = :userid";
$q = $conn->prepare($sql)
$q->execute(array(':userid' => $userID ));
while($r = $q->fetch(PDO::FETCH_ASSOC)){
echo '<div class="mis-per">';
echo '<span class="date-submitted">' . $r['date_submitted'] . '</span>';
// MORE STUF
echo '</div>';
}
The SQL statement can contain zero or more named (:name) or question mark (?) parameter markers for which real values will be substituted when the statement is executed.
With anything you use, it's about how you use it rather than what you use. I'd argue that PDO itself is very safe as long as you use it properly.
$sql = "SELECT * FROM persons WHERE id =$userID";
That's bad *. Better :
$sql = "SELECT * FROM persons WHERE id = " . $conn->quote($userID);
Better :
$q = $conn->prepare('SELECT * FROM persons WHERE id = ?')->execute(array($userID));
* This is bad, and that's because if $userID is "1 OR 1", the query becomes SELECT * FROM persons WHERE id =1 OR 1 which will always return all values in the persons table.
As the comments say: Atm there is no security whatsoever against SQLI. PDO offers you (if the database driver supports it (mysql does)) Prepared Statements. Think of it like a query-template that is compiled/passed to the dbms and later filled with values.
here is an example of usage:
$sql = 'SELECT name, colour, calories
FROM fruit
WHERE calories < :calories AND colour = :colour';
//Prepare the Query
$sth = $dbh->prepare($sql);
//Execute the query with values (so no tainted things can happen)
$sth->execute(array(':calories' => 150, ':colour' => 'red'));
$red = $sth->fetchAll();
Adjust as follows (you can use either :userId or simply ? as Tom van der Woerdt suggests, even if I think the first one gives more clearness, especially when there are more than just one parameter):
$sql = "SELECT * FROM persons WHERE id =:userID";
$q = $conn->prepare( $sql );
$q->bindValue( ":userID", $userID, PDO::PARAM_INT ); // or PDO::PARAM_STR, it depends
$q->execute();
$r = $st->fetch();
...
...

How can I properly use a PDO object for a parameterized SELECT query

I've tried following the PHP.net instructions for doing SELECT queries but I am not sure the best way to go about doing this.
I would like to use a parameterized SELECT query, if possible, to return the ID in a table where the name field matches the parameter. This should return one ID because it will be unique.
I would then like to use that ID for an INSERT into another table, so I will need to determine if it was successful or not.
I also read that you can prepare the queries for reuse but I wasn't sure how this helps.
You select data like this:
$db = new PDO("...");
$statement = $db->prepare("select id from some_table where name = :name");
$statement->execute(array(':name' => "Jimbo"));
$row = $statement->fetch(); // Use fetchAll() if you want all results, or just iterate over the statement, since it implements Iterator
You insert in the same way:
$statement = $db->prepare("insert into some_other_table (some_id) values (:some_id)");
$statement->execute(array(':some_id' => $row['id']));
I recommend that you configure PDO to throw exceptions upon error. You would then get a PDOException if any of the queries fail - No need to check explicitly. To turn on exceptions, call this just after you've created the $db object:
$db = new PDO("...");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
I've been working with PDO lately and the answer above is completely right, but I just wanted to document that the following works as well.
$nametosearch = "Tobias";
$conn = new PDO("server", "username", "password");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sth = $conn->prepare("SELECT `id` from `tablename` WHERE `name` = :name");
$sth->bindParam(':name', $nametosearch);
// Or sth->bindParam(':name', $_POST['namefromform']); depending on application
$sth->execute();
You can use the bindParam or bindValue methods to help prepare your statement.
It makes things more clear on first sight instead of doing $check->execute(array(':name' => $name)); Especially if you are binding multiple values/variables.
Check the clear, easy to read example below:
$q = $db->prepare("SELECT id FROM table WHERE forename = :forename and surname = :surname LIMIT 1");
$q->bindValue(':forename', 'Joe');
$q->bindValue(':surname', 'Bloggs');
$q->execute();
if ($q->rowCount() > 0){
$check = $q->fetch(PDO::FETCH_ASSOC);
$row_id = $check['id'];
// do something
}
If you are expecting multiple rows remove the LIMIT 1 and change the fetch method into fetchAll:
$q = $db->prepare("SELECT id FROM table WHERE forename = :forename and surname = :surname");// removed limit 1
$q->bindValue(':forename', 'Joe');
$q->bindValue(':surname', 'Bloggs');
$q->execute();
if ($q->rowCount() > 0){
$check = $q->fetchAll(PDO::FETCH_ASSOC);
//$check will now hold an array of returned rows.
//let's say we need the second result, i.e. index of 1
$row_id = $check[1]['id'];
// do something
}
A litle bit complete answer is here with all ready for use:
$sql = "SELECT `username` FROM `users` WHERE `id` = :id";
$q = $dbh->prepare($sql);
$q->execute(array(':id' => "4"));
$done= $q->fetch();
echo $done[0];
Here $dbh is PDO db connecter, and based on id from table users we've get the username using fetch();
I hope this help someone, Enjoy!
Method 1:USE PDO query method
$stmt = $db->query('SELECT id FROM Employee where name ="'.$name.'"');
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
Getting Row Count
$stmt = $db->query('SELECT id FROM Employee where name ="'.$name.'"');
$row_count = $stmt->rowCount();
echo $row_count.' rows selected';
Method 2: Statements With Parameters
$stmt = $db->prepare("SELECT id FROM Employee WHERE name=?");
$stmt->execute(array($name));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
Method 3:Bind parameters
$stmt = $db->prepare("SELECT id FROM Employee WHERE name=?");
$stmt->bindValue(1, $name, PDO::PARAM_STR);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
**bind with named parameters**
$stmt = $db->prepare("SELECT id FROM Employee WHERE name=:name");
$stmt->bindValue(':name', $name, PDO::PARAM_STR);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
or
$stmt = $db->prepare("SELECT id FROM Employee WHERE name=:name");
$stmt->execute(array(':name' => $name));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
Want to know more look at this link
if you are using inline coding in single page and not using oops than go with this full example, it will sure help
//connect to the db
$dbh = new PDO('mysql:host=localhost;dbname=mydb', dbuser, dbpw);
//build the query
$query="SELECT field1, field2
FROM ubertable
WHERE field1 > 6969";
//execute the query
$data = $dbh->query($query);
//convert result resource to array
$result = $data->fetchAll(PDO::FETCH_ASSOC);
//view the entire array (for testing)
print_r($result);
//display array elements
foreach($result as $output) {
echo output[field1] . " " . output[field1] . "<br />";
}

Categories