how to get diffrent data from single column in mysql and php - php

i want to store multiple data with comma separated in single column and get back data with the help of php in different different line
like in column view it will looks like this-- toothbrush-1234,glass-1234,
in up there 1234 is product id
i want to get this data in php with separated values each line with its all details.
like
<?php $sql="select product_name form products where product_id=1234" ?>
So is it possible to get data and separat it by - and , from single column.

You want to display your comma separated data into separate rows. You can try this.
<?
//Here is the complete example of your code by using MYSQLi Object Oriented:
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "select product_id,product_name form products where product_id=1234";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
$yourData = array();
while($row = $result->fetch_assoc()) {
$yourData[$row['product_id']] = explode(",",$row['product_name']);
}
if(count($yourData) > 0){
foreach ($yourData as $key => $value) {
foreach ($value as $productname) {
echo "Product ID >> ".$key. " -- Product Name >> ".$productname;
}
}
}
}
else
{
echo "0 results";
}
$conn->close();
?>
Side Note: If you are using mysql_* in your application than i suggest you to use mysqli_* or PDO because mysql_* is deprecated and not available in PHP 7.

Related

Some table values returning null?

I have a database that stores a website's news articles. Each row contains a time, title, author, and a content field. Javascript handles the information passed from php and displays it via togglable buttons. For some reason even though I see the data in Mysql Workbench some content fields are returning null. Why would this be?
Here is my code..
var json = <?php
$servername = "sfxworks.net"; //Currently pulls from my webserver. Pass sql credentials or write a php file that I can include that wont show on github.
$username = "foo";
$password = "bar";
$dbname = "foodbarmmmmmmmmm";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$rows = array();
$sql = "SELECT title, author, date, content FROM News";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$rows[] = $row;
}
} else {
echo "0 results";
}
$conn->close();
print json_encode($rows);
?>;
For some reason, after php processes this with error reporting on, I just get null values at random. In the same places, but random.
There are some values in the table with interesting apostrophes..
After removing [ ’ ] from the string and replacing it with [ ' ] the value is no longer null.

PhP MySQL get ceratin items from database and echo them

I need some help and I can't figure it out,i tried searching the internet but I found nothing
So I'm using this code from w3schools
<?php
$servername = "localhost"; //Obviously this are set to my parameters
$username = "username"; //Obviously this are set to my parameters
$password = "password"; //Obviously this are set to my parameters
$dbname = "myDB"; //Obviously this are set to my parameters
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM People";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
//Some code goes here
}
} else {
echo "0 results";
}
$conn->close();
?>
How can I modify this code to echo certain items only?
EXAMPLE
I have 10 items in talbe People (Table people contains id,age,name,gender)
I want to echo out 3 out of 10 People by using their ID which are 1 trough 10
I know i can use this AND id IN(1, 5, 9)"; This just echoes them out 1 after another
Is there a way to echo out id 1 goes here , id 5 goes here and than id 9 goes there like in 3 different places with 3 different codes or something? is this even possible?
You could use:
class people
{
public function people()
{
$sql = $this->conn->prepare("SELECT * FROM `people`");
$sql->execute();
$result = $sql->fetch(PDO::FETCH_OBJ);
return $result;
}
}
then when you want certain information you could simply use in say index.php:
$fetch = new people();
$info = $fetch->people();
you can then run simple echo's such as $info->name or $info->id etc etc..
Depending on how you're searching for the user you could just add
WHERE `userid` = :id
$sql->bindParam(':id', $userid);
and add $userid into the people($userid)
But this will vary depending on how you're pulling out specific users.
use this code
<?php
//using PDO
try
{
$conn = new PDO('mysql:dbhost=myhost;dbname=mydbname;', 'user','pass');
}
catch (PDOException $e)
{
echo $e->getMessage();
}
$getId = $conn->query("
SELECT * FROM users
WHERE id = 1
AND id = 5
AND id = 9
");
while ($ids = $getId->fetch(PDO::FETCH_OBJ)
{
echo $getId->id . '<br>';
}

How to make custom function that returns all applicable rows in PHP

Below is my custom function that will take care the queries I call:
<?php
function cusQuery($sql){
$servername = "localhost";
$username = "root";
$password = "366y~V3g4n";
$dbname = "learnTurkishDesktop";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$result = $conn->query($sql);
$output = array();
if($result->num_rows>0){
while ($row = $result->fetch_assoc()){
//as you see I tried to output all rows using print_r and it worked but I want it to just return an array containing all applicable rows and the call should handle the rest(formatting and which columns to include).
print_r($output[] = $row);
}
}else{
return array("0 results");
}
mysqli_close($conn);
}
?>
Now I am calling the my cusQuery function at my index.php
<?php
include('myFunctions.php');
$myQuery = cusQuery("SELECT Title, Content FROM user_created_notebooks");
echo "<h4>". $myQuery['Title']." ".$myQuery['Content']."</h4>";
?>
I tried using for loop in my function call but it didn't work. Below is the reference of what I'm trying to do:
http://www.dreamincode.net/forums/topic/126144-shortest-way-to-write-a-mysql-fetch-query/
I also tried not using while loop in the function itself just like the example given in the link but it only outputs the first applicable row.
I would love to hear new ideas too.
Thanks in advance.
The reference given works perfectly because only one row was returned from the database. "SELECT name FROM table WHERE ID = '$var'";
For your case the "$output[] = $row" statement creates a multidimentional array
of associative arrays contained with in a numeric array so the method does not work. below is how you should loop over the results
if(!empty($output)){
foreach($output as $row){
echo "h4 {$row['Title']} {$row['content']}";
}
}

How to write php returns json format according to the key?

I use XAMPP to create local networks and write php file to return the data in the database as json. This is my code:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "landslide";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
function myexample {
$mysqli = "SELECT id, temp, acc, moisture, battery, time FROM devices";
$result = $conn->query($mysqli);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_array($result)){
$response["main"] =array();
$response["parameters"]= array();
$main = array();
$main["id"]=$row["id"];
array_push($response["main"],$main);
$parameter = array();
$parameter["temp"] = $row["temp"];
$parameter["acc"] = $row["acc"];
$parameter["moisture"] = $row["moisture"];
$parameter["battery"] = $row["battery"];
$parameter["time"] = $row["time"];
array_push($response["parameters"],$parameter);
}
// echoing JSON response
$result_response = echo json_encode($response);
return $result_response;
}
} // end of my example function
?>
now when you call this function you will get json_encode format
now parse it by using
$res = JSON.parse($result_response);
now
$moisture = $res['moisture'];
My local link: http://127.0.0.1/landslide/currentdata.php .
Now, I want to write one php file returns json format according to the "key"(here i want key is id). As of Openweather api address below, key is cities (example London). http://api.openweathermap.org/data/2.5/weather?q=London,uk
So, how to i return json format by php according to key? Please help me! (My expression was not good, sorry about that)
when you are returning the json_encode($response);
You need to parse it to get in like an object and access it you can achieive it like in one variable.
$result = JSON.parse($response);
and access this $result array like if you want to access moisture
then $moisture = $result['moisture']; like so on...

Value returned from mysqli db call in php doesn't return values with newline chara

Ok so for some reason when I try and get values from a cell in my table with type TEXT it returns nothing, even thought there is text in the cell. It might be because there are new line characters in the text. In fact I'm certain that's the reason cause the only time things aren't return from the table is when there are newlines in it.
Here is the code where I get the data from my db:
function getRecord($cmo_name,$username,$password){
$i = 0;
$servername = "localhost";
$db = "my_db";
$return_array[] = "";
$conn = new mysqli($servername, $username, $password, $db);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM `my_table` WHERE `Name` = '".$name."'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()){
foreach($row as $value)
array_push($return_array, $value);}
}
$conn->close();
return $return_array;
}
The above code returns nothing for the TEXT column that includes the newlines.
Help please!!!
Wrap your query result in PHP's TRIM function to strip the newline and returns out:
http://php.net/manual/en/function.trim.php

Categories