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();
Related
This question already has an answer here:
PDO fetch returns only first row
(1 answer)
Closed 2 years ago.
A table called "checks" has fields ID;email;pass;entered;firstname;lastname;trading.
The only code in this test is the DB connection and the new PDO connection made prior to these snippets. The following snippet reports correctly that there are 5 users in the table "checks".
$sql = "SELECT COUNT(*) AS num FROM checks";
$stmt = $conn->prepare($sql);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
echo '<br>' . $row['num'] . ' users exist.';
This snippet which follows immediately after the above doesn't show the expected result.
$sql = "SELECT * FROM checks";
$stmt = $conn->prepare($sql);
$stmt->execute($id);
$users = $stmt->fetch(PDO::FETCH_ASSOC);
print_r($users);
The print_r statement results in the first array being printed correctly with all fields/contents correctly displayed.
On the next line it prints only the email field contents from each row as a single string!
I'm probably missing something obvious but I just can't spot it. Help please?
PDO::fetch() returns a single row from the result set. You need PDO::fetchAll() instead.
$sql = "SELECT * FROM checks";
$stmt = $conn->prepare($sql);
$stmt->execute();
$users = $stmt->fetchAll(PDO::FETCH_ASSOC); // <--- here
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
$sql = "SELECT firstName , lastName FROM People WHERE born='1934'" ;
$stmt = $db->prepare($sql);
echo "<p>Execute the SQL-statement:<br><code>$sql</code><p>";
$stmt->execute();
// Get the results as an array with column names as array keys
$res = $stmt->fetchColumn();
$stmt->execute();
$res2 = $stmt->fetchColumn(1);
$ANSWER = $res." ".$res2;
If i remove the second execute(); statement the $res2 variable is empty.
Why is that? When i already have retrieved the results once/executed the statement.
if i input 1 as the parameter in the first fetchColumn(); i get the lastName DB column, so the results are there already.
The reason i'm using fetchColumn(); is that i need the result as string and not an array. I just cant understand why it doesnt work without the second execute, it seems like the result set gets destroyed or something after the first fetch and i need to execute it again? That sounds weird.
So previously my queries were working fine. I usually use mysql but have recently changed to a pre-configured vps through godaddy. Last night I was trying to connect to my server via PDO, which is showing the connection is being made.
Next I was trying to select the data from a table using:
global $conn;
$sql = "SELECT name FROM suppliers";
$stm = $conn->prepare($sql);
$stm->execute();
return $stm->fetch();
All this shows on my website is Connection Successful, Array
It doesn't show any array information or anything, just the word "Array". The table has information in it, so it should be displaying the results. Any idea of what I am doing wrong?
You get Array because you are echoing an array. Fetch returns an array,
PDO::FETCH_BOTH (default): returns an array indexed by both column name and 0-indexed column number as returned in your result set
Since you are querying a full table you probably want all the results so you should loop the fetch and return that array.
$sql = "SELECT name FROM suppliers";
$stm = $conn->prepare($sql);
$stm->execute();
while($row = $stm->fetch()) {
$returned_array[] = $row['name'];
}
return $returned_array;
Then iterate over this where ever you are using it for all the supplier names.
foreach(function_call_for_names() as $name) {
echo $name;
}
Alternately, you could use the PDO fetchAll function,
$sql = "SELECT name FROM suppliers";
$stm = $conn->prepare($sql);
$stm->execute();
return $stm->fetchAll();
then
foreach(function_call_for_names() as $row) {
echo $row['name'];
}
Below is the code, I have, it is written in mysql. My goal is to convert this to PDO.
$query = "SELECT name, age FROM table WHERE condition=$condtion";
$mysql_query = mysql_query($query);
echo $name = mysql_result($mysql_query, 0, 'name');
echo $age = mysql_result($mysql_query, 0, 'age');
I have tried doing the following code below, but it is giving me an empty result.
$query = $PDO -> prepare("SELECT name, age FROM table");
$query -> execute();
echo $name = $query->fetch(PDO::FETCH_ASSOC)['name'];
echo $age = $query->fetch(PDO::FETCH_ASSOC)['age'];
Try:
$query = $PDO->prepare("SELECT name, age FROM table WHERE condition = :param");
$query->bindParam(':param', $param); // define this somewhere
$query->execute();
$result = $query->fetch();
echo $name = $result['name'];
echo $age = $result['age'];
From PHP.net, fetch works as follows:
Fetches a row from a result set associated with a PDOStatement object. The fetch_style parameter determines how PDO returns the row.
When you execute a prepared statement, you need to perform a fetch or a fetchAll to pull the data. fetch gets you the first row, and in your case with a condition = X, I am guessing you only want one row.
Updated with links for reference:
execute: http://php.net/manual/en/pdostatement.execute.php
fetch: http://php.net/manual/en/pdostatement.fetch.php