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
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.
I am really trying to wrap my head around this and failing miserably. What I want to do it build a MySQL query based on the URL parameters passed by the URL. I am trying to create a re usable dynamic script that can do what it needs to do based on the URL parameter.
This is what I have come up with, and it appears that it does what it is supposed to do (no errors or anything) but nothing actually gets inserted in the database. I know somewhere I have made a dumb mistake (or thought something out wrong) so hopefully one of you guys can point me in the right direction.
Thanks!
//List all possible variables you can expect the script to receive.
$expectedVars = array('name', 'email', 'score', 'age', 'date');
// This is used for the second part of the query (WHERE, VALUES, ETC)
$fields = array('uName','uEmail','uScore','uAge','uDate');
// Make sure some fields are actually populated....
foreach ($expectedVars as $Var)
{
if (!empty($_GET[$Var]))
{
$fields[] = sprintf("'%s' = '%s'", $Var, mysql_real_escape_string($_GET[$Var]));
}
}
if (count($fields) > 0)
{
// Construct the WHERE Clause
$whereClause = "VALUES " . implode(",",$fields);
//Create the SQL query itself
$sql = ("INSERT INTO $mysql_table ($fields) . $whereClause ");
echo "1"; //It worked
mysql_close($con);
}
else
{
// Return 0 if query failed.
echo "0";
}
?>
You missed mysql_query($sql):
if(!mysql_query($sql)){
//die(mysql_error());
}
Please consider to use PDO or My SQLi using parametrize query because mysl_* function depreciated.
Your SQL is all wrong. You're using the field = value syntax for an INSERT, then you're concatenating an array as if it were a string ($fields), and you're missing a couple of parentheses around the values.
a couple of things: i've found for php <-> mysql its important to see what's going into mysql and experiement directly with those queries in phpmyadmin when i get stuck.
1 - in my code I output mysql_error() when the query fails or when a debug flag is set. this usually explains the sql issue in a way that can point me to a misspelled field name etc...
2 - this way i can feed that mysql query directly into phpmyadmin and tweak it until it gives me the results i want. (while i'm there i can also use explain to see if i need to optimize the table)
specifics in your code. unlike C languages sprintf is implied. here's how i'd write your code:
// List all possible variables you can expect the script to receive.
$expectedvars = array('name', 'email', 'score', 'age', 'date');
// This is used for the second part of the query (WHERE, VALUES, ETC)
// $fields = array('uName','uEmail','uScore','uAge','uDate');
$fields = array();
// Set only the variables that were populated ...
foreach ($expectedvars as $var) {
if (!empty($_GET[$var])) {
$name = "u" + ucwords($var); // convert var into mysql field names
$fields[] = "{$name} = " . mysql_real_escape_string($_GET[$var]);
}
}
// only set those fields which are passed in, let the rest use the mysql default
if (count($fields) > 0) {
// Create the SQL query itself
$sql = "INSERT INTO {$mysql_table} SET " . implode("," , $fields);
$ret = mysql_query($sql);
if (!$ret) {
var_dump('query_failed: ', $sql, $ret);
echo "0"; // Query failed
} else {
echo "1"; // It worked
}
} else {
// Return 0 if nothing to do
echo "0";
}
mysql_close($con);