Table will not display - php

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();

Related

mysqli_fetch_array only displays the first result

I struggled all day to display the results of an SQL query using PHP.
I have a table in the database named coins with the following columns:
- nr_unic (which is the index);
- rank;
- name;
- symbol;
- price_usd;
- price_btc;
What I need to do is to fetch the values of each coin (from the name field) and display the symbol, price_usd, price_btc, and rank. The piece of code which contains the query I am running and trying to display the values is:
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// SQL QUERY
$sql= "SELECT rank, name, symbol, price_usd, price_btc, 24h_volume_usd FROM coins WHERE rank BETWEEN 1 AND 10 ORDER BY nr_unic DESC LIMIT 10";
$result = $conn->query($sql);
$rows = array();
if ($result) {
while($row = mysqli_fetch_array($result, MYSQLI_BOTH)) {
$rows[] = $row['name'] . " " . $row['price_usd'] . " " . $row['symbol'] . " " . $row['rank'];
foreach ($rows as $key => $value) {
echo $value;
}
}
mysqli_free_result ($result);
}
Thank you!
LATER EDIT
Following #Máté Solymosi indications I managed updated the code and to display the results. The problem now is they are getting duplicated: I get the first coin, then the first and the second, then the first, second and third... and so on.
The code I use was updated
The return statement in your while loop causes the function to terminate immediately, returning just the first row. Instead, you should collect the results in an array and return the array at the end:
$rows = array();
while($row = mysqli_fetch_array($result, MYSQLI_BOTH)) {
$rows[] = $row['name'] . " " . // ...
}
mysqli_free_result($result);
return $rows;

Use session name in MySQL statement

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?

While selecting data from database using following code

I have used this code to select data from table tbl_users but it is showing 1. what does it mean..
require_once('config.php');
$dbCon = getConnection();
$sql = "SELECT * FROM tbl_users";
$stmt = $dbCon->prepare($sql);
print($stmt->execute());
can Anyone Help...????
If the query runs successfully, $stmt->execute() returns true, which will print as 1.
To return data:
//Returns first row as array
$row = $stmt->fetch();
//Returns first row as key => value array
$row = $stmt->fetch(PDO::FETCH_ASSOC);
//Returns all rows as key=>value arrays
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
You can use this to print data like so:
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
//Print all data
$print_r($rows);
//Print data row-by-row
foreach($rows as $row){
print_r($row);
}
At this moment you're printing the response of the query, not the results.
To print the results you should do something like this:
foreach ($stmt as $row) {
print $row['name'] . "\t";
print $row['first_name'] . "\t";
print $row['birth_date'] . "\n";
}
On successful execution of query execute() return True .
$sql = "SELECT * FROM tbl_users";
$stmt = $dbCon->prepare($sql);
$result = $stmt->fetchAll();
print_r($result);

Getting number of rows form SQL Server table

I have a problem with getting the right value after I counted the rows from a table. I searched on the web but didn't find an answer.
In the database i have a table with all the categories in it they all have an id, and i would like to count using this column.
I have this PHP code, it works but is there an other and better to get over this?
$sql2 = "SELECT COUNT(id) FROM categories";
$stmt2 = sqlsrv_query($conn, $sql2);
$res = sqlsrv_fetch_array($stmt2, SQLSRV_FETCH_ASSOC);
foreach($res as $row)
{
$rows = $row;
}
//if there are categories display them otherwise don't
if ($rows > 0)
{
$sql = "SELECT * FROM categories";
$stmt = sqlsrv_query($conn, $sql);
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
echo "<a href='#' class='cat_links'>" . $row['category_name'] . " - <font size='-1'>" . $row['category_description'] . "</font></a>";
}
}
else
{
echo "<p style='text-align: center'>No categories yet.</p>";
}
I think has to be a better way to convert the $stmt2 variable from a SQL resource to an actual number, or to convert the $res variable from an array to an number. If I try to echo the whole array using foreach, it will only print out the number of rows. This is why I use it to count the rows now.
I can't use the sqlsrv_num_rows function because I then get an error, or no answer.

PHP - (PDO) Execute with binding variables

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.

Categories