Problem with php variable to using MySQL query - php

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

Related

PHP variable is not working with WHERE clause

My query is not working when I use the variable in the WHERE clause. I have tried everything. I echo the variable $res, it shows me the perfect value, when I use the variable in the query the query is not fetching anything thus mysqli_num_rows is giving me the zero value, but when I give the value that the variable contains statically the query executes perfectly. I have used the same kind of code many times and it worked perfectly, but now in this part of module it is not working.
Code:
$res = $_GET['res']; // I have tried both post and get
echo $res; //here it echos the value = mahanta
$query = "SELECT * FROM `seller` WHERE `restaurant` = '$res'"; // Here it contains the problem I have tried everything. Note: restaurant name is same as it is in the database $res contains a value and also when I give the value of $res i.e. mahanta in the query it is then working.
$z = mysqli_query($conn, $query);
$row2 = mysqli_fetch_array($z);
echo var_dump($row2); // It is giving me null
$num = mysqli_num_rows($z); // Gives zero
if ($num > 0) {
while ($row2 = mysqli_fetch_array($z)) {
$no = $row2['orders'];
$id = $res . $no;
}
}
else {
echo "none selected";
}
As discussed in the comment. By printing the query var_dump($query), you will get the exact syntax that you are sending to your database to query.
Debugging Tip: You can also test by pasting the var_dump($query) value in your database and you will see the results if your query is okay.
So update your query syntax and print the query will help you.
$query = "SELECT * FROM `seller` WHERE `restaurant` = '$res'";
var_dump($query);
Hope this will help you and for newbies in future, how to test your queries.
Suggestion: Also see how to write a mysql query syntax for better understanding php variables inside mysql query
The problem is the way you're using $res in your query. Use .$res instead. In PHP (native or framework), injecting variables into queries need a proper syntax.

Trying to echo a specific variable from a specific row

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

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.

Creating a dynamic MySQL query from URL paramaters

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);

Categories