I'm having problem with my php code.
I need to query db using in WHERE session name from php page.
Below code:
<?php session_start();
try {
//$con= new PDO('mysql:host=localhost;dbname=wydania_tonery', "sa", "sql");
$zmien_kodowanie = $dbo->query("SET names 'utf8'");
$sesja = $_SESSION['username'];
$query = "SELECT
mdl_user.firstname AS 'Imie',
mdl_user.lastname AS 'Nazwisko',
mdl_user.department AS 'Akronim',
reg.data AS 'Region',
sta.data AS 'Stanowisko',
mdl_user.aim AS 'Stan',
NULLIF('Uwagi', 0) AS 'Uwagi'
FROM
mdl_user
LEFT JOIN
mdl_user_info_data AS reg ON reg.userid=mdl_user.id AND reg.fieldid='2'
LEFT JOIN
mdl_user_info_data AS sta ON sta.userid=mdl_user.id AND sta.fieldid='4'
WHERE
mdl_user.email LIKE 'kierownik.%' AND mdl_user.deleted='0' AND mdl_user_info_data.fieldid = ".$_SESSION['username']." /*AND mdl_user.department='BBT'*/
ORDER BY
mdl_user.department ASC";
//first pass just gets the column name
echo "<table> \n";
$result = $dbo->query($query);
//return only the first row (we only need field names)
$row = $result->fetch(PDO::FETCH_ASSOC);
print " <tr> \n";
foreach ($row as $field => $value){
print " <th>$field</th> \n";
} // end foreach
print " </tr> \n";
//second query gets the data
$data = $dbo->query($query);
$data->setFetchMode(PDO::FETCH_ASSOC);
foreach($data as $row){
print " <tr> \n";
foreach ($row as $name=>$value){
print " <td>$value</td> \n";
} // end field loop
print " </tr> \n";
} // end record loop
print "</table> \n";
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
} // end try
?>
When I use standard way (".$variable.") to pass php variable I got error below:
Fatal error: Call to a member function fetch() on boolean in
Path/to/my/page on line 35
If anyone would like to help me solve my problem I'd be glad to thank him
Try
<?php session_start();
try {
//$con= new PDO('mysql:host=localhost;dbname=wydania_tonery', "sa", "sql");
$zmien_kodowanie = $dbo->query("SET names 'utf8'");
$sesja = $_SESSION['username'];
$query = "SELECT
mdl_user.firstname AS 'Imie',
mdl_user.lastname AS 'Nazwisko',
mdl_user.department AS 'Akronim',
reg.data AS 'Region',
sta.data AS 'Stanowisko',
mdl_user.aim AS 'Stan',
NULLIF('Uwagi', 0) AS 'Uwagi'
FROM
mdl_user
LEFT JOIN
mdl_user_info_data AS reg ON reg.userid=mdl_user.id AND reg.fieldid='2'
LEFT JOIN
mdl_user_info_data AS sta ON sta.userid=mdl_user.id AND sta.fieldid='4'
WHERE
mdl_user.email LIKE 'kierownik.%' AND mdl_user.deleted='0' AND mdl_user_info_data.fieldid = ? /*AND mdl_user.department='BBT'*/
ORDER BY
mdl_user.department ASC";
//first pass just gets the column name
echo "<table> \n";
$stmt = $dbo->prepare($query);
$stmt->bind_param("s", $_SESSION['username']);
$result = $stmt->execute();
Instead of using direct substitution values, you could use below methods to avoid sql injection.
You basically have two options to achieve this:
Using PDO:
$stmt = $pdo->prepare('SELECT * FROM employees WHERE name = :name');
$stmt->execute(array('name' => $name));
foreach ($stmt as $row) {
// do something with $row
}
Please refer How can I prevent SQL-injection in PHP?
Related
I am having no success linking the upper part of the code containing the prepared statements to the table display. After eradicating several syntax errors, all I am getting now is a single row of numbers starting at 0 and running through to 2713 instead of the database results. The code below is exactly as I am using it except that for this purpose I have removed my personal details from the '$con'
<?php
$con= new PDO('mysql:host=;', "",
"");
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if (isset($_POST['submit-keyword'])) {
$keyword = '%'.$keyword. '%';
$stmt = $con->prepare("SELECT * FROM Bath_Wells_NBR WHERE Founder LIKE :keyword ORDER BY DATE");
$stmt->bindParam(':keyword',$keyword,PDO::PARAM_STR);
$stmt->execute();
//use fetchAll to get full array of results, or an empty array
$result=$stmt->fetchAll();
if(count($result)>0) {
print "<table>";
//return only the first row (we only need field names)
$row = $result;
print " <tr>";
foreach ($row as $field => $value){
print " <th>$field</th>";
} // end foreach
print " </tr>";
//second query gets the data
$data = $con->prepare("SELECT * FROM Bath_Wells_NBR WHERE Founder LIKE :keyword ORDER BY DATE");
$data->setFetchMode(PDO::FETCH_ASSOC);
foreach($data as $row){
print " <tr>";
foreach ($row as $name=>$value){
print " <td>$value</td>";
} // end field loop
print " </tr>";
} // end record loop
print "</table>";
}
}
?>
\\
your second query not get bind param properly
See Doc
$data = $con->prepare("SELECT * FROM Bath_Wells_NBR WHERE Founder LIKE :keyword ORDER BY DATE");
$data->bindParam(':keyword', $keyword, PDO::PARAM_STR);
$data->setFetchMode(PDO::FETCH_ASSOC);
$rows = $data->execute();
I'm trying to use foreach loop, for showing my DB but I always get error. What I want is to print each row and column. My code is like this :
$sql = "SELECT a.*, b.klasifikasi FROM kl_stre as b
INNER JOIN data_latih as a
ON a.id_stres = b.id_stres
ORDER BY a.id_dl";
$result = mysqli_query($conn, $sql);
foreach ($result as $dt_train => $row_dt_train):
foreach ($row_dt_train as $attr => $attr_dt_train):
echo $result[$row_dt_train][$attr_dt_trian]; // this line is the problem
endforeach;
endforeach;
the error I get is
Warning: Illegal offset type in C:\xampp\htdocs\knn\array_db.php on line 43
Would you mind explaining what is wrong with this code and how to solve this problem ?
you need to first check your query
if (!$result) {
die('query is not correct'.mysqli_error($conn));//$con is your database connection paste it after $result = mysqli_query($conn, $sql);
}
after that fetch record and simply remove foreach and try to use while() loop
while ($row=mysqli_fetch_array($result)) {
echo $row['your database field name'];
}
your code will be
$sql = "SELECT a.*, b.klasifikasi FROM kl_stre as b
INNER JOIN data_latih as a
ON a.id_stres = b.id_stres
ORDER BY a.id_dl";
$result = mysqli_query($conn, $sql);
if (!$result) {
die('query is not correct'.mysqli_error($conn));
}
while ($row=mysqli_fetch_array($result)) {
echo $row['your database field name'];
}
I don't know why my code doesn't return true, the while loop works fine, but there's a problem.
$PDO_result = $db_PDO->prepare("SELECT * FROM nnm_anime INNER JOIN nnm_anime_info ON nnm_anime.a_id = nnm_anime_info.a_id WHERE a_name LIKE '?%' ");
$PDO_result->bindParam(1, $pismenka[$i]);
$PDO_result->execute();
Here when I var_dump() $PDO_result I get one item in array so the following while loop should work:
while($row = $PDO_result->fetch(PDO::FETCH_ASSOC))
but it doesn't.
Working MySQLi:
$result = mysqli_query($connect_to_db, "SELECT * FROM nnm_anime INNER JOIN nnm_anime_info ON nnm_anime.a_id = nnm_anime_info.a_id WHERE a_name LIKE '$pismenka[$i]%' ");
while($row = mysqli_fetch_array($result))
The most simple solution would be to change $pdo->fetch(PDO::FETCH_ASSOC) to $pdo->fetchAll(PDO::FETCH_ASSOC)
fetchAll returns ALL rows in the requested query, while fetch only gets 1 row (the first)
Example:
<?php
try {
$PDO_result = $db_PDO->prepare("SELECT * FROM nnm_anime INNER JOIN nnm_anime_info ON nnm_anime.a_id = nnm_anime_info.a_id WHERE a_name LIKE ?");
//Execute by inserting an array:
if (!$PDO_result->execute([$pismenka[$i] . "%" ])) { //Added ."%"
die('Error!');
}
//Fetch rows:
$rows = $PDO_result->fetchAll(PDO::FETCH_ASSOC);
//Go trough each row:
foreach ($rows as $row) {
//Do something
}
//Catch exceptions thrown by PDO
} catch (PDOException $ex) {
print_r($ex);
}
I have switched over to the mysqli_ extension for PHP, and I have ran into a bit of an issue.
I have 2 databases. 1 database I am only allowed read privileges, the other I have all privileges. My end goal is to read what I need from database 1, and put it in a table in database 2.
I use a join on database 1 to get all the information I need. I then loop through the results with a while loop. I have a unique id (domainid) in both databases. Where I am encountering the issue is inside the while loop once I have the domainid from the read-only database, I need to check if it exists inside my all-privileges database. I am just unsure of how to accomplish this?
Here is the code:
require 'db/connect.php';
require 'db/connect2.php';
if($result = $db->query("
SELECT tblhosting.domain as domain, tblhosting.id as domainid, tblclients.email as email
FROM tblhosting
LEFT JOIN tblclients ON
tblclients.id = tblhosting.userid
")){
if ($count = $result->num_rows) {
while($row = $result->fetch_object()){
$domainid = $row->domainid;
$domain = $row->domain;
$email = $row->email;
$result2 = $db2->prepare("SELECT domainid FROM information WHERE domainid = ?");
$result2->bind_param('i', $row->domainid);
$result2->execute();
$result2->bind_result($domainid2);
//$result2->fetch();
while($row2 = $result2->fetch_object()){
$domainid2 = $row2->domainid;
if ($domainid == $domainid2) {
echo "Information exists in both Databases", '<br>';
}
else{
echo "New Information Added to Database 2", '<br>';
}
}
}
}
}
This is what I have tried, but was unsuccessful.
EDIT
Second attempt putting the results into an array then looping through them. The array is correct when I print them out. The issue is with the 2nd execute(); command.
$result = $db->query("
SELECT tblhosting.domain as domain, tblhosting.id as domainid, tblclients.email as email
FROM tblhosting
LEFT JOIN tblclients ON
tblclients.id = tblhosting.userid
");
$domainid_arr = array();
while($row = $result->fetch_object()){
$domainid_arr[] = array(
'domainid' => $row->domainid,
'domain' => $row->domain
);
}
foreach ($domainid_arr as $d) {
echo $d['domainid'], $d['domain'], '<br>';
$result2 = $db2->prepare("SELECT domainid FROM information WHERE domainid = ?");
$result2->bind_param('i', $d['domainid']);
$result2->execute();
$result2->bind_result($domainid2);
while($row2 = $result2->fetch_object()){
$domainid2 = $row2->domainid;
if ($d['domainid'] == $domainid2) {
echo "Information exists in both Databases", '<br>';
}
else{
echo "New Information Added to Database 2", '<br>';
}
}
}
I just started playing around with PDO and I am trying to create a function that will display all the data for a given table name. After reading a few posts here I found a solution that I can get working (shown below with a hard-coded select statement). However, I can't get my execute statements to work when I bind my field names (I get an exception similar to: Undefined index: person_id). I should mention my class extends PDO:
/*********************************************************************
*Function showTable
*Purpose Display all information for a given table.
*Params $sTable -> Table name
********************************************************************/
public function showTable($sTable)
{
$result;
try
{
if(isset($sTable))
{
//create a result in a table format
$result = "<table>";
//$stmt = $this->prepare('DESCRIBE :sTable');
$stmt = $this->prepare('DESCRIBE ' . $sTable);
//$stmt->bindParam(':sTable', $sTable);
$stmt->execute();
//array version of the column names
$aCols = $stmt->fetchAll(PDO::FETCH_COLUMN);
//string version of the column names
$sCols = implode (", ", $aCols);
//$stmt = $this->prepare('SELECT :fields FROM :sTable');
//$stmt = $this->prepare('SELECT :fields FROM person');
$stmt = $this->prepare('SELECT person_id, first_name, last_name FROM person');
//$stmt->execute(array(':fields'=>$sCols, 'stable'=>$sTable));
//$stmt->execute(array(':fields'=>$sCols));
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
var_dump($row);
$result = $result . "<tr>";
foreach($aCols as $col)
{
//var_dump($row);
$result = $result . " <td>" . $row[$col]. "</td>";
}
$result = $result . "</tr>";
}
$result = $result . "</table>";
}
return $result;
}
catch(PDOException $e)
{
if($this->bDebug)
{
echo $e->getMessage();
}
}
}
Like I said the hard coded select string works but when i comment out the hard coded and uncomment the execute with a bind it throws exceptions.
You cannot insert identifiers or keywords this way.
PDOStatement::execute() will put the value in escaped form inside single quotes. Your query would look like:
SELECT 'col1, col2' FROM person
What is invalid MySQL syntax.
A valid example:
$stmt = $this->prepare('SELECT col FROM person WHERE name = :name');
$stmt->execute(array(':name' => $name));
It works, because it's a value you insert here; and not an keyword or identifier.