How do I retrieve specific Column Data - php

I've been messing around with PHP once again. I am trying to retrieve information from a specific Column. So for example I'll do
http://127.0.0.1:8002/api/galaxy/rgalaxy.php?api&Name=Hi
The Column looks like this.
+----------------+-------+
| Name | Data |
+----------------+-------+
--> | Hi | Grab | <--
| Medium product | 9.99 |
| Large product | 15.99 |
+----------------+-------+
And It'll retrieve this info Grab
So since I put in Hi As the Parameter, It'll retrieve Grab
I have no idea how to do that. Would anyone mind helping?

$query = "SELECT column_name FROM table_name WHERE other_column = 'value'";
replace "column_name", "table_name", "other_column" and "value" by desired.
To get your 'Name' value from url use $_GET['Name']

Firstly, open a connection to your database
$connection = mysqli_connect('localhost', 'db_username', 'db_password, 'db_name');
Then, use this connection to perform your query
Edit : to avoid SQL injection
<?php
$name = '';
if(isset($_GET['Name'])){
$name = $_GET['Name'];
}
$connection = mysqli_connect('localhost', 'root', '', 'ett');
$query = 'SELECT name FROM items WHERE name like ?';
$stmt = $connection->prepare($query);
$stmt->bind_param('s', $name);
$stmt->execute();
$result = $stmt->get_result();
$names_array = array();
while ($row = $result->fetch_assoc()) {
$names_array[] = $row;
}

Insert this Mysql query if you want only Data value as Grab
$name=$_GET['Name'];
$sql = "SELECT Data FROM YOUR_TABLE_NAME WHERE Name='.$name.' ";
and if you want to fetch more data like
| Hi | Grab |
| Medium product | 9.99 |
| Large product | 15.99 |
all then you need to add one more column who's value is common to all row and pass those column value to your url .

Your MySQL query will look something like this:
"SELECT * FROM your_table_name WHERE Name=$_GET['Name']"
Then you need to run the above query, and fetch it into a PHP variable and do whatever you want with that. I hope this helps you.

Related

Updating a database column (vertically) with an array

I have a database table with the following structure. id column is added later. So all id cells are empty.
id | song | album | artist
-----------------------------
| song1 | alb1 | art1
| song2 | alb2 | art2
| song3 | alb3 | art3
| song4 | alb4 | art4
| song5 | alb5 | art5
I have an array which holds the id values for the table. I'll be updating the table (the id column) with the values in the array. For example:
$array = [
"C45Rm3fLGn",
"ocIik81up2",
"IcuSn9T77y",
"tJv7AbF53r",
"a9eZ6xYM5Y",
];
These items are unique random strings.
How should I proceed? I'm thinking about iterating the array and using UPDATE on each item.
$array = [
"C45Rm3fLGn",
"ocIik81up2",
"IcuSn9T77y",
"tJv7AbF53r",
"a9eZ6xYM5Y",
];
$rows = $mysqli->query("SELECT * FROM songs")->fetch_all(MYSQLI_ASSOC);
for ($i = 0; $i < count($array); $i++) {
$row = $rows[$i];
$id = $array[$i];
$mysqli->query("UPDATE songs SET id = '$id' WHERE song = '{$row["song"]}' AND artist = '{$row["artist"]}'");
}
Is there a more preferable way?
UPDATE: I do not use auto increment and the id column didn't exist at the time of table was created. Now, I've added an id column. There are 300+ records. IDs of the records are unique random strings. Before I add another record to the database, every record needs to have a unique random string for its id, so that when I insert a new record, I can create a random string and check if it's unique or not by comparing it to the ids in the table.
At this stage, I just need to update the id column using an array. Array items are irrelevant.
Prepared statements are designed to be prepared once and executed many times, with a minimum of overhead. Using them is also an absolute necessity if the data you're inserting is user-generated.
It's been a long time since I've done anything with MySQLi (I strongly recommend looking at PDO for much simpler code) but this should work:
$array = [
"C45Rm3fLGn",
"ocIik81up2",
"IcuSn9T77y",
"tJv7AbF53r",
"a9eZ6xYM5Y",
];
$rows = $mysqli->query("SELECT * FROM songs")->fetch_all(MYSQLI_ASSOC);
$stmt = $mysqli->prepare("UPDATE songs SET id=? WHERE song=? AND artist=?");
foreach ($array as $i=>$id) {
$row = $rows[$i];
$stmt->bind_param("sss", $id, $row["song"], $row["artist"]);
$stmt->execute();
}
I would also recommend building your array such that it references the columns you're renaming. You're relying on both the database and the array being in the same order, which may not always be the case.
Please try this query:
UPDATE `myTable` SET `id`= CONCAT(item-name, "-id");
Or you can set a counter like this:
UPDATE `myTable`, (SELECT #i := 0) c SET `id`= CONCAT(item-name, "-id-", #i:=#i+1)
I hope this will help you.

PHP : Check If Two Column-Values are Correct in SQL Table

I want to check an SQL table if two column values are both equal to specified values using PHP. My table looks like this:
my_db
------------------------------------------
code | user | email |
------------------------------------------
10314343 | 20 | example#example.com |
13423434 | 22 | example#example.com |
11342434 | 40 | example#example.com |
This is my PHP, although not working:
// Set variables
$tbl_name = mydb;
$matchCode = "10314343"
$matchUserID = "20"
// Query matchCode and MatchUSerID on db
$getName = "SELECT FROM $tbl_name WHERE user ='$matchUserID' ";
$queryName = mysql_query($getName);
// Query matchCode and MatchUSerID on db
$getCode = "SELECT FROM $tbl_name WHERE code ='$matchCode' ";
$queryCode = mysql_query($getCode);
// If these match
if($queryCode == 1 || $queryName == 1) {
echo "The User ID and Code Value Both Match";
}
I'm not sure whether this is the best way of doing things. I was thinking you might be able to get the entire row data by "user" ID, and then query that row for the "code" value. Although I'm unsure how to do that.
What I'm trying to achieve is an sql query that checks if my variable matches the data of "code" for in the row of $matchUserID.
You're not selecting anything, also if you want to check if both values are the same in 1 row, you should combine the queries:
$sql = "SELECT COUNT(*) FROM $tbl_name WHERE user ='$matchUserID' AND code = '$matchCode'";
$result = mysql_query($sql) or die(mysql_error());
$hasMatch = mysql_result($result, 0);
if ($hasMatch) {
...
}
Since you're only interested in knowing whether a row exists in the table, you can use COUNT(*) to only return the number of rows that were found.

PHP-MySQL: Returning Query as Array index name and value

I have a MySQL table like this:
------------
|animal|legs|
------------
| cat 4 |
| chicken 2 |
Is it possible to return an array in PHP with animals as its index name and legs as its values without fetching one by one as in mysqli_fetch_all ?
$result[cat]=4
$result[chicken]=2.
I tried
$q = mysqli_fetch_all($q);
$array=array_combine($q2[0], $q2[1]);
but it does not give me the output that I wanted.
Using safeMysql
$dic = $db->getIndCol("animal","SELECT * FROM animals");
Try:
$result = array();
while ($row = mysqli_fetch_all($q, MYSQLI_ASSOC)){
$result[$row['animal']] = $row['legs'];
}
Remember to use apostrophes around strings in array labels in this way, as 'cat' or 'chicken'.

Combing MySQL Rows With Same ID PHP

I have a table "orders" which saves all the orders made on a website. It saves the data in the following way:
ID | Session_id | image | item | extra | customer_name
Sample date
12 | sdgfafjhsf | image1.jpg | coffee | milk | roger
13 | sdgfafjhsf | image1.jpg | muffin | jam | roger
14 | fjgjgsdfjg | image3.jpg | coffee | none | John
Currently I have the PHP accessing the database and spitting out all of the listings one by one.
mysql_connect("localhost", "root", "") or die(mysql_error()) ;
mysql_select_db("store") or die(mysql_error()) ;
//Retrieves data from MySQL
$data = mysql_query("SELECT * FROM orders WHERE status ='ordered'") or die(mysql_error()); //Puts it into an array
while($info = mysql_fetch_array( $data ))
{
//Outputs the image and other data
Echo "$info[customer_name] <img src='cameras/$info[image]'/> : $info[item] with $info[extras] <br />";
}
I am ideally wanting the data to group by the session ID. So it prints out the name of the customer and the image once and then all of the items associated with it.
eg. Roger , coffee, milk, muffin, jam
Any ideas?
Thanks!
A simple way would be to order the SQL so that you get all entries from each session following each other, and just remember the last session id you fetched to tell if you should output the name and picture or not; here's some pseudo code to show what I mean;
$data =
mysql_query("SELECT * FROM orders WHERE status ='ordered' ORDER BY session_id")
or die(mysql_error());
$last_session_id = "**DUMMY**"; // Set a dummy value to not match the first row
while($info = mysql_fetch_array( $data ))
{
if($info['session_id'] != $last_session_id)
{
//Outputs the image and other data if a new session_id has been found
echo "$info[customer_name] <img src='cameras/$info[image]'/> : $info[item] with $info[extras] <br />";
$last_session_id = $info['session_id'];
} else {
// Same session_id as last row, skip name and picture
echo "$info[item] with $info[extras] <br />";
}
}
As a side note, the mysql_* database API is deprecated, you should look into using mysqli or pdo instead.
well try this..
SELECT Session_id,image,item,extra,customer_name FROM orders WHERE status='ordered' group by Session_id,image,item,extra,customer_name
Here you have to run two separate query. In first query you have to find all distinct customer name, better if you use customer id rather than customer name because id cannot be duplicate. Then after getting all customer who have ordered item, iterate them in loop and inside loop run another query to retrieve all orders of that customer by again customer id or by customer name.
In you while($info = mysql_fetch_array( $data ))-loop, where you print the output, you could add it to a standard array where the keys are the Session_ids.
Then you call echo $foo['sdgfafjhsf'] to get an array with db-entries which you can enumerate through print accordingly.

SELECT MAX(... not returning anything in PHP/MYSQL

This is the table structure-
Table: test
+------+---------+
| PAGE | CONTENT |
+------+---------+
| 1 | ABC |
+------+---------+
| 2 | DEF |
+------+---------+
| 3 | GHI |
+------+---------+
PAGE is a Primary with datatype INT(11). It does not auto-increment. CONTENT is of the datatype TEXT.
In PHP I do-
$result = mysql_query(SELECT MAX(PAGE) FROM test);
$row = mysql_fetch_array($result);
echo $row["PAGE"];
No output. At all. If I do something like echo "Value : ".$row["PAGE"]; all I see is Value :
The query SELECT * FROM test works just fine though. Am I wrong somewhere using the MAX() syntax?
I want it to return the maximum value of PAGE as of yet.
This should be the code.
$result = mysql_query("SELECT MAX(PAGE) AS max_page FROM test");
$row = mysql_fetch_array($result);
echo $row["max_page"];
Shouldn't you have quotes around that query in mysql_query? I have no idea what PHP will do with such a syntactically inadequate statement, I would have thought it would have given you an error.
In any case, an aggregate function may have a different column name than the column used for it (from memory, DB2 gives it a similar name to the function, like max_page_ or something). You may want to ensure it has the correct column name by forcing the name with something like:
$result = mysql_query("SELECT MAX(PAGE) AS MAXPAGE FROM TEST");
$row = mysql_fetch_array($result);
echo $row["MAXPAGE"];
Try below code
$result = mysqli_query($con,"SELECT max(page2_content_id) AS max_page from page2_content_data");
$row = mysqli_fetch_array($result);
echo $row["max_page"];
Where $con=new mysqli($server,$user,$password,$db_name); and page2_content_data is my table,and page2_content_id is the column name
$connect = mysqli_connect("localhost", "root", "", "carBid") or die("not connected");
//connection to database
$sql2 = "SELECT max(mybid) FROM `bid`";
//simle select statement with max function
$result_set2 = mysqli_query($connect,$sql2);
//query a result fetch
if ($result_set2) {
$rowB = mysqli_fetch_array($result_set2);
//feching a result in array format
echo $rowB['max(mybid)'];
//accessing array by name of column with max() function of mysql
} else {
echo 'No Current Bid';
}
mysqli_close($connect);
I used something like this in my code;
$maxscore_query = mysql_query("SELECT MAX(`score`) FROM `allscores` WHERE`level`='$levelcode'");
echo mysql_result($maxscore_query, 0);
The difference here is the use of WHERE for selecting a group.
And mysql_result($maxscore_query, 0); is easier to manage for me.

Categories