Simple problem.
I want to fetch data from database in array without knowing databse indexes. Like dynamic fetching. Let's say I want to fetch two columns from dbase named "name" and "lastname", but echo it using array without database indexes. Like shown in code below:
$sql = mysql_query("SELECT name, lastname FROM employees WHERE id = '1'");
$nameX=array();
while ($myrow = mysql_fetch_array($sql))
{
$nameX=$myrow;
}
foreach ($nameX as $bla)
{
echo $bla;
}
After this code is run it will echo:
JonJonSnowSnow
for the Jon Snow in database as name and lastname.
Little help?
It didn't seem to me a good practice, just relay your model consistency on a dynamic fetching. However I think it could be done using PDO (what is, by the way, a better to implement data acess).
This code probably will help you:
$pdo = new PDO("host;dbname", "user", "pass");
$sql = "SELECT name, lastname FROM employees WHERE id = :id;";
$stmt = $pdo->prepare($sql);
$stmt->bindValue(':id', $id, PDO::PARAM_INT);
$stmt->execute();
if($stmt) {
while(($row = $stmt->fetch(PDO::FETCH_OBJ)) !== false) {
foreach ($row as $key => $value) {
echo($value);
}
}
}
Related
I'm just editing my search script after reading up on SQL injection attacks. I'm trying to get the same functionality out of my script using PDO instead of a regular MySQL connection. So I've been reading other posts about PDO, but I am unsure. Will these two scripts give the same functionality?
With PDO:
$pdo = new PDO('mysql:host=$host; dbname=$database;', $user, $pass);
$stmt = $pdo->prepare('SELECT * FROM auction WHERE name = :name');
$stmt->bindParam(':name', $_GET['searchdivebay']);
$stmt->execute(array(':name' => $name);
With regular MySQL:
$dbhost = #mysql_connect($host, $user, $pass) or die('Unable to connect to server');
#mysql_select_db('divebay') or die('Unable to select database');
$search = $_GET['searchdivebay'];
$query = trim($search);
$sql = "SELECT * FROM auction WHERE name LIKE '%" . $query . "%'";
if(!isset($query)){
echo 'Your search was invalid';
exit;
} //line 18
$result = mysql_query($trim);
$numrows = mysql_num_rows($result);
mysql_close($dbhost);
I go on with the regular example to use
while($i < $numrows){
$row = mysql_fetch_array($result);
to create an array of matching results from the database. How do I do this with PDO?
Take a look at the PDOStatement.fetchAll method. You could also use fetch in an iterator pattern.
Code sample for fetchAll, from the PHP documentation:
<?php
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();
/* Fetch all of the remaining rows in the result set */
print("Fetch all of the remaining rows in the result set:\n");
$result = $sth->fetchAll(\PDO::FETCH_ASSOC);
print_r($result);
Results:
Array
(
[0] => Array
(
[NAME] => pear
[COLOUR] => green
)
[1] => Array
(
[NAME] => watermelon
[COLOUR] => pink
)
)
There are three ways to fetch multiple rows returned by a PDO statement.
The simplest one is just to iterate over the PDO statement itself:
$stmt = $pdo->prepare("SELECT * FROM auction WHERE name LIKE ?")
$stmt->execute(array("%$query%"));
// iterating over a statement
foreach($stmt as $row) {
echo $row['name'];
}
Another one is to fetch rows using the fetch() method inside a familiar while statement:
$stmt = $pdo->prepare("SELECT * FROM auction WHERE name LIKE ?")
$stmt->execute(array("%$query%"));
// using while
while($row = $stmt->fetch()) {
echo $row['name'];
}
But for the modern web application we should have our database interactions separated from the output and thus the most convenient method would be to fetch all rows at once using the fetchAll() method:
$stmt = $pdo->prepare("SELECT * FROM auction WHERE name LIKE ?")
$stmt->execute(array("%$query%"));
// fetching rows into array
$data = $stmt->fetchAll();
Or, if you need to preprocess some data first, use the while loop and collect the data into an array manually:
$result = [];
$stmt = $pdo->prepare("SELECT * FROM auction WHERE name LIKE ?")
$stmt->execute(array("%$query%"));
// using while
while($row = $stmt->fetch()) {
$result[] = [
'newname' => $row['oldname'],
// etc
];
}
And then output them in a template:
<ul>
<?php foreach($data as $row): ?>
<li><?=$row['name']?></li>
<?php endforeach ?>
</ul>
Note that PDO supports many sophisticated fetch modes, allowing fetchAll() to return data in many different formats.
I'm just editing my search script after reading up on SQL injection attacks. I'm trying to get the same functionality out of my script using PDO instead of a regular MySQL connection. So I've been reading other posts about PDO, but I am unsure. Will these two scripts give the same functionality?
With PDO:
$pdo = new PDO('mysql:host=$host; dbname=$database;', $user, $pass);
$stmt = $pdo->prepare('SELECT * FROM auction WHERE name = :name');
$stmt->bindParam(':name', $_GET['searchdivebay']);
$stmt->execute(array(':name' => $name);
With regular MySQL:
$dbhost = #mysql_connect($host, $user, $pass) or die('Unable to connect to server');
#mysql_select_db('divebay') or die('Unable to select database');
$search = $_GET['searchdivebay'];
$query = trim($search);
$sql = "SELECT * FROM auction WHERE name LIKE '%" . $query . "%'";
if(!isset($query)){
echo 'Your search was invalid';
exit;
} //line 18
$result = mysql_query($trim);
$numrows = mysql_num_rows($result);
mysql_close($dbhost);
I go on with the regular example to use
while($i < $numrows){
$row = mysql_fetch_array($result);
to create an array of matching results from the database. How do I do this with PDO?
Take a look at the PDOStatement.fetchAll method. You could also use fetch in an iterator pattern.
Code sample for fetchAll, from the PHP documentation:
<?php
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();
/* Fetch all of the remaining rows in the result set */
print("Fetch all of the remaining rows in the result set:\n");
$result = $sth->fetchAll(\PDO::FETCH_ASSOC);
print_r($result);
Results:
Array
(
[0] => Array
(
[NAME] => pear
[COLOUR] => green
)
[1] => Array
(
[NAME] => watermelon
[COLOUR] => pink
)
)
There are three ways to fetch multiple rows returned by a PDO statement.
The simplest one is just to iterate over the PDO statement itself:
$stmt = $pdo->prepare("SELECT * FROM auction WHERE name LIKE ?")
$stmt->execute(array("%$query%"));
// iterating over a statement
foreach($stmt as $row) {
echo $row['name'];
}
Another one is to fetch rows using the fetch() method inside a familiar while statement:
$stmt = $pdo->prepare("SELECT * FROM auction WHERE name LIKE ?")
$stmt->execute(array("%$query%"));
// using while
while($row = $stmt->fetch()) {
echo $row['name'];
}
But for the modern web application we should have our database interactions separated from the output and thus the most convenient method would be to fetch all rows at once using the fetchAll() method:
$stmt = $pdo->prepare("SELECT * FROM auction WHERE name LIKE ?")
$stmt->execute(array("%$query%"));
// fetching rows into array
$data = $stmt->fetchAll();
Or, if you need to preprocess some data first, use the while loop and collect the data into an array manually:
$result = [];
$stmt = $pdo->prepare("SELECT * FROM auction WHERE name LIKE ?")
$stmt->execute(array("%$query%"));
// using while
while($row = $stmt->fetch()) {
$result[] = [
'newname' => $row['oldname'],
// etc
];
}
And then output them in a template:
<ul>
<?php foreach($data as $row): ?>
<li><?=$row['name']?></li>
<?php endforeach ?>
</ul>
Note that PDO supports many sophisticated fetch modes, allowing fetchAll() to return data in many different formats.
I'm just editing my search script after reading up on SQL injection attacks. I'm trying to get the same functionality out of my script using PDO instead of a regular MySQL connection. So I've been reading other posts about PDO, but I am unsure. Will these two scripts give the same functionality?
With PDO:
$pdo = new PDO('mysql:host=$host; dbname=$database;', $user, $pass);
$stmt = $pdo->prepare('SELECT * FROM auction WHERE name = :name');
$stmt->bindParam(':name', $_GET['searchdivebay']);
$stmt->execute(array(':name' => $name);
With regular MySQL:
$dbhost = #mysql_connect($host, $user, $pass) or die('Unable to connect to server');
#mysql_select_db('divebay') or die('Unable to select database');
$search = $_GET['searchdivebay'];
$query = trim($search);
$sql = "SELECT * FROM auction WHERE name LIKE '%" . $query . "%'";
if(!isset($query)){
echo 'Your search was invalid';
exit;
} //line 18
$result = mysql_query($trim);
$numrows = mysql_num_rows($result);
mysql_close($dbhost);
I go on with the regular example to use
while($i < $numrows){
$row = mysql_fetch_array($result);
to create an array of matching results from the database. How do I do this with PDO?
Take a look at the PDOStatement.fetchAll method. You could also use fetch in an iterator pattern.
Code sample for fetchAll, from the PHP documentation:
<?php
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();
/* Fetch all of the remaining rows in the result set */
print("Fetch all of the remaining rows in the result set:\n");
$result = $sth->fetchAll(\PDO::FETCH_ASSOC);
print_r($result);
Results:
Array
(
[0] => Array
(
[NAME] => pear
[COLOUR] => green
)
[1] => Array
(
[NAME] => watermelon
[COLOUR] => pink
)
)
There are three ways to fetch multiple rows returned by a PDO statement.
The simplest one is just to iterate over the PDO statement itself:
$stmt = $pdo->prepare("SELECT * FROM auction WHERE name LIKE ?")
$stmt->execute(array("%$query%"));
// iterating over a statement
foreach($stmt as $row) {
echo $row['name'];
}
Another one is to fetch rows using the fetch() method inside a familiar while statement:
$stmt = $pdo->prepare("SELECT * FROM auction WHERE name LIKE ?")
$stmt->execute(array("%$query%"));
// using while
while($row = $stmt->fetch()) {
echo $row['name'];
}
But for the modern web application we should have our database interactions separated from the output and thus the most convenient method would be to fetch all rows at once using the fetchAll() method:
$stmt = $pdo->prepare("SELECT * FROM auction WHERE name LIKE ?")
$stmt->execute(array("%$query%"));
// fetching rows into array
$data = $stmt->fetchAll();
Or, if you need to preprocess some data first, use the while loop and collect the data into an array manually:
$result = [];
$stmt = $pdo->prepare("SELECT * FROM auction WHERE name LIKE ?")
$stmt->execute(array("%$query%"));
// using while
while($row = $stmt->fetch()) {
$result[] = [
'newname' => $row['oldname'],
// etc
];
}
And then output them in a template:
<ul>
<?php foreach($data as $row): ?>
<li><?=$row['name']?></li>
<?php endforeach ?>
</ul>
Note that PDO supports many sophisticated fetch modes, allowing fetchAll() to return data in many different formats.
I have this code so far
// Starts the transaction
self::$database->startTransaction();
try {
$sql = "SELECT playerId FROM players WHERE name=?";
$stmt = self::getConnection()->prepare($sql);
$stmt->bind_param('s', $playerName);
foreach ($playerNames as $key => $playerName) {
$stmt->execute();
$stmt->bind_result($playerId);
$stmt->fetch();
echo $playerId . "<br>";
}
// commits the transaction
self::$database->commit();
} catch (Exception $e) {
self::$database->rollback();
throw new Exception(__METHOD__." | ".$e->getMessage());
}
The array $playerNames contains the names of the players, e.g.
array('Player1', 'Player2', 'player3')
The code from above should select the playerId of those players from the database. I have some issues:
It just returns the last playerId (in this case the Id of 'player3'). I don't know why.
I use a foreach-loop to execute(). is this bad for the performance, if there were hundreds of names in the array?
In generell: Is this the correct approach for SELECTing or INSERTing stuff from or into a database?
I read this question: How can I prevent SQL injection in PHP?
But it didn't really work because of this:
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// do something with $row
}
I get an error with the getResult()-method. It says, the method doesn't exist. I think my webspace doesn't support it and I can't install it manually. So I need to stick with fetch().
Or might it have other reasons?
$sql = "SELECT playerId FROM players WHERE name=?";
$stmt = self::getConnection()->prepare($sql);
$stmt->bind_param('s', $playerName);
$stmt->bind_result($playerId);
foreach ($playerNames as $key => $playerName) {
$stmt->execute();
$stmt->fetch();
echo $playerId . "<br>";
}
You are fetching results of only last execute
Running long loops is apparently bad for performance. Try to avoid them.
Yes, in general.
You basically have two options to echo the rows in the HTML page using PHP:
Using PDO:
$stmt = $pdo->prepare('SELECT * FROM employees WHERE name = :name');
$stmt->execute(array(':name' => $name));
foreach ($stmt as $row) {
// do something with $row
}
Using mysqli:
$stmt = $dbConnection->prepare('SELECT * FROM employees WHERE name = ?');
$stmt->bind_param('s', $name);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// do something with $row
}
So when you give $row the data of the first row, the pointer moves to the next row of the query. If you are going to need that same list of data in other part of the page, what is the proper thing to do?
Return the pointer to the first row (how to do it?);
Recall the query (and spend more time and resources);
Create a array with the data (how to do it?);
I always use an array for this.. If nothing else, you will keep high readability of your code at least.