Trying to echo a specific variable from a specific row - php

So I am attempting to;
-send a HTTP request from another source to the php file, within that http request it will contain something like; http://mywebsite.com/postServer.php/type=cmd&game=5342252 and what is should be doing is taking the post "game" and comparing it with the table to find witch row contains 5342252 in the column "gid".
However its not working. Now if I remove $game = $_POST["game"] and just put 5342252 were $game is it will work just fine... So im very confused as to why it wont work with $_POST
<?php
$type = $_POST["type"];
$game = $_POST["game"];
if(type == "cmd") {
$con = new mysqli("localhost","***","***","***");
if(mysqli_connect_errno()){
echo(mysqli_connect_error());
}
$data = $con->query("SELECT * FROM onlineservers WHERE gid =".$game);
while($row = $data->fetch_array()){
echo json_encode(array('command' => $row[cmd]));
}
}
?>

Note: First you must understand how to pass the variables in the URL with parameters. You have been missing the basic knowledge of how to pass the variables as parameters in the URL.
Rules:
First Parameter to be given with ? mark alone with value
Second Parameter to be given with & symbol along with values.
You can add any number of parameter provide the first one has to be with the ? symbol otherwise the code will not work.
Example: http:// domain.com?first_param=1&second_param=2
Brief Explanations on URL Parameters.
http://domain.net/page.php?id=1254
Why is there a question mark after the page name?
The answer is that the characters after the question mark are an HTTP query string. An HTTP query string can contain both variables and their values. In the example above, the HTTP query string contains a variable named "id", with the value "1254".
Here is another example:
http://domain.net/page.php?name=Joe
Again, you have a variable ("name") with a value ("Joe").
How to get the variable with PHP?
Let's say you have a PHP page named people.php. Now you can call this page using the following URL:
people.php?name=Joe
With PHP, you will be able to get the value of the variable 'name' like this:
<?php
echo $_REQUEST['name']; // Result the Output as Joe
echo $_GET['name']; // Result the Output as Joe
?>
Let's try it in an example:
<html>
<head>
<title>Query string</title>
</head>
<body>
<?php
// The value of the variable name is found
echo "<h1>Hello " . $_GET["name"] . "</h1>";
// The value of the variable name is found
echo "<h1>Hello " . $_REQUEST["name"] . "</h1>";
?>
</body>
</html>
Several variables in the same URL:
You are not limited to pass only one variable in a URL. By separating the variables with &, multiple variables can be passed:
people.php?name=Joe&age=24
This URL contains two variables: name and age. In the same way as above, you can get the variables like this:
$_GET["name"]
$_GET["age"]
Let's add the extra variable to the example:
<html>
<head>
<title>Query string </title>
</head>
<body>
<?php
// The value of the variable name is found
echo "<h1>Hello " . $_GET["name"] . "</h1>";
// The value of the variable age is found
echo "<h1>You are " . $_GET["age"] . " years old </h1>";
?>
</body>
</html>
Solution for Your Code
1.) Your URL should be like this as i have stated below.
http://mywebsite.com/postServer.php/?type=cmd&game=5342252
Then alone you can retrieve the data from the URL separately
2.) In order to get the data from the URL you have to use $_GET OR $_REQUEST. But you have used $_POST which is totally a blunder
It should be
$type = $_REQUEST["type"];
$game = $_REQUEST["game"];
3.) If statement seems to a error in your code.
You have to replace it as this:
if($type == "cmd") {}
But you have done like this if(type == "cmd") {} whoch leads to fatal error.
4.) While selecting the statements you have to check for the count of the query executed since if the count is ZERO and you execute the while or foreach you may be facing error.
Hence the Entire code will look like as follows:
<?php
$type = $_REQUEST["type"];
$game = $_REQUEST["game"];
if($type == "cmd") {
$con = new mysqli("localhost","***","***","***");
if(mysqli_connect_errno()){
echo(mysqli_connect_error());
}
$data = $con->query("SELECT * FROM onlineservers WHERE gid =".$game);
$count = $data->num_rows;
if($count==0)
{
// perform the failure action
}
else
{
while($row = $data->fetch_array()){
echo json_encode(array('command' => $row[cmd]));
}
}
}
?>
After you have done all the checks that i have mentioned above you have to ensure the note below in order to check your code works or not.
Note: You first put echo to the Select Statement and then break the execution by putting the exit; and you copy the statement that is echoed and place it in SQL of the DB and then check whether any error occurs in insertion. If no error occurs remove the echo and delete the exit;

Change the $_POST["..."] for $_GET["..."].
Each variable that you pass in URL is obtained through the $_GET method.
Example: If you do http://some.com/anything.php?var=test if you do $_GET["var"] you will get "test".

Try this :
<?php
$type = $_GET["type"];
$game = $_GET["game"];
if($type == "cmd") {
$con = new mysqli("localhost","***","***","***");
if(mysqli_connect_errno()){
echo(mysqli_connect_error());
}
$data = $con->query("SELECT * FROM onlineservers WHERE gid =".$game);
while($row = $data->fetch_array()){
echo json_encode(array('command' => $row[cmd]));
}
}
?>
You are not Posting the data, but receiving the data and hence $_GET is required.
And also your url shoud be like this:
http://mywebsite.com/postServer.php?type=cmd&game=5342252

Related

Problem with php variable to using MySQL query

Two variables, one is $current_shop another is $shop (see below). Both are printed same value: "sps-app-test.com". But when I use them in the below SQL Update query, the $shop variable works fine by SQL condition, but when using the $current_shop variable, it does not work.
However, the store_url = 'sps-app-test.com'.
I have tried without success, and posted this problem in many other places.
$shopify = $_GET;
$current_shop = $shopify['shop'];
print_r($current_shop); // sps-app-test.com
$shop = "sps-app-test.com";
print_r($shop);
// form_title
if(!empty($_POST['form_title']) ){
$form_title = mysqli_real_escape_string($conn,
$_POST['form_title']);
if( isset($form_title) ){
$query_form_title = "UPDATE widget_cont SET
form_title='$form_title' WHERE store_url='$current_shop' ";
echo $_POST['form_title'];
}
if( !mysqli_query($conn, $query_form_title) ){
echo "ERROR: " . mysqli_error($conn);
}
}
More details in this image
MySQL row
Please try not to include image instead write the code and can you try this :
$current_shop = $_GET['shop']
since the error is from this one try to use $_GET without assign it to a variable

Get data from MYSQL using PHP returns no results

So I am using this tutorial: https://www.simplifiedcoding.net/android-mysql-tutorial-to-perform-basic-crud-operation/ to try and get data from my local MYSQL server (using Wamp64). I had the undefined index error at first, which I fixed using the isset() statement.
But now it just returns:
{"result":[]}
I have, however, a lot of data in the set column of that database.
Here is the code:
<?php
//Getting the requested klas
$klas = isset($_GET['klas']) ? $_GET['klas'] : '';
//Importing database
require_once('dbConnect.php');
//Creating SQL query with where clause to get a specific klas
$sql = "SELECT * FROM lessen WHERE klas='$klas'";
//Getting result
$r = mysqli_query($con,$sql);
//Pushing result to an array
$result = array();
while ($row = mysqli_fetch_array($r)) {
array_push($result,array(
"id"=>$row['id'],
"klas"=>$row['klas'],
"dag"=>$row['dag'],
"lesuur"=>$row['lesuur'],
"les"=>$row['les'],
"lokaal"=>$row['lokaal']
));
}
//Displaying the array in JSON format
echo json_encode(array('result'=>$result));
mysqli_close($con);
?>
I tried out the
SELECT * FROM lessen WHERE klas='$klas'
statement in my database and it seems to return the correct data.
Any idea what is causing this?
Thanks in advance!
Point 1 is:
isset function only checks if klas is set in the $_GET global array. So if somehow $klas is blank - your query will return empty (without giving error).
So please check values in the $_GET and possibly from where it is accessed. Or you can add condition to avoid empty query like --
if (!empty($_GET['klas'])) {
// rest of the code block upto return
Point 2 is:
You have mentioned if you echo the sql it returns
SELECT * FROM lessen WHERE klas=''{"result":[]}
Here the second part (the JSON) is from echoing the result at the end of your code. So for the first part (i.e. echoing $sql) we see that klas=''. That actually goes to the Point 1 as mentioned above.
So finally you have to check why the value at $_GET is showing blank. That will solve your problem.
UPDATE:
From #GeeSplit's comment For the request
"GET /JSON-parsing/getKlas.php?=3ECA"
There will be nothing in $_GET['klas'] cause the querystring in the url doesn't contain any key.
So either you have to change the source from where the file is called. Or you can change how you are getting the value of klas.
Example:
$tmpKlas = $_SERVER['QUERY_STRING'];
$klas = ltrim($tmpKlas, '=');
Rest of your code will work.
Use this code
<?php
$klas ='';
if(isset($_GET['klas']) && !empty($_GET['klas']))
{
$klas = $_GET['klas'];
require_once('dbConnect.php');
$sql = 'SELECT * FROM lessen WHERE klas="'.$klas.'"';
$r = mysqli_query($con,$sql);
$result = array();
while ($row = mysqli_fetch_array($r)) {
array_push($result,array(
"id"=>$row['id'],
"klas"=>$row['klas'],
"dag"=>$row['dag'],
"lesuur"=>$row['lesuur'],
"les"=>$row['les'],
"lokaal"=>$row['lokaal']
));
}
echo json_encode(array('result'=>$result));
mysqli_close($con);
}
?>

VAR data not pushing to SQL

I'm having a slight issue and I'm not sure why. Maybe someone can help me out. First a few disclaimers; I'm still learning PHP, I'm aware of mysqli or pdo but the server this will live on is running an old ver 4 of php.
Ok now on to the problem.
I have a form which passes to my post-data.php form to push to SQL db.
However when it pushes the data it's only pushing the variables not the data within the vars from post action of the form.
Screenshot of submitted data in PHPmyadmin
My Code follows:
<?php
$hostname = "localhost"; $username = "goldme_owner";
$dbName = "goldme_dealer_meeting";
$connect = mysql_connect($hostname, $username);
if (!$connect) {
echo "Please try later.";
}
else {
mysql_select_db($dbName, $connect);
$checkboxA1 = isset($_POST['checkboxA1']) ? $_POST['checkboxA1'] : 'No';
$checkboxE1 = isset($_POST['checkboxE1']) ? $_POST['checkboxE1'] : 'No';
$checkboxF1 = isset($_POST['checkboxF1']) ? $_POST['checkboxF1'] : 'No';
$checkboxG1 = isset($_POST['checkboxG1']) ? $_POST['checkboxG1'] : 'No';
$checkboxH1 = isset($_POST['checkboxH1']) ? $_POST['checkboxH1'] : 'No';
$checkboxI1 = isset($_POST['checkboxI1']) ? $_POST['checkboxI1'] : 'No';
$checkboxJ1 = isset($_POST['checkboxJ1']) ? $_POST['checkboxJ1'] : 'No';
$checkboxK1 = isset($_POST['checkboxK1']) ? $_POST['checkboxK1'] : 'No';
}
echo "$checkboxA1"; //just want to make sure checkbox vars are passing //will delete in final code
echo "$checkboxE1"; //just want to make sure checkbox vars are passing //will delete in final code
echo "$checkboxF1"; //just want to make sure checkbox vars are passing //will delete in final code
echo "$checkboxG1"; //just want to make sure checkbox vars are passing //will delete in final code
echo "$checkboxH1"; //just want to make sure checkbox vars are passing //will delete in final code
echo "$checkboxI1"; //just want to make sure checkbox vars are passing //will delete in final code
echo "$checkboxJ1"; //just want to make sure checkbox vars are passing //will delete in final code
echo "$checkboxK1"; //just want to make sure checkbox vars are passing //will delete in final code
echo "$_POST[confirm]"; //just want to make sure confirm code generated //will delete in final code
$sql_statement = 'INSERT INTO 2014_registrations'.
'(confirm_number,timecode,company_name,country,address1,address2,city'.
',state,zip,phone,fax,email,zone_manager,transport,first_name,'.
'last_name,tuesday_tours,tuesday_meat,wed_lunch,wed_dinner,'.
'wed_pool_tourney,thurs_lunch,thurs_dinner,fri_shop,fri_tour,dietary)'.
'VALUES ("$_POST[confirm]","$_POST[timecode]","$_POST[company_name]",'.
'"$_POST[address]","$_POST[address2]","$_POST[city]","$_POST[state]",'.
'"$_POST[zip]","$_POST[country]","$_POST[phone]","$_POST[fax]",'.
'"$_POST[email]","$_POST[zonemanager]","$_POST[transport]",'.
'"$_POST[fattendee1]","$_POST[lattendee1]","$_POST[checkboxA1]",'.
'"$_POST[radio1]","$_POST[checkboxE1]","$_POST[checkboxF1]",'.
'"$_POST[checkboxG1]","$_POST[checkboxH1]","$_POST[checkboxI1]",'.
'"$_POST[checkboxJ1]","$_POST[checkboxK1]","$_POST[dietary1]")';
$rec_insert = mysql_query($sql_statement);
if(! $rec_insert ){
die('Could not enter data: ' . mysql_error());
}
echo "Entered data successfully\n";
mysql_close($connect);
?>
Inside single quotes the variables are not read as variables. For example echo '$a' will print $a but echo "$a" will print the value of $a.
In your code you are trying to use something similar to '$a', or in other words you are using single quotes around variables instead of double quotes.
Try writing it as
"VALUES ('$_POST[confirm]','$_POST[timecode]','$_POST[company_name]',".
or
'VALUES ("'.$_POST[confirm].'","'.$_POST[timecode].'","'.$_POST[company_name].'",'.
and so on..
Note that the use of $_POST[confirm] gives an notice. The correct way to use it is $_POST['confirm'].
Also note that your code is vulnerable to SQL injections. Consider using prepared statements.
The variables are being read as strings because they're written in single quotes.
I've moved the variables to outside of the single quotes and just concatenated them to the string. This code is extremely susceptible to SQL injection and should not be used in a production environment.
$sql_statement = 'INSERT INTO 2014_registrations'.
'(confirm_number,timecode,company_name,country,address1,address2,city'.
',state,zip,phone,fax,email,zone_manager,transport,first_name,'.
'last_name,tuesday_tours,tuesday_meat,wed_lunch,wed_dinner,'.
'wed_pool_tourney,thurs_lunch,thurs_dinner,fri_shop,fri_tour,dietary)'.
'VALUES ("'.$_POST[confirm].'","'.$_POST[timecode].'","'.$_POST[company_name].'",'.
'"'.$_POST[address].'","'.$_POST[address2].'","'.$_POST[city].'","'.$_POST[state].'",'.
'"'.$_POST[zip].'","'.$_POST[country].'","'.$_POST[phone].'","'.$_POST[fax].'",'.
'"'.$_POST[email].'","'.$_POST[zonemanager].'","'.$_POST[transport].'",'.
'"'.$_POST[fattendee1].'","'.$_POST[lattendee1].'","'.$_POST[checkboxA1].'",'.
'"'.$_POST[radio1].'","'.$_POST[checkboxE1].'","'.$_POST[checkboxF1].'",'.
'"'.$_POST[checkboxG1].'","'.$_POST[checkboxH1].'","'.$_POST[checkboxI1].'",'.
'"'.$_POST[checkboxJ1].'","'.$_POST[checkboxK1].'","'.$_POST[dietary1].'")';
First of all, inserting data directly into the db from POST request is almost never a good idea.
I know this is really badly formatted, but try using this $sql_statement instead:
$sql_statement = 'INSERT INTO 2014_registrations'.
'(confirm_number,timecode,company_name,country,address1,address2,city'.
',state,zip,phone,fax,email,zone_manager,transport,first_name,'.
'last_name,tuesday_tours,tuesday_meat,wed_lunch,wed_dinner,'.
'wed_pool_tourney,thurs_lunch,thurs_dinner,fri_shop,fri_tour,dietary)'.
"VALUES (\"{$_POST[confirm]}\",\"{$_POST[timecode]}\",\"{$_POST[company_name]}\",".
"\"{$_POST[address]}\",\"{$_POST[address2]}\",\"{$_POST[city]}\",\"{$_POST[state]}\",".
"\"{$_POST[zip]}\",\"{$_POST[country]}\",\"{$_POST[phone]}\",\"{$_POST[fax]}\",".
"\"{$_POST[email]}\",\"{$_POST[zonemanager]}\",\"{$_POST[transport]}\",".
"\"{$_POST[fattendee1]}\",\"{$_POST[lattendee1]}\",\"{$_POST[checkboxA1]}\",".
"\"{$_POST[radio1]}\",\"{$_POST[checkboxE1]}\",\"{$_POST[checkboxF1]}\",".
"\"{$_POST[checkboxG1]}\",\"{$_POST[checkboxH1]}\",\"{$_POST[checkboxI1]}\",".
"\"{$_POST[checkboxJ1]}\",\"{$_POST[checkboxK1]}\",\"{$_POST[dietary1]}\")";
Your `sql_statment is wrong.
$sql_statement = 'INSERT INTO 2014_registrations'.
'(confirm_number,timecode,company_name,country,address1,address2,city'.
',state,zip,phone,fax,email,zone_manager,transport,first_name,'.
'last_name,tuesday_tours,tuesday_meat,wed_lunch,wed_dinner,'.
'wed_pool_tourney,thurs_lunch,thurs_dinner,fri_shop,fri_tour,dietary)'.
'VALUES ("$_POST[confirm]","$_POST[timecode]","$_POST[company_name]",'.
'"$_POST[address]","$_POST[address2]","$_POST[city]","$_POST[state]",'.
'"$_POST[zip]","$_POST[country]","$_POST[phone]","$_POST[fax]",'.
'"$_POST[email]","$_POST[zonemanager]","$_POST[transport]",'.
'"$_POST[fattendee1]","$_POST[lattendee1]","$_POST[checkboxA1]",'.
'"$_POST[radio1]","$_POST[checkboxE1]","$_POST[checkboxF1]",'.
'"$_POST[checkboxG1]","$_POST[checkboxH1]","$_POST[checkboxI1]",'.
'"$_POST[checkboxJ1]","$_POST[checkboxK1]","$_POST[dietary1]")';
Change to:
$sql_statment = "INSERT INTO 2014_registrations".
"(confirm_number,timecode,company_name,country,address1,address2,city".
",state,zip,phone,fax,email,zone_manager,transport,first_name,".
"last_name,tuesday_tours,tuesday_meat,wed_lunch,wed_dinner,".
"wed_pool_tourney,thurs_lunch,thurs_dinner,fri_shop,fri_tour,dietary)".
"VALUES ($_POST['confirm'],$_POST['timecode'],$_POST['company_name'],".
"$_POST['address'],$_POST['address2'],$_POST['city'],$_POST['state'],".
"$_POST['zip'],$_POST['country],$_POST[phone'],$_POST['fax'],".
"$_POST['email'],$_POST['zonemanager'],$_POST['transport'],".
"$_POST['fattendee1'],$_POST['lattendee1'],$_POST['checkboxA1'],".
"$_POST['radio1'],$_POST['checkboxE1'],$_POST['checkboxF1'],".
"$_POST['checkboxG1'],$_POST['checkboxH1'],$_POST['checkboxI1'],".
"$_POST['checkboxJ1'],$_POST['checkboxK1'],$_POST['dietary1']")";
If you are using $sql_statment = '' you cant put a variable in $sql_statment = '$_POST[confirm]'; because it will treat it like a text. You have to make it like $sql_statment = $_POST['checkboxG1'].','.$_POST['checkboxH1'].','.$_POST['checkboxI1'].','.
Another way is to change it all to $sql_statment = "$_POST['checkboxG1'],$_POST['checkboxH1'],$_POST['checkboxI1'],"; like I did.
See that there is a differance in using ' and ";
Btw. you should use some security for example mysql_escape_string.

Getting information from MySQL

I'm having trouble getting info from my MySQL database.
Here is my code :
/********************
* Database Info
********************/
$host = "localhost";
$user = "admin";
$pass = "admin#";
$database = "db_admin";
/********************
* Database connection
********************/
$con = mysqli_connect( $host, $user, $pass, $database );
if (mysqli_connect_errno ()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error ();
}
$result = array();
if (isset($_POST['ID'])) {
$id = $_POST['ID'];
$query = "SELECT * FROM Servers WHERE PID='" .$id. "'";
$result = mysqli_query($con, $query);
}
print("<pre>".print_r($result,true)."</pre>");
My first question, Did I use "isset" function currectly?
Because it doesnt seem like it is actually going though the if statement.
The Url I am using is : #..com/view.php?ID=1
My second question, Did I use the $query correctly?
Because I echo $id and that echoed out a "MySQL Object()"
Finally, the print printed out "Array()"
I'm just starting on PHP, Thanks for the help :)
A few things:
If you're passing the variable in the query string, use $_GET instead of $_POST to retrieve the values.
$result will return an pointer to the recordset, not the rows themselves. You will have to use mysqli_fetch_array() to fetch the rows.
ADD:
If you are sure that you will only have 1 record returning, you can use:
$row = mysqli_fetch_assoc($query);
echo $row['field_name'];
More then 1 record?
while($row = mysqli_fetch_assoc($query)){
echo $row['field_name'];
}
# your first question: if you have a input field with the name="ID", then its good.
Please also post your HTML :)
$var = 'Hello world';
if(isset($var)){ //If the var $var has been set (in this case it is)
echo $var;
} else {
//If $var is not set, then we get in the else
echo 'The var $var is not set';
}
The best thing is debugging the code with a debugger, you may use XDebug, or at least use var_dump(); to see what happens
var_dump($_REQUEST, $result);
Answer to your first question: It's hard to say if you've used it correctly when you haven't said what you're trying to do. I'm presuming that you only want run the code enclosed in the if-statement if the POST variable 'ID' has been received. If so, yes you've done it correctly.
Answer to your second question: I'm presuming on this line you're trying to build a string with a valid MySQL query. You've done that correctly, assuming $_POST['ID'] is a string (or can be converted to a string, see http://www.php.net/manual/en/language.types.string.php#language.types.string.casting).
If you're echoing $id and it's returning an object, however, you'll have a problem. You can't combine a string and an object like that. You'd need to iterate the object with a foreach, for example, and extract the id from that. The rest of the code won't work until that part is resolved.
The thing to investigate now is why $_POST['ID'] is returning an object. You'll need to provide the form code at the very least.

PHP check a string for something and if there save to variable

I am getting my URL from my site and trying to save a certain field to a variable
$link = "$_SERVER[REQUEST_URI]";
// example of $link = "/index.php?option=com_course&id=1&Itemid=104"
if(strpos($actual_link,'id=') !== false){
$id = // the number after id= in the string
}
basically im checking if id= exists within the string and if it does to save the number of the id to $id.
so the outcome of the example of $link listed above would be for $id = 1
If the URL from the site is passing variables you can just use GET?
$id = $_GET["id"];
First of all, you want the first line to be $link = $_SERVER['REQUEST_URI'];.
But for requesting data like that, from an request to your own server, there's a reserved global variable: $_GET (http://php.net/manual/en/reserved.variables.get.php)
It'd work like this: $id = $_GET['id'];

Categories