Replacing $_HTTP_GET_VARS with $_GET - php

This is a question about setting up variables in an array for a personal memory aid project analogous to the old paper-based flash cards, which I now want to dust off. A PHP programmer at my old work 5 years ago helped write the page - alas I have long since lost contact, and my PHP skills are rudimentary at best.
Current Code (PHP4)
<?php
# Setting up Variables
reset($HTTP_GET_VARS);
while(list($key,$value) = each($HTTP_GET_VARS))
{
$$key = $value;
}
#set query string, current_id and current_index
$query_string = "sound=$sound&hint=$hint&type=$type";
if(!isset($current_id)) $current_id = "";
if(!isset($current_index)) $current_index = "";
#connect to MySQL
$conn = #mysql_connect( "localhost","xxxx","xxxx" )
or die( "Sorry - could not connect to MySQL" );
#select the specified database
$rs = #mysql_select_db( "xxx", $conn )
or die( "Sorry - could not connect to specified Db" );
# create the query to select the records and then …
Attempts to find solution
Initially I tried a simple substitution as recommended elsewhere. But in the case of this page's code it did not work. I also looked at Replaced $HTTP_GET_VARS with $_GET, but not working and it too did not solve the issue (see below attempt)
Attempted New Code (PHP5)
Assuming a single table Db, with multiple columns, say 'alpha', 'bravo' and 'charlie', then rows of data in the table cells. The now depreciated $HTTP_GET_VARS used to work fine:
<?php
# Setting up Variables
unset($alpha, $bravo, $charlie);
while(list($key,$values) = each($alpha = $_GET['alpha'], $bravo = $_GET['bravo'], $charlie = $_GET['charlie']))
{
$$key = $value;
}
#set query string, current_id and current_index
$query_string = "sound=$sound&hint=$hint&type=$type";
if(!isset($current_id)) $current_id = "";
if(!isset($current_index)) $current_index = "";
#connect to MySQL
$conn = #mysql_connect( "localhost","xxxx","xxxx" )
or die( "Sorry - could not connect to MySQL" );
#select the specified database
$rs = #mysql_select_db( "xxx", $conn )
or die( "Sorry - could not connect to specified Db" );
# create the query to select the records and then...
The error I get with this code is: Notice: Undefined index: alpha in C:\wamp\www\page2.php on line 4

that is not an error, it is a notice - telling you some $_GET array index might not exist where you use it. You might look into php's error_reporting() and possibly set it to error_reporting(E_ERROR) at the very beginngin of the script to avoid notices - in your case that would probably suffice.
http://php.net/manual/en/function.error-reporting.php

4) If you want to have the keys available as local variables and (correctly) have register_globals disabled, what's wrong with extract($_GET);? – DaveRandom
From:
<?php
# Setting up Variables
unset($alpha, $bravo, $charlie);
while(list($key,$values) = each($alpha = $_GET['alpha'], $bravo = $_GET['bravo'], $charlie = $_GET['charlie']))
{
$$key = $value;
}
To:
# Setting up Variables
unset($alpha, $bravo, $charlie);
extract($_GET);
Seems to have done the trick.
Thanks DaveRandom

Because you unset variables that aren't set yet
I think you have in php4 register_globals on and in php 5 off
register_globals is a bad thing so don't put it on

Related

Data not being saved in DB via PHP form

I,ve trying to save some data in my DB, but it just don't save, no error thrown, i used the echo query_orcN; to see if the data that was input by the form is valid, and its all fine, the form can input up to 5 services ($servicoN), so the cod is kinda repetetive, as i am new with php and mySql, expect to see some newbie coding.
I also verified and the logic to choose what if statement will be used is working fine too, so i will post just the case with one service:
...
<?php
include('login/conexao.php');
$nome_cli = $_POST['nome_cli'];
$nome_orc = $_POST['nome_orc'];
$obs_trab = $_POST['obs_orc'];
$servico1 = $_POST['serv1'];
$obs_serv1 = $_POST['obs_serv1'];
$total1 = $_POST['total1'];
$servico2 = $_POST['serv2'];
$obs_serv2 = $_POST['obs_serv2'];
$total2 = $_POST['total2'];
$servico3 = $_POST['serv3'];
$obs_serv3 = $_POST['obs_serv3'];
$total3 = $_POST['total3'];
$servico4 = $_POST['serv4'];
$obs_serv4 = $_POST['obs_serv4'];
$total4 = $_POST['total4'];
$servico5 = $_POST['serv5'];
$obs_serv5 = $_POST['obs_serv5'];
$total5 = $_POST['total5'];
//um serviço
if($servico1 != '' && $servico2 == '' && $servico3 == '' && $servico4 == '' && $servico5 == ''){
$query_orc1 = "START TRANSACTION;
SET #cod_cli = (SELECT cod_cliente
FROM CLIENTE
WHERE nome_cliente = '$nome_cli');
INSERT INTO TRABALHO(nome_trabalho, cod_cliente, obs_trabalho, statuspag_trabalho)
VALUES ('$nome_orc', #cod_cli, '$obs_trab', 0);
SET #orc = LAST_INSERT_ID();
SET #cod_serv1 = (SELECT cod_servicos
FROM SERVICOS
WHERE descri_servicos = '$servico1');
INSERT INTO SERV_TRAB(cod_trabalho, cod_servicos, qtt_serv_trab, obs_serv_trab)
VALUES (#orc, #cod_serv1, $total1, '$obs_serv1');
COMMIT;";
if($resultado_query_orc1 = mysqli_multi_query($conexao, $query_orc1))
{
//echo $query_orc1;
header('Location: sucesso_orc.php');
exit();
}
else
{
echo "<h3>Falha </h3>".$valid;
echo $result_msg_cliente;
}}
...
I'm using myawardspace to host my project, and already set de engine of the tables to InnoDB as for what i,ve understood, it's one that can support the TRANSACTION.
Already thanks anyone in advance for any help and attention, its the first time a post a question here, hope it's well structered.
You have two problems.
PROBLEM 1: failure of the script to produce expected results (i.e., the question you asked).
PROBLEM 2: Lack of diagnostic information.
To solve problem 2, put the following three lines at the start of your script:
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
Running the script with this change might produce error messages that will lead to a solution for your script. If not, run simple php with a known error, such as:
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
echo '1' //no semi colon is an error
echo '2';
If this produces no error messages, it means there is something in the php or web server (such as Apache) configuration stopping them. Find error logs for php and and the web server (probably apache). Exact details for accessing logs are available myawardspace.
SOLVING PROBLEM 1 - Your Script
Whenever running sql through php, there are two major steps involved in getting it to work.
STEP 1: Verify the sql is valid.
The first shot at forming sql within a php script very often contains errors. That means an important milestone in the development of every php script interacting with a database is verifying the sql outside php. An easy way to do this is to put the following statement immediately after setting the value of query_orc1:
echo query_orc1;
exit;
This will put onto your screen the sql the script is attempting to running. Use copy/paste to run the sql using phpmyadmin or whatever interface you have for your database. If there are problems with the sql, you will see them here. If the sql runs as expected, then you know the part of your script creating the sql is working.
STEP 2: Fix php errors that are failing to submit sql correctly to the database.
Maybe someone can spot errors in this script without benefit of error messages. That is fantastic if someone can provide you that information. I would focus on getting your system to show you error message before trying to troubleshoot the php.
I have no experience with mysqli, therefore I use PDO.
At first: Maybe you should overthink the first part with servico1 to servico5. There is maybe a better solution.
My Changes:
Switch from mysqli to PDO
add prepare statements
replace two statements with subselects
I hope I have commented on every change.
The altered Code:
<?php
include('login/conexao.php');
// Build an PDO Instance (Documentation: https://www.php.net/manual/en/book.pdo.php)
// $db = new PDO("mysql:host=localhost;dbname=test;charset=UTF8", "username", "password", [
// PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
// ]);
$nome_cli = $_POST['nome_cli'];
$nome_orc = $_POST['nome_orc'];
$obs_trab = $_POST['obs_orc'];
$servico1 = $_POST['serv1'];
$obs_serv1 = $_POST['obs_serv1'];
$total1 = $_POST['total1'];
$servico2 = $_POST['serv2'];
$obs_serv2 = $_POST['obs_serv2'];
$total2 = $_POST['total2'];
$servico3 = $_POST['serv3'];
$obs_serv3 = $_POST['obs_serv3'];
$total3 = $_POST['total3'];
$servico4 = $_POST['serv4'];
$obs_serv4 = $_POST['obs_serv4'];
$total4 = $_POST['total4'];
$servico5 = $_POST['serv5'];
$obs_serv5 = $_POST['obs_serv5'];
$total5 = $_POST['total5'];
// switch from
// ($servico1 != '') to !empty($servico1)
// optional, if you like the syntax more, you could use: ($servico1 !== '')
// tripple equals or !== prevents type juggeling
// #see https://www.php.net/manual/en/language.types.type-juggling.php
if (!empty($servico1) && empty($servico2) && empty($servico3) && empty($servico4) && empty($servico5)) {
// Prepared statment to prevent sqlinjection
$stmt = $db->prepare("INSERT INTO TRABALHO (
nome_trabalho,
cod_cliente,
obs_trabalho,
statuspag_trabalho
) VALUES (
:nome_orc,
(SELECT cod_cliente FROM CLIENTE WHERE nome_cliente = :nome_cli ), -- with subselects we can remove unnecessary sql statments
:obs_trab,
0
)
");
try {
// Execute the query and bind the named paraments
// All variables a treated as string
$stmt->execute([
'nome_orc' => $nome_orc,
'nome_cli' => $nome_cli,
'obs_trab' => $obs_trab
]);
} catch (Exception $e) {
// #todo handle exception
echo $e->getMessage();
exit;
}
$stmt = $db->prepare("INSERT INTO SERV_TRAB (
cod_trabalho,
cod_servicos,
qtt_serv_trab,
obs_serv_trab
) VALUES (
:orc,
(SELECT cod_servicos FROM SERVICOS WHERE descri_servicos = :servico1),
$total1,
:obs_serv1
)
");
try {
// get last inserted id with pdo: $db->lastInsertId()
$stmt->execute([
'orc' => $db->lastInsertId(),
'servico1' => $servico1,
'obs_serv1' => $obs_serv1
]);
} catch (Exception $e) {
// #todo handle exception
echo $e->getMessage();
exit;
}
// we don't need an if at this point because if an error occures it will throw an exception
// and the try / catch will catch and handle it
header('Location: sucesso_orc.php');
exit;
}

PHP INSERT into creates Database error

I am attempting to create a function that will insert items (and will do the same to edit) items in a database through a form. I have the form and the PHP - and when I run the function, I get the correct database name to pull and the variable names to pull along with the values I input, but I then see a database error? Any help would be great (I'm still newer to PHP really and pulling out some hair)
Config File:
$hostname = 'localhost';
$username = 'DEFINED';
$password = 'DEFINED';
$database = 'DEFINED';
$table = 'recipes';
require('../config.php');
$link = mysql_connect($hostname,$username,$password);
mysql_select_db($database,$link);
/* Get values and submit */
$rid = mysql_real_escape_string($_POST['rid']);
$name = mysql_real_escape_string($_POST['name']);
$category = mysql_real_escape_string($_POST['category']);
$tags = mysql_real_escape_string($_POST['tags']);
$search_tags = mysql_real_escape_string($_POST['search_tags']);
$description = mysql_real_escape_string($_POST['description']);
$description2 = mysql_real_escape_string($_POST['description2']);
$recipeAbout = mysql_real_escape_string($_POST['recipeAbout']);
$ingredients_1 = mysql_real_escape_string($_POST['ingredients_1']);
$directions_1 = mysql_real_escape_string($_POST['directions_1']);
$query = "INSERT INTO $table (name, category, tags, search_tags, description,description2, recipeAbout, ingredients_1,directions_1) VALUES ('$name','$category','$description','$description2' $tags','$search_tags','$description','$recipeAbout','$ingredients_1','$directions_1')";
echo $query;
Besides the missing comma in '$description2' $tags' => '$description2', $tags' which you said had been added afterwards, and signaled by Ryan: there's also a missing quote, so change it to '$description2', '$tags' and having 2x '$description' variables, remove one.
VALUES
('$name','$category','$tags','$description','$description2', '$search_tags','$recipeAbout','$ingredients_1','$directions_1')";
However, the most important part to querying, is that you must use mysql_query() which you are not using => mysql_query() which is why data isn't being inserted, once you've fixed the syntax errors.
mysql_query() is the essential part.
Add the following to your code:
if(mysql_query($sql,$link)){
echo "Success";
}
else{
echo "Error" . mysql_error();
}
Plus, use prepared statements, or PDO with prepared statements.
You're using a deprecated library and open to SQL injection..
Plus make sure you have assigned $table to the table you wish to enter data into. It's not shown in your question.
You also did not show what your HTML form contains. Make sure that you are using a POST method and that all elements are named with no typos.
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
Sidenote: Error reporting should only be done in staging, and never production.
EDIT: and using mysqli_
As a quick test, try the following and replacing the values in the line below with your own.
<?php
$link = mysqli_connect("host","username","password","database")
or die("Error " . mysqli_error($link));
$table = "recipes";
$name = mysqli_real_escape_string($link,$_POST['name']);
mysqli_query($link,"INSERT INTO `$table` (`name`) VALUES ('".$name."')")
or die(mysqli_error($link));
?>
If that still does not work, then you need to check your database, table, column name(s), including types and column lengths.
Lot's of stuff wrong here...
You're missing a quote on the second of these two items, as well as either a string concat or a comma: '$description2' $tags'
You've also got your order messed up for tags, search tags, and description 1/2.
$description is in there twice (you have 9 columns defined and 10 values in your statement)
You don't seem to have declared a value for $table
As Fred -ii- has pointed out in his answer, you're missing mysql_query() to actually run it. I assumed you have it further down in your code, but it's missing from the post, which is causing some confusion...
Also, consider updating to use mysqli instead of mysql functions.
what are you echoing $query for?
You do not have any reason to do that except if you just want to use it as a string variable.
it should be mysql_query($query);
What is the exact "database error" error you are getting?
I suggest reading this article about PDO
If you can't insert the data correctly, this might be your problem too.

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.

SQL Table not updating in PHP

I'm trying to create an update function in PHP but the records don't seem to be changing as per the update. I've created a JSON object to hold the values being passed over to this file and according to the Firebug Lite console I've running these values are outputted just fine so it's prob something wrong with the sql side. Can anyone spot a problem? I'd appreciate the help!
<?php
$var1 = $_REQUEST['action']; // We dont need action for this tutorial, but in a complex code you need a way to determine ajax action nature
$jsonObject = json_decode($_REQUEST['outputJSON']); // Decode JSON object into readable PHP object
$name = $jsonObject->{'name'}; // Get name from object
$desc = $jsonObject->{'desc'}; // Get desc from object
$did = $jsonObject->{'did'};// Get id object
mysql_connect("localhost","root",""); // Conect to mysql, first parameter is location, second is mysql username and a third one is a mysql password
#mysql_select_db("findadeal") or die( "Unable to select database"); // Connect to database called test
$query = "UPDATE deal SET dname = {'$name'}, desc={'$desc'} WHERE dealid = {'$did'}";
$add = mysql_query($query);
$num = mysql_num_rows($add);
if($num != 0) {
echo "true";
} else {
echo "false";
}
?>
I believe you are misusing the curly braces. The single quote should go on the outside of them.:
"UPDATE deal SET dname = {'$name'}, desc={'$desc'} WHERE dealid = {'$did'}"
Becomes
"UPDATE deal SET dname = '{$name}', desc='{$desc}' WHERE dealid = '{$did}'"
On a side note, using any mysql_* functions isn't really good security-wise. I would recommend looking into php's mysqli or pdo extensions.
You need to escape reserved words in MySQL like desc with backticks
UPDATE deal
SET dname = {'$name'}, `desc`= {'$desc'} ....
^----^--------------------------here
you need to use mysql_affected_rows() after update not mysql_num_rows

Joomla, Mysql error

I have uploaded a page with the code below to my joomla root directory.
<?php
$value = trim($_POST['opts']);
if ($value){
$db = "my_db";
$link = mysql_connect('localhost',$me,$my_password);
if(!$link) die("Error 1 ".mysql_error());
mysql_select_db($db);
**$query = "SELECT introtext,fulltext FROM jos_content WHERE title='$value' ";**
$result = mysql_query($query);
**if(!$result) die("Error 2 ".mysql_error());**
$obj = mysql_fetch_array($result);
$obj_f = $obj[0];
$lenght = strlen($obj_f);
$header2 = strpos($obj_f, "Did you know");
$header3 = strstr($obj_f, "Summary");
$third_part = $header3;
$first_part = substr($obj_f, 0, ($header2 - 1));
$second_part = substr($obj_f, $header2,((strpos($obj_f, "Summary")) - $header2) );
}
?>
the problem is that when i change my select(http://sanatural.co.za/sanp/test.php) i get this error message:
Error 2 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'fulltext FROM jos_content WHERE title='Arthritis'' at line 1
The code highlighted in bold is where i think the problem might be. Please help.
Fulltext is a mysql keyword and you must escape it. Replace:
$query = "SELECT introtext,fulltext FROM jos_content WHERE title='$value' ";
with
$query = "SELECT `introtext`,`fulltext` FROM jos_content WHERE title='$value' ";
This is a bit off topic, but an easy way to use PHP in Joomla is through the PHP Component.
http://www.fijiwebdesign.com/products/joomla-php-pages.html
This allows you to put add PHP in Joomla as if it were a Joomla Component.
If you want something quick, then you can also use the PHP Module.
http://www.fijiwebdesign.com/products/joomla-php-module.html
Just install either, add your PHP, and add it to the Joomla menu.
You can then use the Joomla API which will simplify what you want to do within Joomla.
For example, your database queries could be:
// Joomla already has a connection to the DB
// available here as a Singleton in the Factory pattern
$Db =& JFactory::getDBO();
// querying the db
$Db->setQuery('SELECT `introtext`,`fulltext` FROM #__content WHERE title='.$Db->Quote($value).' LIMIT 1';
// retrieving a single row as an object
$article = $Db->loadObject();
// handle errors
if($Db->getErrorNum()) {
JError::raiseError( 500, $Db->stderr());
}
//Then accessing each column/property would look something like:
$intro = $article->introtext;
$text = $article->fulltext;
The full Database API is documented here:
http://api.joomla.org/Joomla-Framework/Database/JDatabase.html

Categories