Can someone explain the principle behind this simple code please? - php

Im having difficulty comprehending a line of code that i am using to retrieve results from a mysql database.
I connect to the database with
<?php
try
{
$pdo = new PDO('mysql:host=localhost;dbname=****', '****',
'****');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->exec('SET NAMES "utf8"');
}
catch (PDOException $e)
{
$error = 'Unable to connect to the database server.' . $e->getMessage;
echo $error;
exit();
}
this is fine. the connection works.
to retrive the results i use this code....
$sql = 'SELECT joketext FROM joke';
$results = $pdo->query($sql);
this also is fine but then i use a foreach loop to loop through the result set as so...
foreach ($results as $result){
$jokes[] = $result['joketext'];
}
and then another foreach to loop through $jokes as so...
foreach ($jokes as $joke) {
echo $joke;
}
now this all works it displays the joketext i wanted from the mysql table. However i dont understand the line...
$jokes[] = $result['joketext'];
does this means I am assigning the result set to an array? what does $jokes[]= mean? and why do i have to do this?
I thought i was retrieving strings of text from the database table. The table has an id, joketext, jokedate, and authorid as columns. But if im only selecting the joketext column surely that retrieves a list of all the joketext entries and therefore i can just loop through with a foreach echoing out the results?

The $jokes[] syntax is appending the joke text string to the $jokes array. If the array doesn't exist, it will be created.
It's the same as doing:
array_push($jokes, $result['joketext']);
If you don't need to create a new array, you can just work with the joke text directly in the $results foreach, if you prefer.

your query only selects for one column joketext so you don't have any of the other column data in your result set.
Using $jokes[] = .. is a shorthand way of assigning a value to a new element in the $jokes array. You don't necessarily need to do this. It is just commonly done so that you can use the data later on, in multiple places if you want. Alternatively, you can just work with the result set directly each time. That isn't as commonly done though since the result set is an object or resource that contains more than what you may actually need. But if you're just looking to output the joketext immediately, then you can skip putting it into a separate array and just echo $result['joketext']; in your first loop

$jokes[] = appends a new value to an array and is the same as doing $jokes[count($jokes)] (not completely correct but is a simple way of explaining it).
Technically, you don't have to put all the values in a new array, you could use the original loop instead.
array_push has the same functionality, you can read up about it here

If I understand you correctly then I believe you are correct. The second foreach is not needed, you can simply echo the $result['joketext'] during the first foreach and skip the second one altogether.
so delete the second foreach and edit the first one as follows:
foreach ($results as $result){
echo( $result['joketext'] );
}

Related

Moving Query to MySQLi

I'm updating some old code that has deprecated MySQL functions. But for some reasons I cannot get all the results from the column. The strange part is that if I run the query directly on the server I get all results fine. So this is an issue with PHP getting the results, not the MySQL server or my query.
Here is the new and old code:
My current updated code:
$sql = "SELECT user, monitor FROM users WHERE `status` = 'y'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
// This works. It shows all results
echo $row["user"];
// This does not work! Only shows one result:
$account= $row["user"];
}
else {
echo 'No results';
}
When I use that query directly on DB server, I get all results. So the SQL query is correct. I actually also get all results as well in PHP if I echo the row directly like:
echo $row["user"];
But for some reason when I try to use it with a PHP with variable it only lists one user result.
In the past I used this but the mysql_fetch_array function is now deprecated
while ($row = mysql_fetch_array($result)) {
array_push($data, $row["user"]);
}
foreach($data as $value) {
$account = $value
}
I cannot use my previous code anymore as those MySQL functions are obsolete today. I need to write the results into a file and my old method worked fine. The new one using mysqli does not.
Any suggestions?
You just need to add one of these [, and one of these ].
$account[] = $row["user"];
// ^^ right here.
$account= $row["user"]; means you're storing the value of $row["user"] in $account each time the loop executes. $account is a string, and it gets a new value each time.
$account[] = $row["user"]; means you're appending each value of $row["user"] to an array instead.
You should not use array_push for this. It's overkill for appending a single value to an array. And if the array isn't defined beforehand, it won't work at all.

I need a php (pdo) code to view database full table with column names

I need a php (pdo) code to view database whatever table with it's column names and values in a html table format ..
I managed to do every thing except viewing the column names dinamically..
Here is a part of my code :
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("$sql");
$stmt->execute();
$x=1;
// set the resulting array to associative
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
echo "<tr><th>Name</th><th>Email</th><th>Website</th><th>Comment</th><th>Gender</th></tr>";
foreach(new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as $k=>$v) {
echo $v;
}
as you see i'm viewing the column names manually using normal echo statement.
any help appricated , thanks
With PDO::FETCH_ASSOC, the column names are the keys of the array elements, so $k.
First time you iterate over the result set, grab the keys. Or just do
$results=$stmt->fetchAll();
echo "<tr>";
foreach(array_keys($results[0]) as $column_name) echo "<th>$column_name</th>";
echo "</tr>";
Then continue with your loop over the fetchall (now stored in $results).
Alternately you could take your existing loop and add something that checks if it's the first iteration of the loop and prints the headers then
You can make additional SQL call to get columns from table: SHOW COLUMNS FROM table_name;

Quicker way of doing this

I'm using PDO to get an array of relations from my DB.
$dbRelaties = $dbh->query("SELECT pkRelatieId,naam,email FROM relaties");
in another function i need to acces one specific row in this array. I've managed to do it like this:
$klant = array();
foreach($dbRelaties as $dbRelatie)
{
if($dbRelatie["pkRelatieId"] == $relatie){ $klant = $dbRelatie; break; }
}
sendMail("Subject",$klant);
The above code works. But i'me looking for a neater solution and a quicker one, the above code is called in a function and that function is called inside a loop. So everytime it executes is has to loop through $dbRelaties to get the correct relation.
Can anyone set me in the right direction?
assuming the pk means primary key, then
while($row = mysql_fetch_assoc($result)) {
$dbRelatie[$row['pkRelatieID']] = $row;
}
would produce an array keyed with your primary key field, so
$dbRelatie[$pk]['naam']
will give you that particular pk's naam value.
To show a PDO specific version of Marc B's answer.
Assuming a query was executed through PDO like so:
$sql = "SELECT pkRelatieId,naam,email FROM relaties";
$resultSet = $pdo->query($sql);
The results can be read into a PHP array using PDO's fetch method.
$dbRelaties = array();
while ($row = $resultSet->fetch(PDO::FETCH_ASSOC)) {
$dbRelaties[$row['pkRelatieID']] = $row;
}
This can then be used to access values based on the PK of the row.
sendMail("Subject", $dbRelaties[$relatie]['naam']);
Furthermore. PDO lets you assign a default fetch mode to each PDO instance, and the PDOStatement class is Traversable, so that you don't actually have to call the fetch() method in a while loop to go through a result set.
If you were to do this to a PDO object before a query: (Ideally only once right after creating the object.)
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
Then you can use a foreach loop on the result set to get row arrays with field names, instead of using a while loop.
$dbRelaties = array();
foreach ($stmt as $row) {
$dbRelaties[$row['pkRelatieID']] = $row;
}

Array not containing values when using "in_array" (php) w/ mysql_query

I continue to struggle with array! This is probably easy to answer.
I'm retrieving a data set from MYSQL w/ PHP. I get an array that has the 1st row (ala the mysql_fetch_array). Typically I would just loop through this and get each value, but in this case I'm already in the middle of a loop and I need to find out if a particular value exists in the full data set (which will be more than 1 row).
I figured I could just loop through and put all the values into an array with something like:
$query = "SELECT MapId FROM Map Where GameId = $gl_game_id";
$result_set = mysql_query($query, $connection);
confirm_query($result_set);
$map_set = array();
while($row = mysql_fetch_assoc($result_set)) {
$map_set[] = $row;
}
When I print_r this, I do in fact get the full data set (e.g. all rows of MapId from table Map).
So now, when I go to look in there and see if a value (that is coming out of this other loop) exists, it won't find it.
So my code looks like:
if (in_array($i, $map_set)) {
echo "yes, it's there baby!";
}
But it doesn't work. I tried hard coding the array, and that does in fact work. So there is simply something wrong with the way I'm constructing my array that this function doesn't like it.
if (in_array($i, array(40,12,53,65))) {
echo "yes, it's there baby!";
}
arrrg... I do hate being a noobie at this.
Function mysql_fetch_assoc returned array.
If you make print_r($map_set) then you will see that is 2-dimension array. Sure in_array not worked.
Just replace $map_set[] = $row; by $map_set[] = $row["MapId"]; and then try again.

How to display all data from a table?

Well i've been searching google, but I still can't find out how to do this.
I'm a beginner in php so i'm really stumped.
Anyways what I need to do is get all the data from a table and display it on my page.
Like
Contents of row 1
Contents of row 2
etc.
Well that's nice, get down voted for asking for help.
This might help you
print_r() displays information about a variable in a way that's readable by humans.
print_r(), var_dump() and var_export() will also show protected and private properties of objects with PHP 5. Static class members will not be shown.
Remember that print_r() will move the array pointer to the end. Use reset() to bring it back to beginning.
http://php.net/manual/en/function.print-r.php
This is pretty much PHP DB access 101
$pdo = new PDO('mysql:host=localhost;dbname=myDbName', 'username', 'password');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $pdo->prepare('SELECT * FROM a_table');
$stmt->execute();
$resultSet = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($resultSet as $idx => $row) {
echo '<p>Contents of row ', $idx + 1, '</p><dl>';
foreach ($row as $col => $val) {
printf('<dt>%s</dt><dd>%s</dd>',
htmlspecialchars($col),
htmlspecialchars($val));
}
echo '</dl>';
}
I think google should have given you your answer since this is a rather easy to answer question, but when starting, you don't always know what to search for.
Anyways, hope this helps.
<?php
// connect with you database, returns boolean so you know if you succeeded or not
$con = mysql_connect($database,$username,$password);
if(!$scon){
die('Could not connect to database'); // Stop execution if connection fails
}
//create your query
$query = "Place your database query here";
//get the results
$result = mysql_query($query);
//now you want to go through each row of the result table and echo the contents, or
//use them for whatever reason
while($row = mysql_fetch_array($result)){
echo $row['field_you_want_to_display'];
echo $row['another_field_you_want_to_display']; //You see where this is going
}
//After doing what you want, close the connection to the database
mysql_close($con);
?>
Also, you may want to take a look at the documentation of php for find out what functions you have not seen before do.

Categories