I have the following code. Is there any way to combine and simplify it?
The output in the json.html file should be like this: ["abc","def","ghi"].
<?php
// Make a MySQL Connection
mysql_connect("localhost", "root", "admin") or die(mysql_error());
mysql_select_db("test1") or die(mysql_error());
// Get all the data from the "example" table
$result = mysql_query("SELECT * FROM test_auto_complete") or die(mysql_error());
$menu = array();
while($row = mysql_fetch_assoc($result))
{
$menu[] = array("id" => $row['username'],);
}
foreach($menu as $key=>$value)
{
$menu[$key] = $value['id'];
}
$my_json_content = json_encode($menu);
$file = 'json.html';
$current = file_get_contents($file);
file_put_contents($file, $my_json_content);
?>
I know the code looks bad, but even so, can someone help me?
Thanks
Haan
If you want to put content in file than just use file_put_contents
$my_json_content = json_encode($menu);
$file = 'json.html';
file_put_contents($file, $my_json_content);
And use this while loop without foreach
while($row = mysql_fetch_assoc($result))
{
$menu[] = $row['username'];
}
I won't even give you solution with mysql_* because they are depracated look at the solution in PDO
<?php
$dsn = 'mysql:dbname=test1;host=127.0.0.1';
$user = 'root';
$password = 'admin';
try{
$dbh = new PDO($dsn, $user, $password);
$menu = array();
foreach ($conn->query("SELECT * FROM test_auto_complete") as $row)
$menu[] = $row['username'];
file_put_contents('json.html', json_encode($menu));
}catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
?>
Tips:
Mysql_* functions are depracated and they don't support a lot of features of MySQL
Foreach in your case was senseless.
File_get_contents() in your code does not have any sense for me, what do you need the content of file for?
Variables are used for data which is going to be changed. For example in your case you use variable for json.html which seems to be constant, if so, then use constant string.
Related
hye, i'm having trouble in calling all the rows in one table. hope anyone could assist me solve the error:
<?php
require_once('database.php');
$result = mysql_query("SELECT * FROM events ");
while($row = mysql_fetch_array($result))
?>
I am not an expert on mysqli stuff (I use a Connection class I found somewhere which provides functions like selectMultipleRows($query) and so on) but I will try to give a good answer here.
assuming you already have created a connection $this->connID
$mysqli = $this->connID;
$result = $mysqli->query($query);
$data = $result->fetch_all(MYSQLI_ASSOC);
//stuff I do to make my life easier:
$return = array(); //for scoping reasons
if (isset($data[0]['id'])) {
foreach ($data as $value) {
$return[$value['id']] = $value;
}
} else {
$return = $data;
}
as far as I am concerned this should work.
edit
my class Connection basically works like this:
$this->connID = new mysqli($this->server, $this->user, $this->pass, $this->database);
if ($this->connID→connect_errno) { //debug stuff
var_dump($this->connID->connect_error);
}
$this->connID->set_charset("utf8");
I guess this is all you will need.
I'm migrating parts of my code from mySQL over to PDO and I can't seem to see what is wrong with my code.
I've got a try/catch statement and error reporting on, but i'm getting nothing at all.
Can anyone here see what is wrong?
The files that are relevant to this question are:
db_pdo.php
<?php
// Define connection
$db_host = "localhost";
$db_name = "winestore";
$db_user = "user";
$db_pass = "pass";
$db = new PDO("mysql:host=$db_host;dbname=$db_name", $db_user, $db_pass);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
?>
search.php
<?php
require_once ("MiniTemplator.class.php");
function getSearch($tableName, $attributeName) {
try {
require ("db_pdo.php");
$query = "SELECT DISTINCT {$attributeName} FROM {$tableName} ORDER BY {$attributeName}";
return $db->query($query);
} catch (PDOException $e) {
echo $e->getMessage();
exit;
}
}
function generatePage(){
$t = new MiniTemplator;
$t->readTemplateFromFile ("search_template.htm");
$rows = getSearch("region", "region_name");
while ($row = $result->fetch(PDO::FETCH_ASSOC)){
$t->setVariable('regionName', $row['region_name']);
$t->addBlock("regionName");
}
$rows = getSearch("grape_variety", "variety");
while ($row = $result->fetch(PDO::FETCH_ASSOC)){
$t->setVariable('variety', $row['variety']);
$t->addBlock("variety");
}
$rows = getSearch("wine", "year");
while ($row = $result->fetch(PDO::FETCH_ASSOC)){
$t->setVariable('minYear', $row['year']);
$t->addBlock("minYear");
}
$rows = getSearch("wine", "year");
while ($row = $result->fetch(PDO::FETCH_ASSOC)){
$t->setVariable('maxYear', $row['year']);
$t->addBlock("maxYear");
}
$t->generateOutput();
}
generatePage();
?>
You are storing in $rows, but you are using $result afterwards, which will be empty.
// $rows = getSearch("region", "region_name");
// should be this:
$result = getSearch("region", "region_name");
while ($row = $result->fetch(PDO::FETCH_ASSOC)){
Side note: You are creating a new database connection with every search. You should store your $db object and reuse it, instead of creating new instances of it. I'd recommend to wrap all these functions in a class where you store it, but since you stated that you are migrating existing code you could use global $db to pull the existing object into the variable scope of your function:
// include this file once at the beginning of your script
require_once("db_pdo.php");
function getSearch($tableName, $attributeName) {
global $db; // pull $db inside the variable scope
try {
// ...
Try it?
$rows = getSearch("region", "region_name");
but
$result->fetch(PDO::FETCH_$rows->fetch(PDO::FETCH_ASSOC)){ )){
to
$rows->fetch(PDO::FETCH_ASSOC)){
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;
I have a Microsoft Access Database, and I am trying to query the table using PHP, and output valid JSON. I have an equivalent code for a MSSQL database, am I am trying to make my code do the same thing, but just for the Access database.
Here is the MSSQL code
$myServer = "server";
$myDB = "db";
$conn = sqlsrv_connect ($myServer, array('Database'=>$myDB));
$sql = "SELECT *
FROM db.dbo.table";
$data = sqlsrv_query ($conn, $sql);
$result = array();
do {
while ($row = sqlsrv_fetch_array ($data, SQLSRV_FETCH_ASSOC)) {
$result[] = $row;
}
} while (sqlsrv_next_result($data));
$json = json_encode ($result);
sqlsrv_free_stmt ($data);
sqlsrv_close ($conn);
Here is what I tried for the MDB file
$dbName = "/filename.mdb";
if (!file_exists($dbName)) {
die("Could not find database file.");
}
$db = odbc_connect("Driver={Microsoft Access Driver (*.mdb)};Dbq=$dbName", $user, $password);
$sql = "SELECT *
FROM cemetery";
$data = $db->query($sql); // I'm getting an error here
$result = array();
// Not sure what do do for this part...
do {
while ($row = fetch($data, SQLSRV_FETCH_ASSOC)) {
$result[] = $row;
}
} while (sqlsrv_next_result($data));
$json = json_encode ($result);
I kind of followed this to try to connect to the database: http://phpmaster.com/using-an-access-database-with-php/
Currently this is giving me a 500 Internal Server Error. I'm expecting a string such as this to be saved in the variable $json
[
{
"col1":"col value",
"col2":"col value",
"col3":"col value",
},
{
"col1":"col value",
"col2":"col value",
"col3":"col value",
},
{
etc...
}
]
Can someone help me port the MSSQL code I have above so I can use it with an MDB database? Thanks for the help!
EDIT: I'm commenting out the lines one by one, and it throws me the 500 error at the line $data = $db->query($sql);. I looked in the error log, and I'm getting the error Call to a member function query() on a non-object. I already have the line extension=php_pdo_odbc.dll uncommented in my php.ini file. Anyone know what the problem could be?
You only need 1 loop,
fetchAll is your iterable friend:
while ($row = $data->fetchAll(SQLSRV_FETCH_ASSOC)) {
$result[] = $row;
}
odbc_connect doesn't return an object, it returns a resource. see (http://php.net/manual/en/function.odbc-connect.php) so you would need to do something like this.
$db = odbc_connect("Driver={Microsoft Access Driver (*.mdb)};Dbq=$dbName", $user, $password);
$oexec = obdc_exec($db,$sql);
$result[] = odbc_fetch_array($oexec);
and then you can iterate over results..
see also:
http://www.php.net/manual/en/function.odbc-fetch-array.php
http://www.php.net/manual/en/function.odbc-exec.php
I finally figured it out.
<?php
// Location of database. For some reason I could only get it to work in
// the same location as the site. It's probably an easy fix though
$dbName = "dbName.mdb";
$tName = "table";
// Throws an error if the database cannot be found
if (!file_exists($dbName)) {
die("Could not find database file.");
}
// Connects to the database
// Assumes there is no username or password
$conn = odbc_connect("Driver={Microsoft Access Driver (*.mdb)};Dbq=$dbName", '', '');
// This is the query
// You have to have each column you select in the format tableName.[ColumnName]
$sql = "SELECT $tName.[ColumnOne], $tName.[ColumnTwo], etc...
FROM $dbName.$tName";
// Runs the query above in the table
$rs = odbc_exec($conn, $sql);
// This message is displayed if the query has an error in it
if (!$rs) {
exit("There is an error in the SQL!");
}
$data = array();
$i = 0;
// Grabs all the rows, saves it in $data
while( $row = odbc_fetch_array($rs) ) {
$data[$i] = $row;
$i++;
}
odbc_close($conn); // Closes the connection
$json = json_encode($data); // Generates the JSON, saves it in a variable
?>
I use this code to get results from an ODBC query into a JSON array:
$response = null;
$conn = null;
try {
$odbc_name = 'myODBC'; //<-ODBC connectyion name as is in the Windows "Data Sources (ODBC) administrator"
$sql_query = "SELECT * FROM table;";
$conn = odbc_connect($odbc_name, 'user', 'pass');
$result = odbc_exec($conn, $sql_query);
//this will show all results:
//echo odbc_result_all($result);
//this will fetch row by row and allows to change column name, format, etc:
while( $row = odbc_fetch_array($result) ) {
$json['cod_sistema'] = $row['cod_sistema'];
$json['sistema'] = $row['sistema'];
$json['cod_subsistema'] = $row['cod_subsistema'];
$json['sub_sistema'] = $row['sub_sistema'];
$json['cod_funcion'] = $row['cod_funcion'];
$json['funcion'] = $row['funcion'];
$json['func_desc_abrev'] = $row['desc_abreviada'];
$json['cod_tipo_funcion'] = $row['cod_tipo_funcion'];
$response[] = array('funcionalidad' => $json);
}
odbc_free_result($result); //<- Release used resources
} catch (Exception $e) {
$response = array('resultado' => 'err', 'detalle' => $e->getMessage());
echo 'ERROR: ', $e->getMessage(), "\n";
}
odbc_close($conn);
return $response;
And finnally encoding the response in JSON format:
echo json_encode($response);
I'm learning PHP and I'm well versed with Java and C. I was given a practice assignment to create a shopping project. I need to pull out the products from my database. I'm using the product id to do this. I thought of using for loop but I can't access the prod_id from the database as a condition to check! Can anybody help me?! I have done all the form handling but I need to output the products. This is the for-loop I am using. Please let me know if I have to add any more info. Thanks in advance :)
for($i=1; $i + 1 < prod_id; $i++)
{
$query = "SELECT * FROM products where prod_id=$i";
}
I would suggest that you use PDO. This method will secure all your SQLand will keep all your connections closed and intact.
Here is an example
EXAMPLE.
This is your dbc class (dbc.php)
<?php
class dbc {
public $dbserver = 'server';
public $dbusername = 'user';
public $dbpassword = 'pass';
public $dbname = 'db';
function openDb() {
try {
$db = new PDO('mysql:host=' . $this->dbserver . ';dbname=' . $this->dbname . ';charset=utf8', '' . $this->dbusername . '', '' . $this->dbpassword . '');
} catch (PDOException $e) {
die("error, please try again");
}
return $db;
}
function getproduct($id) {
//prepared query to prevent SQL injections
$query = "SELECT * FROM products where prod_id=?";
$stmt = $this->openDb()->prepare($query);
$stmt->bindValue(1, $id, PDO::PARAM_INT);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $rows;
}
?>
your PHP page:
<?php
require "dbc.php";
for($i=1; $i+1<prod_id; $i++)
{
$getList = $db->getproduct($i);
//for each loop will be useful Only if there are more than one records (FYI)
foreach ($getList as $key=> $row) {
echo $row['columnName'] .' key: '. $key;
}
}
First of all, you should use database access drivers to connect to your database.
Your query should not be passed to cycle. It is very rare situation, when such approach is needed. Better to use WHERE condition clause properly.
To get all rows from products table you may just ommit WHERE clause. Consider reading of manual at http://dev.mysql.com/doc.
The statement selects all rows if there is no WHERE clause.
Following example is for MySQLi driver.
// connection to MySQL:
// replace host, login, password, database with real values.
$dbms = mysqli_connect('host', 'login', 'password', 'database');
// if not connected then exit:
if($dbms->connect_errno)exit($dbms->connect_error);
$sql = "SELECT * FROM products";
// executing query:
$result = $dbms->query($sql);
// if query failed then exit:
if($dbms->errno)exit($dbms->error);
// for each result row as $product:
while($product = $row->fetch_assoc()){
// output:
var_dump($product); // replace it with requied template
}
// free result memory:
$result->free();
// close dbms connection:
$dbms->close();
for($i=1;$i+1<prod_id;$i++) {
$query = "SELECT * FROM products where prod_id=$i";
$result = mysqli_query($query, $con);
$con is the Database connection details
you can use wile loop to loop thru each rows
while ($row = mysqli_fetch_array($result))
{
......
}
}
Hope this might work as per your need..
for($i=1; $i+1<prod_id; $i++) {
$query = "SELECT * FROM products where prod_id = $i";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
print_r($row);
}
}
I think you want all records from your table, if this is the requirement you can easily do it
$query = mysql_query("SELECT * FROM products"); // where condition is optional
while($row=mysql_fetch_array($query)){
print_r($row);
echo '<br>';
}
This will print an associative array for each row, you can access each field like
echo $row['prod_id'];