Retreive element from PhP array - php

I am getting data from database in PhP array data_areas like this:
$query_area = "SELECT name FROM area where id>0";
$result = pg_query($con, $query_area) or die("Cannot execute query: $query_area\n");
if(pg_num_rows($result))
{
$data_areas=array();
while($row=pg_fetch_row($result))
{
$data_areas[] = array(
'name'=>$row[0]
);
}
pg_free_result($result);
pg_close($con);
$area1=$data_areas[0];
$area2=$data_areas[1];
}
How to retrieve the element from array in different variables, for example, I tried to retrieve data in area1 and area2 variable. Thank you

you can write like this;
$data_areas[0]['name']

Try Below code
$query_area = "SELECT name FROM area where id>0";
$result = pg_query($con, $query_area) or die("Cannot execute query: $query_area\n");
if(pg_num_rows($result))
{
$data_areas=array();
while($row=pg_fetch_row($result))
{
$data_areas[] = array(
'name'=>$row[0]
);
}
pg_free_result($result);
pg_close($con);
$area1=isset($data_areas[0]['name']) ?$data_areas[0]['name'] : '' ;
$area2= isset($data_areas[1]['name']) ? $data_areas[1]['name'] : '';
}

So first things first. You need first of all set up your array that you retrieve your data from the db.
Inside your while loop , and considering that you know what each of the rows has as associated value you can do something like:
$data_areas[] = array(
'name' => $row[0],
'surname' => $row[1],
'email' => $row[2]
);
This will create your array with all the values.
Now if you want to access/assign it's of those array values i am pretty sure you will need new dedicated arrays as your query retrieves all data from the table (small note that you don't need where id>0 as your id is auto increment so it will always be greater than 0)
Having said that we can move forward.
In order to access this data you can simple try:
print_r($data_areas['name']);
This will return you an array of all the names you have. So you don't need new table you can use the already existing one you have.

You are writing like this
$row[0]
Try writing this
$row['name']

Related

MYSQL select only part of a column

I running a simple mysql query and trying to grab from the src column but I only want to grab the "video#.mp4" part - not the whole value (see picture attached below)
If anyone knows how to achieve this... I really appreciated it! Thank you for any help!
Code:
$con=mysqli_connect("localhost","test","123","test");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="SELECT id, title, src, type, poster_img FROM TABLE_NAME";
if ($result=mysqli_query($con,$sql))
{
$id = 0;
// Fetch one and one row
while ($row=mysqli_fetch_row($result))
{
// Show video#.mp4 here ///
echo '';
$id++;
}
// Free result set
mysqli_free_result($result);
}
mysqli_close($con);
I suggest you to store quality and video name in 2 different columns, because this will help you in searching etc.
In your example, you can achieve your desired result by using json_decode but again, it will work if you have valid json in src column.
Example:
$string = '[{"quality":"default","mp4":"video2.mp4"}]';
$array = json_decode($string,true);
print_r($array);
Result:
Array ( [0] => Array ( [quality] => default [mp4] => video2.mp4 ) )
Now you can get the index mp4 easily, if you have multiple file format, than you can group than inside your loop.

How to create variables using rows from mysql?

I would like to create a file like this:
<?php
$cssMainVersion = "1.0.3";
$cssBootStrapVersion = "1.0.1";
$cssElseVersion = "1.0.4";
$jpgVersion = "1.0.1";
$jsMainVersion = "1.0.1";
$jsElseVersion = "1.0.1";
?>
I have created a mySQL table that holds the variable name, and the variable data. For example, the first row contains "cssMainVersion" and the second row contains "1.0.3".
How would I loop thorugh each row and print that data in a new file according to the format above?
You can create variables dynamically with php
$query = mysqli_query($conn, 'SELECT id, cachename, cacheversion FROM cache');
while($row = mysqli_fetch_assoc($query)) {
$$row['cachename'] = $row['cacheversion'];
}
the $$ will be evaluted from right to left, so, first $row['field'] will be replaced with this value, let say cssMainVersion, then we have $cssMainVersion

why i am getting 0 at first, while parsing JSON data?

I am new to json, my aim is to maintain the history of specific columns(which are posted through $_POST in php) on every update in mysql using php. I took one json array for the history column and placed it in a while loop, after that I appended the variable which i want to merge with the previous one with array_merge() function. I am getting the output but starting with 0. Let me know how to append the required fields in a proper json format and also how to retrieve the json data in a div tag. Thanks in advance.
PHP Code:
<?php
$query = mysqli_query($conn,"SELECT `history` FROM projects WHERE `no` = '$id'");
$json_data = array();
while ($js = mysqli_fetch_assoc($query))
{
$json_data[] = $js['history'];
$j = $json_data;
}
?>
<?php
if(isset($_POST['submit'])){
if(isset($_GET['id'])){
$id = $_GET['id'];
$assign = mysqli_real_escape_string($conn,$_POST['assign']);
$end_date = mysqli_real_escape_string($conn,$_POST['end_date']);
$comments = mysqli_real_escape_string($conn,$_POST['comments']);
$end_date = [
'assigned_to' => $assign,
'end_date' => $end_date,
'comments' => $comments
];
$json = array_merge($j,$end_date);
$js = json_encode($json);
$ins = mysqli_query($conn,"UPDATE `projects` SET `assigned_to`='$assign',`end_date`='$end_date',
`status`='$status',`comments`='$comments'`history`= '$js' WHERE
`episode_no` = '$id'");
}
}
?>
JSON data in MYSQL :
{"0":"{"0":"{"0":"","assigned_to":"AAA","end_date":"2018-09-12","comments":"happy"}",
"assigned_to":"AAA","end_date":"2018-09-12","comments":"jolly"}",
"assigned_to":"AAA","end_date":"2018-09-12","comments":"xvbcvbdfghdfg"}
First of all, the answer to your question: you are loading an array of strings in $j, so the array_merge function won't work as expected:
$j[0] = 'some JSON string from DB';
$json = array_merge($j, $end_date);
the array_merge finds that the second argument is a sparse array, so it merges the keys as strings:
$json = [
'0' => 'the previous string',
'assigned_to' => ...
]
For your idea to work you probably need to store the new history item by appending to the array:
$j[] = $end_date;
$js = json_encode($j);
...
This would solve your issue.
But there is a very major issue here that you need to solve first. It's a OMG-like WTF-like issue. You are getting $id from user input (query parameters) and sending it to the DB without any fear. Suppose that the user sends
https://your.server/some/path?id=';TRUNCATE TABLE projects --'
(propery url-encoded of course). Now you are sending this to the database:
SELECT `history` FROM projects WHERE `no` = '';TRUNCATE TABLE projects --''
Bye bye projects. A user can do whatever to your database, change passwords, reassign foreign keys, set himself as administrator.
Please for the sake of whatever you believe in, use a proper ORM and never pass user input to the DB!!!

Echo php Variable from Mysql DB

This is my Entire Code:
<?php
$query = "SELECT category FROM html where id = '1' ";
$result = mysql_query($query);
//while loop to display mysql table field values in html text boxes
$i = 0;
while ($row = mysql_fetch_row($result)) {
$count = count($row);
$y = 0;
while ($y < $count) {
$c_row = current($row);
next($row);
$y = $y + 1;
}
$i = $i + 1;
$category = $c_row;
}
echo $category;
?>
I am showing the value of $categories variable using this code given below:
Categories ( '. $categories; .' )
Actaully, the above code including to is not directly written in php
web page. The code "Categories ( '. $categories; .' ) " is containing in the data base. Therefore $categories; cannot be parsed.
What I need is to show the Value:
Eg, if $categories = Books and Shelf;
I need, Categories ( '. $categories; .' ) :- Categories (Books and Shelf)
The $categories; value is already obtained in the php page before selecting from Mysql Table.
How can I parse php variable inserted in Mysql Row?
Categories ( '. $categories; .' ) :- The complete html tag is putted in the data base. The complete html code in the Mysql DB.
I'd like to know why you are storing variable references like that in your db but to solve it you could simply do something like this:
/*
assuming $string contains EXACTLY this
<h4>Categories ( '. $categories; .' ) </h4>
*/
echo str_replace('\'. $categories; .\'',$categories, $string);
If you commonly need to do word replacement on strings stored in a database I would recommend one of the following instead:
1) Use sprintf() and store your string like this:
$string = '<h4>Categories ( %s ) </h4>';
echo sprintf($string, $categories);
2) Use str_replace() and format string with braces around replacements:
$string = '<h4>Categories ( {categories} ) </h4>';
echo str_replace('{categories}', $categories, $string);
The benefit of that last one is you could store all kinds of variable references and replace them accordingly without having to know if they exist in the string:
$string = 'Hello, my name is {firstname} and I live in {city}, {state}';
$replace = ['{firstname}','{lastname}','{address}','{city}','{state}'];
$info = [
'firstname' => 'john',
'lastname' => 'doe',
'address' => '123 main st',
'city' => 'somewhere',
'state' => 'IL'
];
echo str_replace($replace, $info, $string);
OUTPUT: Hello, my name is john and I live in somewhere, IL
A rewrite of your code:
1) Stop using MySQL_ fuctions, they are deprecated, insecure and should not be used. There are two alternatives; mysqli_ functions (Object orientated or Procedural) or PDO functionality (object orientated only)
2) Your question appears uclear, is your <h4> tag within <?php tags or is it just HTML? To output PHP you need to wrap the print/echo article in <?php tags to tell the server how to process this section of the code.
Likewise, you need to be sure the page is pocessed as a PHP page rather than just as an HTML page. So does the page name end with .php (such as page.php)?
3) For clarity: while ($row = mysql_fetch_row($result)) will only ever output one row at a time, each MySQL row with hold numerous columns.
4) It's very useful for you to indent your brackets correctly, typing four spaces (not tab) for each bracket contents, as exampled a litte bit below.
5) Your While loops are confused; you have too any brackets. Your value $c_row will only ever be the final value found in the row, but the row will only ever have one unqiue value in it -- that of the category column, because that's what's specified in the SQL query.
Rewrite:
/***
* Fill with your own values, Address is usually 'Localhost'
***/
// connction details:
$conn = mysqli_connect(Address, User, Password, Database);
// A numeric column (id) does not need values to be quoted.
$query = "SELECT category FROM html where id = 1 ";
// note the mysqli_ and use of new $conn variable setout above
$result = mysqli_query($conn, $query);
/***
* Typical output from the above for returning two rows from
* the DB would be:
* $result[0]['category'] = "whatever_value"
* $result[0][0] = "whatever_value"
* $result[1]['category'] = "whatever_value_row2"
* $result[1][0] = "whatever_value_row2"
***/
// This will fetch all the rows, one row at a time,
// with array keys being the SQL column names
// (ignores numeric array keys).
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
{
// use definite named array key selectors to not need counters.
$category = $row['category'];
echo $category;
}
That would give you an output:
whatever_value
whatever_value_row2
To make your <h4> work as expected you can try replacing your echo with:
print "<h4>Categories ( ". $category; ." ) </h4>";

Split query into multiple arrays based on column name

I want to run a query that gets all the data from a database then have the data split into arrays for each column. With this I intend to dynamically populate html. I am not very experienced with php and could use some assistance with how to put my query into multiple arrays depending on what column it was in.
Example: For the column name I want an array $itemName[] and it will contain every item name in asc order. Then for the image column I want an array $itemImage[] for every image/image url in the same order.
With this I plan to run a for loop where as x increases it will go through each diff array and pull from the specified location. There are no null values in my DB so I don't need to worry about that.
Any help you can give me with the writing the query into multiple arrays based on the column name is appreciated.
$mPos = array(mPos1, mPos2, mPos3, mPos4);
for (x=0; x<4; x++){
echo "<div class="$mPos[x]"> <div class="$mPos[x] . '_1'">"$title[x]"</div><div class="$mPos1 . '_2'">"$image[x]"</div>
Still doesn't make sense for me to separate it that way, but here you go.
Since you didn't provide a database/table structure, I will assume your db table got the following columns:
itemId | itemName | itemImage | itemDescription
In PHP you loop through the result row for row and populate your arrays like
foreach ( $result AS $row ) {
$itemNames[$row->itemId] = $row->itemName;
$itemImages[$row->itemId] = $row->itemImage;
$itemDescriptions[$row->itemId] = $row->itemDescription;
}
EDIT: After question was updated and now includes the HTML output, I'd suggest something like this.
foreach ( $result AS $row ) {
$items[$row->itemId] = array(
'name' => $row->itemName,
'image' => $row->itemImage,
'description' => $row->itemDescription,
'price' => $row->itemPrice,
'link' => $row->itemLink,
);
}
$x = 0;
while ($x<4) {
$x++;
$item = array_shift($items);
echo '<div class="mPos'.$x.'">
<div class="mPos'.$x.'_1">"'.$item['name'].'"</div>
<div class="mPos'.$x.'_2">"'.$item['price'].'"</div>
<div class="mPos'.$x.'_3"><a href="'.$item['link'].'">
<img src="'.$item['image'].'" /></a>
</div>
</div>';
}
$sth = $dbh->prepare("SELECT itemName, itemImage FROM myTable");
$sth->execute();
$result = $sth->fetchAll();
$myArr = array();
foreach($result as $row){
foreach($row as $colName => $colVal){
$myArr[$colName][] => $colVal;
}
}
echo '<pre>';
print_r($myArr);
echo '</pre>';
Although I do have misgivings about how you're actually approaching this from a design perspective.

Categories