Good morning
I've been struggling to work arround this recently, as I'm fairly new to PHP & MySQL in general.
I have a database with a table "videos" in which I store useful informations about videos and I have a document called search.php who will display specific videos based on GET Request.
A Request looks like this:
http://example.ex/search.php?tag=EXAMPLE1
The logic would be to store the tag value like this:
if(!empty($_GET["tag"])){
// Get videos from tag only
$curTag = strval($_GET["tag"]);
displayByTag($curTag); //the function that parse the database
}
I have my connection ready:
$server = "localhost";
$username = "root";
$password = "";
$db = "mydatabase";
$conn = mysqli_connect($server, $username, $password, $db);
$query = "SELECT * FROM videos";
$response = array();
$result = mysqli_query($conn, $query);
while($row = mysqli_fetch_array($result)) {
$response[] = $row;
}
Technically as of right now, my table is stored inside $response[].
What I need to do is to parse the database and looks for the "tags" column, split its string value ("EXAMPLE1,EXAMPLE2,EXAMPLE3" in table) and then see if the GET value matches one of them.
That's when I need your help. I understand the logic, the steps, but can't "translate" it into PHP. Here's what I would do (human-language):
function displayByTag($tag) {
for each $video-item inside $array {
$tagsArray = explodes(",", $video-item[tags-column]); //That's how I split the tags stored inside the table
for i as integer = 0 to $tagsArray.length {
if $tagsArray(i) == $tag {
//THATS A MATCH
}
}
}
}
Is this the right way to do it ? And how can I translate that "human" language into PHP code ?
Thanks for the help.
After a little bit of testing and debugging I got my function working pretty easily. If anyone is interested:
function searchVideos($search) {
$currentSearchQueries = explode(" ", strtoupper($search)); //Split the searched tags in a array and make them to uppercase for easier comparaison.
//Establish a connection the MySql Database
$server = "localhost";
$username = "root";
$password = "";
$db = "mydatabase";
$conn = mysqli_connect($server, $username, $password, $db);
//Select all the entries from my 'videos' table
$query = "SELECT * FROM videos";
$response = array();
$result = mysqli_query($conn, $query);
while($row = mysqli_fetch_array($result)){
$response[] = $row; //Place them into a array
}
//Parse the array for matching entries
foreach ($response as &$video){ //Each entries goes through the process
foreach ($currentSearchQueries as $t) {
//We compare if one the tags searched matches for this particular entry
if((strtoupper($video[tags]) == $t) {
//THAT'S A MATCH
}
}
}
}
It was very fun to code, looking forward for new experiences !
Related
<?php
$q= $_REQUEST["q"];
$r = $_REQUEST["r"];
$s = $_SESSION['empid'];
$max = 0;
$dbhost = 'localhost:3306';
$dbuser = 'root';
$dbpass = '';
$dbname = 'employeesurvey';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
$sql1 = "SELECT QuestionID FROM question";
if(!mysqli_query($conn,$sql1)){
echo 'error2 php';
}
while($rw1 = mysqli_fetch_array($sql1)){
$Q = $rw1['QuestionID'] ;
if ($max<$Q){
$max = $Q;
}
}
$Q = $Q+1;
$sql = "INSERT INTO question VALUES (".$Q.",'".$r."',".$s.",CURRENT_DATE(),".$q.",0)";
if(!mysqli_query($conn,$sql)){
echo "Error";
}
?>
The db, table names are all correct. I'm using xmlHttpRequest.open() to pass the values to this page
the call statement is:
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "gethint1.php?q=" + cid + "&r=" + question, true);
Im not getting any errors, nor the values are being inserted
Replace this line:
if(!mysqli_query($conn,$sql1)){
with these
$resultSet = mysqli_query($conn,$sql1);
if(!$resultSet){
And now replace this line:
while($rw1 = mysqli_fetch_array($sql1)){
With this one
while($rw1 = mysqli_fetch_array($resultSet)){
Reason is that you haven't executed query and stored the result set while at fetching record from result set, you are using direct query variable which is logically wrong.
why are you making a simple thing this complicated by obtaining Question id from table just use autoincrement field in your mysql table or use insert_id
and the problem is mysqli_fetch_array() function works on mysqli_query() function's output i.e. a object you are providing a string to a function which expects an object
I am about to lose my mind.I dont have any php experince and I am struggling about php web service.
Here is my code;
<?php
private $username2 = "";
private $password2 = "";
private $DB_CONNECTION;
private $servername = "localhost";
private $username = "root";
private $password = "";
private $dbname = "dptest";
function __construct()
{
$this->DB_CONNECTION = mysqli_connect($this->servername, $this->username,
$this->password, $this->dbname);
}
function getUserType(){
$sql = "SELECT usertype FROM `login_test` WHERE username = '". $this->username2."'AND password = '".$this->password2."'";
$result = mysqli_query($this->DB_CONNECTION,$sql);
//$value = mysqli_fetch_array($result);
while(!is_null($value = mysqli_fetch_array($result))){
return $value['usertype'];
}
}
}
This is my function code.The other is my login code;
<?php
include_once 'Authentication.php';
use user\Authentication;
$auth = new Authentication();
$auth->prepare($_POST);
$userStatus = $auth->isUserValidToLogIn();
if ($userStatus) {
// user existed
// So log him to main page
$json['success'] = 1;
$json['message'] = 'access granted';
$json['usertype'] = $auth->getUserType();
echo json_encode($json);
} else {
$json['success'] = 0;
$json['message'] = 'error!';
echo json_encode($json);
}
I am trying to get the user's type but when try to get the data form phpmyadmin local database it only gives the first column's usertype.When I try to get 2nd,3rd,4th so on.. user's usertype it doesnt return anything and blank page shows up on postman app.
Also my database looks like this;
usertype username password
admin despro 1234
client test 1234
client despro2 1234
client despro3 1234
The reason you are only getting one column back is because you only request the one column. In order to get the columns you want you need to explicitly request them in your query or use '*' in order to get all columns back. So your query should look like this in order to get all columns from the data table:
$sql = "SELECT * FROM `login_test` WHERE username = '". $this->username2."'AND password = '".$this->password2."'";
In general, I highly recommend that you stop using MySQLi extension and start using PHP Data Objects (PDO). It makes it easy to use prepared statements. Which also makes your code safer.
Then your query could look something like this (this is NOT the complete code):
// connecting to db
$pdo = new PDO($dsn, $user, $pass, $opt);
$sql = 'SELECT *
FROM login_test
WHERE userName = :username
AND pass = :password;';
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':username', $username2, PDO::PARAM_STR);
$stmt->bindParam(':password', $password2, PDO::PARAM_STR);
$res = $stmt->execute();
if ($res) {
$response["userdata"] = array();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
$myData = array();
$myData["usertype"] = $row["usertype"];
$myData["username"] = $row["username"];
array_push($response["userdata"], $myData);
}
}
Note that the code above is for returning multiple rows of data. If you just want the one row then use something like this:
if ($res) {
$response["userdata"] = array();
$myData = array();
$myData["usertype"] = $row["usertype"];
$myData["username"] = $row["username"];
array_push($response["userdata"], $myData);
}
removing the 'while' statement.
You might want to take a look at this answer I gave, recently. It is a comprehensive example of using a webservice from an Android app.
How to insert all the SQL table data into an array in java [android studio]
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']}";
}
}
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...
How can I implement a DataSet in PHP like .NET?
I want this class to read data from database only once, then I should be able to use the data without connecting again to MySQL to run queries.
select * from user
When I run this query on the DataSet the data is fetched from memory.
How can I implement this mechanism in PHP?
You could push your data into an array like this:
$result = mysql_query( 'select * from user' );
$results = array();
while ( $row = mysql_fetch_array( $result ) ) {
array_push( $results, $row );
}
mysql_close();
Then you can do whatever operations you want on the array...
foreach( $results as $record ){
$foo = $record['col_name'];
//...
}
What you are describing is the DataSet / DataTable data container classes of .NET which can work in disconnected mode.
A DataReader is kind of a cursor and needs to have the connection open in order to move through the result set of the underlying query.
In PHP you could do this:
<?PHP
$user_name = "root";
$password = "";
$database = "addressbook";
$server = "127.0.0.1";
$db_handle = mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database, $db_handle);
if ($db_found) {
$SQL = "SELECT * FROM tb_address_book";
$result = mysql_query($SQL);
while ($db_field = mysql_fetch_assoc($result)) {
print $db_field['ID'] . "<BR>";
print $db_field['First_Name'] . "<BR>";
print $db_field['Surname'] . "<BR>";
print $db_field['Address'] . "<BR>";
}
mysql_close($db_handle);
}
else {
print "Database NOT Found ";
mysql_close($db_handle);
}
?>
I don't think php can provide what you're looking for as it's very much text code and HTML driven, so you don't get the fancy GUI objects like you do in .net. PEAR provides a lot of source code that will produce data grids, that you could possibly investigate, all stored in code like arrays etc. I'm relatively new to php, so maybe someone would disagree...