About the mysql_query -> mysql_fetch_array() procedure - php

Sample code:
$infoArray = array();
require_once("connectAndSelect.php");
// Connects to mysql and selects the appropriate database
$sql = "SOME SQL";
if($results = mysql_query($sql))
{
while($result = mysql_fetch_array($results, MYSQL_ASSOC))
{
$infoArray[] = $result;
}
}
else
{
// Handle error
}
echo("<pre>");
print_r($infoArray);
echo("</pre>");
In this sample code, I simply want to get the result of my query in $infoArray. Simple task, simple measures... not.
I would have enjoyed something like this:
$sql = "SOME SQL";
$infoArray = mysql_results($sql);
But no, as you can see, I have two extra variables and a while loop which I don't care for too much. They don't actually DO anything: I'll never use them again. Furthermore, I never know how to call them. Here I use $results and $result, which kind of represents what they are, but can also be quite confusing since they look so much alike. So here are my questions:
Is there any simpler method that I
don't know about for this kind of
task?
And if not, what names do you
give those one-use variables? Is
there any standard?

The while loop is really only necessary if you are expecting multiple rows to be returned. If you are just getting one row you can simply use mysql_fetch_array().
$query = "SOME SQL";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
For single line returns is the standard I use. Sure it is a little clunky to do this in PHP, but at least you have the process broken down into debug-able steps.

Use PDO:
<?php
/*** mysql hostname ***/
$hostname = 'localhost';
/*** mysql username ***/
$username = 'username';
/*** mysql password ***/
$password = 'password';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=mysql", $username, $password);
$sql = "SELECT * FROM myTable";
$result = $dbh->query($sql)
//Do what you want with an actual dataset
}
catch(PDOException $e) {
echo $e->getMessage();
}
?>

Unless you are legacied into it by an existing codebase. DONT use the mysql extension. Use PDO or Mysqli. PDO being preferred out of the two.
Your example can be come a set of very consise statements with PDO:
// create a connection this could be done in your connection include
$db = new PDO('mysql:host=localhost;dbname=your_db_name', $user, $password);
// for the first or only result
$infoArray = $db->query('SOME SQL')->fetch(PDO::FETCH_ASSOC);
// if you have multiple results and want to get them all at once in an array
$infoArray = $db->query('SOME SQL')->fetchAll(PDO::FETCH_ASSOC);
// if you have multiple results and want to use buffering like you would with mysql_result
$stmt = $db->query('SOME SQL');
foreach($stmt as $result){
// use your result here
}
However you should only use the above when there are now variables in the query. If there are variables they need to be escaped... the easiest way to handle this is with a prepared statement:
$stmt = $db->prepare('SELECT * FROM some_table WHERE id = :id');
$stmt->execute(array(':id' => $id));
// get the first result
$infoArray = $stmt->fetch(PDO::FETCH_ASSOC);
// loop through the data as a buffered result set
while(false !== ($row = $stmt->fetch(PDO::FETCH_ASSOC))){
// do stuff with $row data
}

Related

Print MySQL Output Based on Query String Value

I'm trying to take a query string param such as ?table=products and have mysql return all the rows for the "products" table in mysql. I tried running the code below in my browser, but I just get a blank white page. I know the mysql server/username/pass information is correct, I've tested the query in mysql and it works fine.
I guess I have two question:
What am I doing wrong?
How come I can't see any error messages when php has an issue?
e.g. code:
<?php
// Get query string parameter value
$keys = array_keys($_GET);
$key = $keys[0];
$value = $_GET[$key];
// Setup connection to mysql database
$serverName = "localhost";
$username = "root";
$password = "password";
$dbname = "webserver";
$conn = new mysqli($serverName, $username, $password, $dbname);
// SQL query
$sql = "SELECT * FROM $value";
$result = $conn->query($sql);
// Print results
echo $result;
?>
Follow the instuctions on below link to enable php.ini errors
How do I get PHP errors to display?
VULNERABLE IMPLEMENTATION WARNING
The above comments clearly mention the side effects of this implementation.
Since knowing the actual bug is a developer's right! Continue reading the answer keeping the safety of software and its users in mind.
You are trying to print $result which is not valid since its an object.
You can do the following instead:
$response = array();
$sql = "SELECT * FROM $value";
$result = $conn->query($sql);
// Print results
if ($result) {
while($row = $result->fetch_array(MYSQL_ASSOC)) {
$response[] = $row;
}
}
echo json_encode($response);
What am I doing wrong?
Sadly, pretty much everything.
// Get query string parameter value
$keys = array_keys($_GET);
$key = $keys[0];
$value = $_GET[$key];
You are dereferencing a named value based on its position. And its totally unnecessary. Consider:
$value=$_GET['table'];
...
$conn = new mysqli($serverName, $username, $password, $dbname);
Where is your error checking to see if $conn was initialized?
$result = $conn->query($sql);
again, no error checking.
echo $result;
$result here is a mysqli_result object. You need to call some methods on it to get the data out.
while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
var_export($row);
}
How come I can't see any error messages when php has an issue?
Have you tested that the default handlers produce output in your browser? You're not overriding the config in php.ini in the code you've shown us. Did you check your logs?
ini_set('diplay_error', 1);
error_reporting(E_ALL);
I just get a blank white page
Would it be so hard to put
print "finished";
at the end of the code? Then you'd at least know if the code executed.
The main issue you have right now is you need to get the results
while ($row = $result->fetch_assoc()) {
//do something with row
}
See ( for mysqli->query method )
http://php.net/manual/en/mysqli.query.php
false on failure and mysqli_query() will return a mysqli_result object on success
See ( for the result objects definition )
http://php.net/manual/en/class.mysqli-result.php
Now as others mentioned I would never just concatenate user data into your query. Imagine a hacker knows the name of a valid table, not hard considering your sending it through the request. All they would have to do is send a value like this:
$value = 'real_table; DROP DATABASE';
And your query becomes.
$sql = "SELECT * FROM real_table; DROP DATABASE";
I won't say that this would actually work as there are ( maybe ) some restrictions on running multiple queries in a single request,user permissions etc... That might save your bacon, but I certainly wouldn't risk it.
So you have 2 choices.
Use a white list of tables
Query the DB for the schema
The first one is easy to do, make a list of tables
$whitelist = [
'table1',
'table2'
];
Then compare your user input
$safeTable = false;
if( false !== ($index = array_search($table, $whitelist))) {
$safeTable = $whitelist[$index];
}else{
//log error and
exit();
}
// SQL query
$sql = "SELECT * FROM $safeTable";
$result = $conn->query($sql);
For the second one,
$schema = $conn->query('SELECT `TABLE_NAME` FROM `information_schema`.`TABLES` WHERE `TABLE_SCHEMA` LIKE "database"');
$whitelist = [];
while ($row = $result->fetch_assoc()) {
$whitelist[] = $row['TABLE_NAME'];
}
$safeTable = false;
if( false !== ($index = array_search($table, $whitelist))) {
$safeTable = $whitelist[$index];
}else{
//log error and
exit();
}
// SQL query
$sql = "SELECT * FROM $safeTable";
$result = $conn->query($sql);
This will return a list of all the tables in that database, from which you can build an array and then compare. The nice thing about the second one is that if you add a table then you don't have to change the code, which may or may not be a good thing. You have to have a user with permission to read from information_schema database. And you have to do an additional query.
-note- I am not directly using the users input, I'm using their input to find my data. It's less prone to breaking when there is a coder error. Consider this:
///all my codes are broken;
--if(!in_array($_GET['table'], $whitelist))) {
-- //log error and
-- exit();
--}
// SQL query
$sql = "SELECT * FROM {$_GET['table']}";
$result = $conn->query($sql);
Against this:
$safeTable = false;
// all my codes are broken
-- if( false !== ($index = array_search($_GET['table'], $whitelist))) {
-- $safeTable = $whitelist[$index];
-- }else{
-- //log error and
-- exit();
-- }
// SQL query
$sql = "SELECT * FROM $safeTable"; //$safeTable is undefined or false;
$result = $conn->query($sql);
Were using our code for inclusion, instead of exclusion. So if it breaks, it's never included. The other way, if it breaks it's never excluded. Which is not a situation we want to be even remotely possible.
I hope that helps you understand some of the pitfalls. The #1 rule for SQL (or anything on the web), is Never Trust the User. Never put their data into your SQL.

PHP - Passing pdo connection query via php function

So i'm trying to pass PDO Query by using php, like this(index.php):
include("dbconn.php");
mysqlConnect("'SELECT * FROM users WHERE name =' . $conn->quote($name))", "jeff");
while my dbconn file that contains the function is(dbconn.php):
function mysqlConnect($queryString, $name) {
// DB Credentials
$dbName = 'db';
$dbUser = 'root';
$dbPass = '';
$dbHost = 'localhost';
try {
$conn = new PDO("mysql:host=$dbHost;dbname=$dbName", $dbUser, $dbPass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Here goes the first parameter, then it uses the second parameter as a variable
$data = $conn->query($queryString);
// So the output should be this:
// $data = $conn->query('SELECT * FROM myTable WHERE name = ' . $conn->quote($name));
foreach($data as $row) {
print_r($row);
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
}
So in my function call the php actually executes the $conn->quote($name)) code, making my application not work.
How should i do this? is this allowed in php?
Edit:
or in other words: i call a function and give it 2 parameters, one of the parameters(even tho it's in double quotes) is executed by php which shouldn't happen. How can i fix this
The way you wrote, it will never work. You just have to learn to distinguish a string literal from executable code.
Anyways, you don't need such a frankenstein at all. There is already a mechanism to put your variable in the query, called prepared statements. You just have to use them.
There are other issues with your code too. I've described them all in the article I wrote recently, The only proper guide on PDO, I am sure you will find it interesting - all the issues like wrong error handling, utterly wrong way to connect, lack of prepared statements - all described there. Having all of them solved, here goes the proper function you need:
function pdo($sql, $data=[])
{
global $pdo; // you can add a call to your favorite IoC here.
$stmt = $pdo->prepare($sql);
$stmt->execute($data);
return $stmt;
}
used as
include("dbconn.php");
$user = pdo("SELECT * FROM users WHERE name = ?", ["jeff"])->fetch();
var_dump($user);
this is how PDO have to be used.
By returning a statement, you'll be able to use all the power of PDO, getting data you need in one line, say a list
$news = pdo("SELECT * FROM news ORDER BY id DESC")->fetchAll();
var_dump($news); // already an array
or just a single value
$count = pdo("SELECT count(*) FROM posts WHERE author=?", [$id])->fetchColumn();
var_dump($count); // already a number
or simply by iterating results one by one
$news = pdo("SELECT * FROM news ORDER BY id DESC")->fetchAll();
foreach ($news as $row) {
var_dump($row);
}
and so on.

Data transfer from one database to another using php and json

I want to make a data transfer from one database to another using PHP and JSON. The first MySQL connection gets and prints the data (which is working), but the second MySQL connection doesn't insert the data in the 2nd database. I don't know how to execute the INSERT QUERY in order to start filling up the other database(retrieve data from json encode).
This is what I get from the first database:
[{"0":"1","productid":"1","1":"0","parent":"0","2":"","language":"","3":"iPod Shuffle","prodname":"iPod Shuffle","4":"1","prodtype":"1","5":"","prodcode":"","6":"","prodfile":"","7":"
And here is my UPDATED code:
<?php
include 'config/config.php';
//include(dirname(__FILE__) . "/settings.inc.php");
//database 1
$data = array();
$conn = #mysql_connect($GLOBALS['VCS_CFG']["dbServer"],$GLOBALS['VCS_CFG']["dbUser"], $GLOBALS['VCS_CFG']["dbPass"]);
if ($conn){
if (mysql_select_db($GLOBALS['VCS_CFG']["dbDatabase"])) {
$SQL = "SELECT * FROM vc_products";
$q = mysql_query($SQL);
while($row = mysql_fetch_array($q))
{
$json_output[] = $row;
}
echo json_encode($json_output);
$data = json_encode($json_output);
}
mysql_close($conn);
}
// database 2
$con = #mysql_connect($GLOBALS['_DB_SERVER_'],$GLOBALS['_DB_USER_'], $GLOBALS['_DB_PASSWD_']);
if ($con) {
if (mysql_select_db($GLOBALS['_DB_NAME_'])) {
$sql = "INSERT INTO ps_order_detail(product_name) VALUES('".$data[0][8]."')";
$Q = mysql_query($sql);
foreach ($data as $key => $value)
{
$Q -> bind_param(
's', // the types of the data we are about to insert: s = string ( i = int )
$value['prodname']
);
$Q->execute();
}
$Q->close();
}
mysql_close($conn);
}
?>
I don't see you are executing any insert query ¿?
You are just building the string.
A few problems:
You are encoding twice instead of encoding and decoding;
You need to add error handling (PDO and mysqli can throw exceptions, very useful);
You need to get rid of the error supressor operator #;
You should switch to PDO or mysqli and prepared statements to avoid sql injection problems and because the mysql_* functions are deprecated.
Not related, but why would you encode and decode to json in the same script when you really want to use the original array?

Initializing variable from PDO query

$q = $db->query(" SELECT username FROM users WHERE userident = '1' ");
echo $q; //error
print_r $q; //prints the query information (SELECT ... etc)
How do I go about getting the specific value of the element I am querying? Say the element under column username and where userident equals '1' contains the value "Patrick"; how do I initialize this string into a variable?
//same query as above
$user = $q;
echo $user; //prints "Patrick"
Sorry if this is something so rudimentary and mundane, but I've never done this outside of a foreach() loop. I'd normally iterate through rows to print specific details. The below works, but the foreach() is unnecessary as far as I understand.
foreach($q as $p) {
$user = $p["username"];
}
echo $print; //this correctly prints "Patrick"
Surely there's a method I missed somewhere?
Using the query method pretty much defeats the purpose of using prepared statements. Plus, I believe for what you're looking for, it isn't quite right.
<?php
if (!isset($_POST['id'])) {
exit;
}
$userId = $_POST['id'];
$db = new PDO(/* Stuff */);
$sql = '
SELECT username
FROM users
WHERE id = :id';
// Get a prepared statement object.
$statement = $db->prepare($sql);
// Bind a parameter to the SQL code.
$statement->bindParam(':id', $userId, PDO::PARAM_INT);
// Actually get the result.
$result = $statement->fetch(PDO::FETCH_ASSOC);
// Close the connection.
$statement->closeCursor();
// Print the result.
print_r($result);
Alternately you can use $statement->fetchAll() to gather more than one result.
Edit: I didn't actually run this code, so you might have to tinker with it to get it working right.

Store elememts of a datatable into an array

I have a database table made in phpmyadmin. I want the elements of the table to be stored row-wise in an array. I have three columns named edge_id, vertexA and VertexB. I want the elements of these three columns to be stored into an array.
I don't know those commands for PHP. Please help me out.
i have columns in my table named
"vertexa" and "vertexb",i want to
store the colums in two separate
arrays ...how can i do it??
The simplest way would be:
$db = new PDO('mysql:host=localhost;dbname=your_db_name;', $user, $password);
$vertices_a = array();
$vertices_b = array();
foreach($db->query('SELECT * from your_table_name') as $row){
$id = $row['edge_id'];
// add them to the proper array using the edge_id as the index -
// this assumes edge_id is unique
$vertices_a[$id] = $row['vertexa'];
$vertices_b[$id] $row['vertexb'];
}
So with PDO:
$db = new PDO('mysql:host=localhost;dbname=your_db_name;', $user, $password);
foreach($db->query('SELECT * from your_table_name') as $row){
echo $row['edge_id'];
echo $row['vertexA'];
echo $row['vertexB'];
}
Now if you need to use input data you need to escape it. The best way to do this is to use a prepared statement because escaping is handle when the parameters are bound to the query.
Lets say for example you want to use the edge_id supplied from a get request like mysite.com/show-boundry.php?edge=5...
$db = new PDO('mysql:host=localhost;dbname=your_db_name;', $user, $password);
// create a prepared statement
$stmt = $db->prepare('SELECT * from your_table_name WHERE edge_id = ?');
// execute the statement binding the edge_id request parameter to the prepared query
$stmt->execute(array($_GET['edge']));
// loop through the results
while(false !== ($row = $stmt->fetch(PDO::FETCH_ASSOC))){
echo $row['edge_id'];
echo $row['vertexA'];
echo $row['vertexB'];
}
Also you shouldnt use mixed case column/table names like vertexA instead use underscore separators like vertex_a.
You first need to connect to the database:
$link = mysql_connect('localhost','username','password');
if (!$link) {
// Cannot connect
}
$ret = mysql_select_db('database-name', $link);
if (!$ret) {
// Cannot select database
}
Then you need to execute your query:
$ret = mysql_query('SELECT * FROM `table`;', $link);
if (!$ret) {
// Query failed
}
Then you simply load each row:
$data = array();
while ($row = mysql_fetch_assoc($ret)) {
$data[] = $row;
}
Then you should free your request results
mysql_free_result($ret);
And voilà.
$res = mysql_query("............");
$row = mysql_fetch_array($res);
Checkout: mysql_fetch_array PHP page

Categories