Store elememts of a datatable into an array - php

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

Related

Fetch multiple rows in mysql single query in php with different id

I have different id's, i am getting the values of these id from users
$id=array();
$id[0]=$_GET["id0"];
$id[1]=$_GET["id1"];
$id[2]=$_GET["id2"];
now to fetch data from database i am using following query:
for($j=0;$j<count($id);$j++)
{
$res=mysql_query("SELECT * FROM mutable WHERE id='$id[$j]'")
while($row=mysql_fetch_array($res))
{
$row[]=array("email"=>$row[2],"name"=>$row[3],"address"=>$row[5]);
echo JSON_encode($row);
}
}
now i am getting proper result from this query using for loop but the result is not in proper JSON format, is there any way to do it more efficentyly and getting proper result in JSON array and JSON object format
Place json_encode() outside of your loops.
Let's modernize and refine things...
*Unfortunately prepared statements that use an IN clause suffer from convolution. pdo does not suffer in the same fashion.
Code: (untested)
if(isset($_GET['id0'],$_GET['id1'],$_GET['id2'])){
$params=[$_GET['id0'],$_GET['id1'],$_GET['id2']]; // array of ids (validation/filtering can be done here)
$count=count($params); // number of ids
$csph=implode(',',array_fill(0,$count,'?')); // comma-separated placeholders
$query="SELECT * FROM mutable WHERE id IN ($csph)";
$stmt=$mysqli->prepare($query); // for security reasons
array_unshift($params,str_repeat('s',$count)); // prepend the type values string
$ref=[]; // add references
foreach($params as $i=>$v){
$ref[$i]=&$params[$i]; // pass by reference as required/advised by the manual
}
call_user_func_array([$stmt,'bind_param'],$ref);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_array(MYSQLI_NUM))
$rows=["email"=>$row[2],"name"=>$row[3],"address"=>$row[5]];
}
$stmt->close();
echo json_encode($rows);
}
Three things:
Always, always, always used prepared statements and bound parameters when dealing with untrusted (i.e., $_GET) input. Just do it.
As regards your problem with JSON, you only need to run json_encode once:
$results = [];
for($j=0;$j<count($id);$j++) {
...
while($row=mysql_fetch_array($res)) {
results[] = ...
}
}
json_encode( $results );
Use a single SQL statement, since you have a known number of IDs to collect:
$dbh = new PDO($dsn, $user, $password);
$sql = "SELECT * FROM mutable WHERE id IN (?, ?, ?)";
$sth = $dbh->prepare( $sql );
foreach ( $sth->execute( [$_GET['id0'], $_GET['id1'], $_GET['id2']] ) as $row ) {
...
This is more efficient then multiple round trips to the database. For this contrived case it probably doesn't matter, but getting into good habits now will serve you in the long run.
you have used $row wrongly, declare array variable outside of loop like
$json_response = array();
for($j=0;$j<count($id);$j++) {
$res=mysql_query("SELECT * FROM mutable WHERE id='$id[$j]'")
while($row=mysql_fetch_array($res)) {
$json_response[]=array("email"=>$row[2],"name"=>$row[3],"address"=>$row[5]);
echo json_encode($json_response); // not good to echo here
}
}
// echo json_encode($json_response); // ideally echo should be here

Getting a multi dimensional array from a mysql database

Right now im using Mysqli to retrieve data from a Mysql Database, The code im using is difficult to understand and from my understanding has depreciated functions or itself in entire is depreciated.
If i could get some insight and maybe some updated techniques on my Qoal of retrieving data from a mysql DB.
mysqli prepared statements
What i have so far is this:
$param = 1;
$mysqli = new mysqli("127.0.0.1", "user", "password", "databaseName");
$mysqli->query('SELECT reply_id FROM replies WHERE reply_topic = ? ORDER BY reply_date ASC');
$mysqli->bind_param('i',$param)
$mysqli->execute();
$row = bind_result_array($mysqli);
while($mysqli->fetch()){
$set[$row['']] = getCopy($row);
}
$mysqli->free_result();
return $set;
function bind_result_array($stmt)
{
$meta = $stmt->result_metadata();
$result = array();
while ($field = $meta->fetch_field())
{
$result[$field->name] = NULL;
$params[] = &$result[$field->name];
}
call_user_func_array(array($stmt, 'bind_result'), $params);
return $result;
}
function getCopy($row)
{
return array_map(create_function('$a', 'return $a;'), $row);
}
You need to clean up the call on the database first. $mysqli->query has send the query before you bound parameters and so on.
Replace with the following;
$stmt = $mysqli->prepare('SELECT reply_id FROM replies WHERE reply_topic = ? ORDER BY reply_date ASC');
$stmt->bind_param('i',$param)
$stmt->execute();
The $mysqli->prepare returns a new object that you should bind values to and then execute. It avoids SQL injection!
None of this is depreciated. mysqli_ is exactly what you should use.
As all you want is an array of the results, you can use the following code to do so - no user functions required.
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
$set[] = $row['reply_id'];
}
For each row in the while, each field is saved into an array with the column name as the key. So $row['reply_id'] contains the value of the reply_id column in the database. Above I have saved this value to an array called $set, and when it loops over the next result row it saves the next value to that array too.
You can manipulate the result before or after saving it to the new array, as you see fit.
Hope this helps.

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?

Jquery Ajax PHP Mysql Autocomplete not Functioning

Can someone please take a look at this link and let me know why the auto complete text box is not functioning?
What I have is a Table called Brangays in a MySQL datadabase "157400X_XXXXXX which contains:
I have these files as PHP files aswell
1-:Get_Auto1.php
<?php
// Database Connection
include("configPDO.php");
// Query to get the usable suggestions
$likeString = '%' . $_GET['term'] . '%';
// We Will prepare SQL Query
$STM = $dbh->prepare("SELECT Barangay FROM Barangays WHERE Barangay LIKE :likeString");
// bind parameters, Named parameters always start with colon(:)
$STM->bindParam(':likeString', $likeString);
// For Executing prepared statement we will use below function
$STM->execute();
// we will fetch records like this and use foreach loop to show multiple Results
$STMrecords = $STM->fetchAll();
// Deifne array for category.
$Category_array = array();
// Use for each loop to push all results in category array.
foreach($STMrecords as $row)
{
// Store all values in $result variable.
$result = $row[0];
// push all values in category array using array_push function which treats array as a stack, and pushes the passed variables onto the end of array.
array_push($Category_array, $result);
}
// encode it using json_encode which returns a string containing the JSON representation of value.
$json = json_encode($Category_array);
// echo it for getting it using Ajax function explained above.
echo $json;
?>
2- configPDO.php
<?php
// mysql hostname
$hostname = 'fdb3.xxxxxxx.net';
// mysql username
$username = '15740xx_xxxxxx';
// mysql password
$password = 'xxxxxxx';
// Database Connection using PDO with Try Catch Statements
try {
$dbh = new PDO("mysql:host=$hostname;dbname=1xxxxx_xxxxxx", $username, $password);
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>

About the mysql_query -> mysql_fetch_array() procedure

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
}

Categories