MYSQL PHP PDO Fill table with database data - php

I want to give out a for every line in my database.
It seems that it is working but only returns the first column.
Note: There are values for the empty fields in database!
$columns = "Ticket, Last_Modified_Date, Requester";
Heres my code:
function getTicket($columns){
echo($columns);
global $db_host, $db_name, $db_user, $db_pass;
$db = new PDO("mysql:host=$db_host;dbname=$db_name;charset=utf8", "$db_user", "$db_pass");
$result = $db->prepare("SELECT $columns FROM tickets");
if ($result->execute()){
echo("<b>Successfully!</b><br><br>");
$rows = $result->fetchAll(PDO::FETCH_ASSOC);
$col_names = explode(',', $columns);
foreach($rows as $row){
echo("<tr>");
foreach($col_names as $col_name){
if (!isset($row[$col_name])){
continue;
}
echo("<td>".$row[$col_name]."</td>");
}
echo("</tr>");
}
}
else{
echo("<b>FAILED!</b><br><br>");
}
$db = null;
}

->fetch() returns only one value of the rows.
Use ->fetchAll() ( PHP Documentation ) if you want to return all of your results.

There are a couple of issues here, first you should use ->fetchall() which will return ALL the result rows in one hit into an array.
Second you are overwriting your $result statement handle with the row being returned by ->fetch
function getTicket($columns){
global $db_host, $db_name, $db_user, $db_pass;
$db = new PDO("mysql:host=$db_host;dbname=$db_name;charset=utf8", "$db_user", "$db_pass");
$result = $db->prepare("SELECT $columns FROM tickets");
if ($result->execute()){
echo("<b>Successfully!</b><br><br>");
// CHANGES HERE
$rows = $result->fetchall(PDO::FETCH_ASSOC);
$col_names = explode(',', $columns); //make array of csv
foreach($rows as $row){
foreach( $col_names as $col_name ) {
echo '<td>' . $row[$col_name] . '</td>';
}
}
}else{
echo("<b>FAILED!</b><br><br>");
}
$db = null;
}

Related

Passing PHP array as parameter for SQL WHERE clause

Adapting an answer from here to try and pass an array as the parameter for a WHERE clause in MySQL. Syntax seems okay but I'm just getting null back form the corresponding JSON. I think understand what it is supposed to do, but not enough that I can work out where it could be going wrong. The code for the function is;
public function getTheseModulesById($moduleids) {
require_once 'include/Config.php';
$con = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD);
// Check connection
if (!$con)
{
die("Connection error: " . mysqli_connect_error());
}
// selecting database
mysqli_select_db($con, DB_DATABASE) or die(mysqli_connect_error());
$in = join(',', array_fill(0, count($moduleids), '?'));
$select = "SELECT * FROM modules WHERE id IN ($in)";
$statement = $con->prepare($select);
$statement->bind_param(str_repeat('i', count($moduleids)), ...$moduleids);
$statement->execute();
$result = $statement->get_result();
$arr = array();
while($row = mysqli_fetch_assoc($result)) {
$arr[] = $row;
}
mysqli_close($con);
return $arr;
}
And the code outwith the function calling it looks like;
$id = $_POST['id'];
$player = $db->getPlayerDetails($id);
if ($player != false) {
$pid = $player["id"];
$moduleids = $db->getModulesByPlayerId($pid); //this one is okay
$modules = $db->getTheseModulesById($moduleids); //problem here
$response["player"]["id"] = $pid;
$response["player"]["fname"] = $player["fname"];
$response["player"]["sname"] = $player["sname"];
$response["modules"] = $modules;
echo json_encode($response);
[EDIT]
I should say, the moduleids are strings.

Flattening a SQL query result for PHP array

I have a SQL table (modules) with two columns (id, name). Now I can retrieve the rows from this through a PHP script but what I want is to use the value of id as the key, and the value of name as the value, in a multidimensional array. Then I want to be able to encode those into a JSON, retaining the relationship between key/value. I've muddled something together but it returns null.
the relevant code from index.php
$mod1 = $core["module1"];
$mod2 = $core["module2"];
$modules = $db->getModulesById($mod1, $mod2); //module names & ids
$response["module"]["mod1"] = $modules[$mod1];
$response["module"]["mod2"] = $modules[$mod2];
$response["module"]["mod1name"] = $modules[$mod1]["name"];
$response["module"]["mod2name"] = $modules[$mod2]["name"];
echo json_encode($response);
The function from DB_Functions.php
public function getModulesById($mod1, $mod2) {
require_once 'include/Config.php';
$con = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD);
// Check connection
if (!$con)
{
die("Connection error: " . mysqli_connect_error());
}
// selecting database
mysqli_select_db($con, DB_DATABASE) or die(mysqli_connect_error());
$query = "SELECT * FROM modules WHERE id= '$mod1' OR id='$mod2'";
$result = mysqli_query($con, $query);
$arr = array();
while($row = mysqli_fetch_assoc($result)) {
// process each row
//each element of $arr now holds an id and name
$arr[] = $row;
}
// return user details
return mysqli_fetch_array($arr);
close();
}
I've looked around but I'm just not 'getting' how the query return is then broken down into key/value for a new array. If someone could ELI5 I'd appreciate it. I'm just concerned with this aspect, it's a personal project so I'm not focusing on security issues as yet, thanks.
You are pretty well there
public function getModulesById($mod1, $mod2) {
require_once 'include/Config.php';
$con = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE);
// Check connection
if (!$con) {
die("Connection error: " . mysqli_connect_error());
}
$query = "SELECT * FROM modules WHERE id= '$mod1' OR id='$mod2'";
$result = mysqli_query($con, $query);
$arr = array();
while($row = mysqli_fetch_assoc($result)) {
$arr[] = $row;
}
// here is wrong
//return mysqli_fetch_array($arr);
// instead return the array youy created
return $arr;
}
And call it and then just json_encode the returned array
$mod1 = $core["module1"];
$mod2 = $core["module2"];
$modules = $db->getModulesById($mod1, $mod2); //module names & ids
$response['modules'] = $modules;
echo json_encode($response);
You should really be using prepared and paramterised queries to avoid SQL Injection like this
public function getModulesById($mod1, $mod2) {
require_once 'include/Config.php';
$con = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE);
// Check connection
if (!$con) {
die("Connection error: " . mysqli_connect_error());
}
$sql = "SELECT * FROM modules WHERE id= ? OR id=?";
$stmt = $con->prepare($sql);
$stmt->bind_param('ii', $mod1, $mod2);
$stmt->execute();
$result = $stmt->get_result();
$arr = array();
while($row = mysqli_fetch_assoc($result)) {
$arr[] = $row;
}
// here is wrong
//return mysqli_fetch_array($arr);
// instead return the array youy created
return $arr;
}
mysqli_fetch_array requires the result of a mysqli_query result. Passing the constructed array to mysqli_fetch_array() is not going to work.
If you want to have a specific value from a row to use as its key, you can't resolve this with any mysqli_* function. You could however construct it yourself:
while($row = mysqli_fetch_assoc($result)) {
// process each row
//each element of $arr now holds an id and name
$arr[$row['id']] = $row;
}
mysqli_close($con);
return $arr;
You should close the connection before returning the result, code positioned after a return will not be executed.

returning multiple rows from mysql in php

I'm trying to write a PHP-script that will fetch multiple rows from MySQL and return them as a JSONObject, the code works if I try to only fetch 1 row but if I try to get more than one at a time the return string is empty.
$i = mysql_query("select * from database where id = '$v1'", $con);
$temp = 2;
while($row = mysql_fetch_assoc($i)) {
$r[$temp] = $row;
//$temp = $temp +1;
}
If I write the code like this it returns what I expect it to, but if I remove the // from the second row in the while loop it will return nothing. Can anyone explain why this is and what I should do to solve it?
You are using an obsolete mysql_* library.
You are SQL injection prone.
Your code is silly and makes no sense.
If you really wan to stick to it, why simply not do:
while($row = mysql_fetch_assoc($i)) {
$r[] = $row;
}
echo json_encode($r);
And finally, an example using PDO:
$database = 'your_database';
$user = 'your_db_user';
$pass = 'your_db_pass';
$pdo = new \PDO('mysql:host=localhost;dbname='. $database, $user, $pass);
$pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
try
{
$stmt = $pdo->prepare("SELECT * FROM your_table WHERE id = :id");
$stmt->bindValue(':id', $id);
$stmt->execute();
$results = $stmt->fetchAll(\PDO::FETCH_ASSOC);
}
catch(\PDOException $e)
{
$results = ['error' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine());
}
echo json_encode($results);
You don't need the $temp variable. You can add an element to an array with:
$r[] = $row;

Import JSON in MySQL DB from Import.io

I'm trying to import data from a JSON feed using PHP into a MySQL database.
I have the code below but am not getting anywhere with it.
I keep just getting Connected to Database but nothing is being pulled in from the JSON data.
The JSON data is being created from a feed using import.io.
Any help appreciated
JSON data here
<?php
$data = file_get_contents('https://query.import.io/store/connector/e18543ae-48d1-47d3-9dc7-c3d55cab2951/_query?_user=363ec2db-fb95-413f-9a20-3fe89acbf061&_apikey=HOXvwSMX4HlmqH123i5HeELV6BwKq%2BFRInTzXc4nfl5VtP0pJyChxMT9AEiu1Ozi0vWZmUB%2BKcSsxHz2ElHNAg%3D%3D&format=JSON&input/webpage/url=http%3A%2F%2Fsports.yahoo.com%2Fgolf%2Fpga%2Fleaderboard');
$array = json_decode($data, true);
$rows = array();
$index = 0;
foreach($array['results'] as $mydata)
{
print_r($mydata);
echo "<br>";
foreach($mydata as $key => $value)
{
print_r ($key);
print_r ($value);
echo $index;
echo "<br><br>";
$rows[] = "('" . $value . "')";
}
echo "<br>";
$index++;
}
echo "<br><br><br>";
print_r ($rows);
$values = implode(",", $rows);
echo "<br><br><br>";
print_r ($values);
$hostname = 'localhost'; // write the rest of your query
$username = 'username';
$password = 'password';
try
{
$dbh = new PDO("mysql:host=$hostname;dbname=database", $username, $password);
echo 'Connected to database<br />'; // echo a message saying we have connected
$count = $dbh->exec("INSERT INTO import_io (total, round_1, round_2, round_3, round_4, thru, name/_source, name, today, name/_text, strokes) VALUES ($values)");
echo $count;// echo the number of affected rows
$dbh = null;// close the database connection
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
First of here we have to fetch every row and then do another loop to fetch every value contained in that row, in this way we will obtain a 2D Array containing the data to format to put after in the db.
$i = 0;
foreach($array['results'] as $result){
foreach ($result as $key => $value)
$rows[$i][] = "'" . $value . "'";
$i++;
}
Then, here we format the data in order to fit our query that will be executed for every row fetched before.
try{
$dbh = new PDO("mysql:host=$hostname;dbname=database", $username, $password);
foreach ($rows as $row) {
$row = implode(",",$row); //making a string from an array with each item separated by comma
$query = "INSERT INTO import_io (total, round_1, round_2, round_3, round_4, thru, name/_source, name, today, name/_text, strokes) VALUES ($row)<br>";
$count = $dbh->exec($query);
}
$dbh = null;// close the database connection
}catch(PDOException $e){
echo $e->getMessage();
}

Run a call from a function PHP

i'm building an website using php and html, im used to receiving data from a database, aka Dynamic Website, i've build an CMS for my own use.
Im trying to "simplify" the receiving process using php and functions.
My Functions.php looks like this:
function get_db($row){
$dsn = "mysql:host=".$GLOBALS["db_host"].";dbname=".$GLOBALS["db_name"];
$dsn = $GLOBALS["dsn"];
try {
$pdo = new PDO($dsn, $GLOBALS["db_user"], $GLOBALS["db_pasw"]);
$stmt = $pdo->prepare("SELECT * FROM lp_sessions");
$stmt->execute();
$row = $stmt->fetchAll();
foreach ($row as $row) {
echo $row['session_id'] . ", ";
}
}
catch(PDOException $e) {
die("Could not connect to the database\n");
}
}
Where i will get the rows content like this: $row['row'];
I'm trying to call it like this:
the snippet below is from the index.php
echo get_db($row['session_id']); // Line 22
just to show whats in all the rows.
When i run that code snippet i get the error:
Notice: Undefined variable: row in C:\wamp\www\Wordpress ish\index.php
on line 22
I'm also using PDO just so you would know :)
Any help is much appreciated!
Regards
Stian
EDIT: Updated functions.php
function get_db(){
$dsn = "mysql:host=".$GLOBALS["db_host"].";dbname=".$GLOBALS["db_name"];
$dsn = $GLOBALS["dsn"];
try {
$pdo = new PDO($dsn, $GLOBALS["db_user"], $GLOBALS["db_pasw"]);
$stmt = $pdo->prepare("SELECT * FROM lp_sessions");
$stmt->execute();
$rows = $stmt->fetchAll();
foreach ($rows as $row) {
echo $row['session_id'] . ", ";
}
}
catch(PDOException $e) {
die("Could not connect to the database\n");
}
}
Instead of echoing the values from the DB, the function should return them as a string.
function get_db(){
$dsn = "mysql:host=".$GLOBALS["db_host"].";dbname=".$GLOBALS["db_name"];
$dsn = $GLOBALS["dsn"];
$result = '';
try {
$pdo = new PDO($dsn, $GLOBALS["db_user"], $GLOBALS["db_pasw"]);
$stmt = $pdo->prepare("SELECT * FROM lp_sessions");
$stmt->execute();
$rows = $stmt->fetchAll();
foreach ($rows as $row) {
$result .= $row['session_id'] . ", ";
}
}
catch(PDOException $e) {
die("Could not connect to the database\n");
}
return $result;
}
Then call it as:
echo get_db();
Another option would be for the function to return the session IDs as an array:
function get_db(){
$dsn = "mysql:host=".$GLOBALS["db_host"].";dbname=".$GLOBALS["db_name"];
$dsn = $GLOBALS["dsn"];
$result = array();
try {
$pdo = new PDO($dsn, $GLOBALS["db_user"], $GLOBALS["db_pasw"]);
$stmt = $pdo->prepare("SELECT * FROM lp_sessions");
$stmt->execute();
$rows = $stmt->fetchAll();
foreach ($rows as $row) {
$result[] = $row['session_id'];
}
}
catch(PDOException $e) {
die("Could not connect to the database\n");
}
return $result;
}
Then you would use it as:
$sessions = get_db(); // $sessions is an array
and the caller can then make use of the values in the array, perhaps using them as the key in some other calls instead of just printing them.
As antoox said, but a complete changeset; change row to rows in two places:
$rows = $stmt->fetchAll();
foreach ($rows as $row) {
echo $row['session_id'] . ", ";
}
Putting this at the start of the script after <?php line will output interesting warnings:
error_reporting(E_ALL|E_NOTICE);
To output only one row, suppose the database table has a field named id and you want to fetch row with id=1234:
$stmt = $pdo->prepare("SELECT * FROM lp_sessions WHERE id=?");
$stmt->bindValue(1, "1234", PDO::PARAM_STR);
I chose PDO::PARAM_STR because it will work with both strings and integers.

Categories