Adding parameters to an already working webservice - php

I have the following already working great, but would like to add a parameter as this returns the whole data set.
<?php
$mysql_db_hostname = "localhost";
$mysql_db_user = "00000";
$mysql_db_password = "00000";
$mysql_db_database = "000000";
$con = #mysqli_connect($mysql_db_hostname, $mysql_db_user, $mysql_db_password,
$mysql_db_database);
if (!$con) {
trigger_error('Could not connect to MySQL: ' . mysqli_connect_error());
}
$var = array();
$sql = "SELECT * FROM mns";
$result = mysqli_query($con, $sql);
while($obj = mysqli_fetch_object($result)) {
$var[] = $obj;
}
echo '{"mns":'.json_encode($var).'}';
?>
For clarification, I was hoping to add a parameter in the url that is passed through to the php so that I get specific records. For example, if there is a field called [Customer], I would like to pass a customer id to it.

Related

JSON from mysql not display properly through PHP

This is my database of mysql on the web
This is my database on the web
This is the PHP file to access the database to get a JSON file, first I select all the "category" cell in the table, then loop through the category, and then loop through the other columns of a category, and assign to an array of $data2, after that assign $data2 and category to br an array of $data, which is the json I want to display.
<?php
header("Access-Control-Allow-Origin: *");
$user = "u348833238_rest"; /* User */
$password = "a!23286029"; /* Password */
$dbname = "u348833238_rest"; /* Database name */
$host = "localhost";
$con = mysqli_connect($host, $user, $password, $dbname);
// Check connection
if (!$con) {
die("Connection failed: " . mysqli_connect_error());
}
// $sel = mysqli_query($con,"select * from restaurant");
// $data = array();
// while ($row = mysqli_fetch_array($sel)) {
// $data[] = array("dishes" => ["name"=>$row['food'], "price"=>$row['price']] , "category"=>$row['category']);
// }
// echo json_encode($data);
$sel = mysqli_query($con,"select distinct category from restaurant");
$data = array();
while ($row = mysqli_fetch_array($sel)) {
$c = $row['category'];
$sel2 = mysqli_query($con,"select * from restaurant where category = $c ");
$data2 = array();
while ($row2 = mysqli_fetch_array($sel2)){
$data2[] = array("name"=>$row2['food'], "price"=>$row2['price']);
}
// echo $data2;
$data[] = array("category"=>$row['category'], "dishes"=>$data2);
}
// echo $data;
echo json_encode($data);
?>
How the JSON is not displayed properly as the array of property "dishes" is empty as below:
the array is empty
I’d recommend turning errors on so you can see where the problem is.
At a guess it’s here:
select * from restaurant where category = $c
Should be:
select * from restaurant where category = '$c'

How to pull data with a link on a different page with mysqli

I figured out the way to link to the page and set what ID i would like to call:
CLICK TEST **(IS THIS RIGHT?)**
But then I need page.php to pull the id, this is what I am using at the moment to pull the id manually. How would I make the following code pull it form the link?
<?php
$query = "select * from Drinklist where id = 10";
$result = mysqli_query($conn,$query);
while($Drinklist = mysqli_fetch_array($result)){
echo "<head>";
echo "<title>".$List['name']." - Site Name</title>";
}
?>
I tried the following (didn't work):
$query = "select * from List where id = . $id";
Seems like I can only find the way to do it with MYSQL and not MYSQLI... Any help would be appreciated.
UPDATED CODE:
<?php
$query = "select * from Drinklist where id = ?";
$result = mysqli_prepare($conn,$query);
mysqli_stmt_bind_param($result, 'i', $_GET['id']);
mysqli_stmt_execute($result);
while($Drinklist = mysqli_fetch_array($result)){
echo "<head>";
echo "<title>".$Drinklist['name']." - Mixed Drinks Station</title>";
}
?>
Getting error:
Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result,
object given in public_html/page.com/test/inc/drink-page.php on line 6
Ok so I ended up figuring this one out with a ton of trial and error...
Thank you chris85 for the early support and hopefully this can help you out a little. This is fun ;)
<?php
$server = "localhost";
$user = "user";
$pass = "password";
$dbname = "database";
//Creating connection for mysqli
$conn = new mysqli($server, $user, $pass, $dbname);
//Checking connection
if($conn->connect_error){
die("Connection failed:" . $conn->connect_error);
}
$article_id = $_GET['id'];
if( ! is_numeric($article_id) )
die("Looks like you are lost! <a href='#'>Back to Home</a> ");
$query = "SELECT * FROM `Whatever` WHERE `ID` =$article_id LIMIT 0 , 30";
$info = mysqli_query($conn,$query);
while($row = mysqli_fetch_array($info, MYSQL_ASSOC))
{
$name = $Whatever['name'];
$description = $Whatever['description'];
$keywords = $Whatever['keywords'];
$lrgpic = $Whatever['lrgpic'];
$vid = $Whatever['vid'];
$name = htmlspecialchars($row['name'],ENT_QUOTES);
$description = htmlspecialchars($row['description'],ENT_QUOTES);
$keywords = htmlspecialchars($row['keywords'],ENT_QUOTES);
$lrgpic = htmlspecialchars($row['lrgpic'],ENT_QUOTES);
$vid = $row['vid']; //Use <-- to be able to have HTML in your database otherwise the above would remove <, >, /, ', ", ect.
echo "<head>";
echo "<title>$name - Site title</title>";
echo "<meta name='description' content='$description'>";
echo "<meta name='keywords' content='$keywords'>";
include 'inc/head.php'; //includes already are in a php file ;)
echo "</head>";
echo "<body>";
include 'inc/header.php';
include 'inc/nav.php';
echo "<div class='wrapper'>";
echo "<div id='drink-name'>";
echo "<h2>$name</h2>";
echo "</div>";
// AND SO ON
}
?>

Simplify php code - connect to a database

Here I have a php code that connects to a database, selects a row by id and creates an associative array from this row using a while loop. Do I have to write this code over and over again to create arrays from other rows by id? Maybe there is a chance to simplify this php code somehow? Please look at my code. BTW I am new in php...
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$db = '_erica';
$conn = new mysqli($dbhost, $dbuser, $dbpass,$db);
$sql1 = "SELECT * FROM pics WHERE id = 1;";
$sql2 = "SELECT * FROM pics WHERE id = 2;";
$sql3 = "SELECT * FROM pics WHERE id = 3;";
$sql4 = "SELECT * FROM pics WHERE id = 4;";
$sql5 = "SELECT * FROM pics WHERE id = 5;";
$sql6 = "SELECT * FROM pics WHERE id = 6;";
$result1 = $conn->query($sql1);
$result2 = $conn->query($sql2);
$result3 = $conn->query($sql3);
$result4 = $conn->query($sql4);
$result5 = $conn->query($sql5);
$result6 = $conn->query($sql6);
while($row1 = $result1->fetch_assoc()) {
$bcgrnd = $row1["link"];
}
while($row2 = $result2->fetch_assoc()) {
$recipes = $row2["link"];
}
while($row3 = $result3->fetch_assoc()) {
$header = $row3["link"];
}
while($row4 = $result4->fetch_assoc()) {
$menu = $row4["link"];
}
while($row5 = $result5->fetch_assoc()) {
$beauty = $row5["link"];
}
while($row6 = $result6->fetch_assoc()) {
$kids = $row6["link"];
}
?>
You can do this in one query:
$sql = "SELECT * FROM pics WHERE id IN (1,2,3,4,5,6);";
$result = $conn->query($sql);
And then you can loop over all results like this:
$data = array();
while ($row = $result->fetch_assoc()) {
$id = $row["id"];
$link = $row["link"];
$data[$id]["link"] = $link;
// add more fields if you want
}
To access for example the link of ID 1, just do:
$data[1]["link"];
You can write one or two simple functions for this. Moreover, please note that your code is vulnerable to SQL Injection. Here is an example how you can achieve this with some simple functions:
<?php
function DB() {
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$db = '_erica';
return new mysqli($dbhost, $dbuser, $dbpass,$db);
}
function query($id) {
$query = "SELECT * FROM `pics` WHERE `id` = $id";
return DB()->query($query);
}
$result = query(1); // will fetch records for ID 1
while($row = $result->fetch_assoc()) {
$bcgrnd = $row["link"];
}
$result = query(2); // will fetch records for ID 2
while($row = $result->fetch_assoc()) {
$bcgrnd = $row["link"];
}
?>
By adapting this approach, you can fetch data for a specific ID. If you don't like this solution, consider using MySQL IN clause.
Try this.
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$db = '_erica';
$conn = new mysqli($dbhost, $dbuser, $dbpass,$db);
$sql = "SELECT * FROM pics WHERE id IN (1,2,3,4,5,6);";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
$bcgrnd[$row["id"]][] = $row["link"];
}
?>
Why not try a Query and Limit it to 6 results, it takes up less resources just pulling 6 results:
SELECT * FROM `pics` ORDER BY `[PRIMARY KEY]` LIMIT 6
MySQL in() function finds a match in the given arguments, you can use it
select pics where id IN(1,2,3,4,5,6)

trying to do SELECT in php but i get

So I got a nifty little bit of code set to run along and find me information when I give it a certain KittenID but its not working at all, I am sad. And oh so tired, Can anyone tell me where I have gone wrong? and yes I do have:
<?php
date_default_timezone_set('America/New_York');
//If statements:
//find:
date_default_timezone_set('America/New_York');
if(isset($_POST['Find']))
{
$connection = mysql_connect("ocelot.aul.fiu.edu","userName","password");
// Check connection
if (!$connection)
{
echo "Connection failed: " . mysql_connect_error();
}
else
{
//select a database
$dbName="spr15_xgotz001";
$db_selected = mysql_select_db($dbName, $connection);
//confirm connection to database
if (!$db_selected)
{
die ('Can\'t use $dbName : ' . mysql_error());
}
else
{
$result = mysql_query($connection,"SELECT * FROM Kittenz WHERE KittenID =<?php$_POST[KittenID]?>;)
while($row = mysql_fetch_array($result))
{
$Name = $row['Name'];
$KittenID = $row['KittenID'];
$KittenAge = $row['KittenAge'];
$Email = $row['Email'];
$Comments = $row['Comments'];
$Gender = $row['Gender'];
$Personality = $row['Personality'];
$Activity = $row['Activity'];
echo $row['Comments'];
}
}
}
mysql_close($connection);
}
?>
Use
$result = mysql_query($connection,"SELECT * FROM Kittenz WHERE KittenID = " .$_POST['KittenID']);
instead of
$result = mysql_query($connection,"SELECT * FROM Kittenz WHERE KittenID =<?php$_POST[KittenID]?>;)
Note: Please use mysqli_ for your future projects
You need to privide more context. How are you setting the $_GET['id'].. is it in fact being stored as $_GET['KittenID'] (e.g. https://yoursite.com?view&KittenID=1). If so...
You can set a variable and declare the 'KittenID'
$kittenid = $_POST['KittenID'];
$result = mysql_query($connection,"SELECT * FROM Kittenz WHERE KittenID = $kittenid");
I suggest providing more context. What error are you getting? What do your parameters look like?
Use
$result = mysql_query($connection,"SELECT * FROM Kittenz WHERE KittenID = " .$_SERVER['KittenID']);
instead of
$result = mysql_query($connection,"SELECT * FROM Kittenz WHERE KittenID =<?php$_POST[KittenID]?>;)

PHP Functions and MySQL Connectivity

I have a database.php file which stores the database connection info like this:
<?php
// Database connectivity stuff
$host = "localhost"; // Hostname for the database. Usually localhost
$username = "root"; // Username used to connect to the database
$password = "root"; // Password for the username used to connect to the database
$database = "blog"; // The database used
// Connect to the database using mysqli_connect
$connection = mysqli_connect($host, $username, $password, $database);
// Check the connection for errors
if (mysqli_connect_errno($connection)) {
// Stop the whole page from loading if errors occur
die("<br />Could not connect to the database. Please check the settings and try again.") . mysqli_connect_error() . mysqli_connect_errno();
}
?>
And also a functions.php file that has the following:
<?php
// Functions file for the system
function show_posts($user_id) {
$posts = array();
$sql = "SELECT body, stamp from posts where user_id = '$user_id' order by stamp desc";
$result = mysqli_query($connection, $sql);
}
function show_users() {
$users = array();
$sql = "SELECT id, username FROM users WHERE status = 'active' ORDER BY username";
$result = mysqli_query($connection, $sql);
while ($data = mysqli_fetch_array($result)) {
$users[$data->id] = $data->username;
}
return $users;
}
function following($user_id) {
$users = array();
$sql = "SELECT DISTINCT user_id FROM following WHERE follower_id = $user_id";
$result = mysqli_query($connection, $sql);
while ($data = mysqli_fetch_assoc($result)) {
array_push($users, $data->user_id);
}
return $users;
}
?>
Both files are inside an /includes folder. I now have a users.php files in which I want to display a list of users. Here's my code that tries to do that:
<?php
$users = show_users();
foreach ($users as $key => $value) {
echo $key . " " . $value;
}
?>
The problem I have is this:
Notice: Undefined variable: connection in
/Applications/MAMP/htdocs/blog/includes/functions.php on line 13
Warning: mysqli_query() expects parameter 1 to be mysqli, null given
in /Applications/MAMP/htdocs/blog/includes/functions.php on line 13
Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result,
null given in /Applications/MAMP/htdocs/blog/includes/functions.php on
line 15
The users.php file has require('includes/functions.php') and require('includes/database.php'). But somehow the values are not passed?. What am I doing wrong? Please help me out. I hope this makes sense. The problem with the undefined variable occurs for each function of the 3.
Either pass the $connection variable to your functions or make it global.
E.g:
function show_posts($connection, $user_id) {
$posts = array();
$sql = "SELECT body, stamp from posts where user_id = '$user_id' order by stamp desc";
$result = mysqli_query($connection, $sql);
}
OR
function show_posts($user_id) {
global $connection;
$posts = array();
$sql = "SELECT body, stamp from posts where user_id = '$user_id' order by stamp desc";
$result = mysqli_query($connection, $sql);
}
Try $GLOBALS['connection'] instead of $connection in your function. See more here

Categories