Logging $_SERVER to mysql - php

I use this code , to log $_SERVER['REMOTE_ADDR']; to my small db
my issue is value never saved to db , cant figure what i missed in the code
Any tips ?
<?php
mysql_connect("localhost", "usr", "passwd");
mysql_select_db("db") or die ( 'Can not select database' );
function initCounter() {
$ip = $_SERVER['REMOTE_ADDR'];
$sql = "INSERT INTO logs(REMOTE_ADDR,) VALUES ('$ip')";
}
echo $_SERVER['REMOTE_ADDR'];
?>

This should work. In addition to the other comments here, you had a comma (,) too much in your query.
<?php
mysql_connect("localhost", "usr", "passwd");
mysql_select_db("db") or die ( 'Can not select database' );
function initCounter() {
$ip = $_SERVER['REMOTE_ADDR'];
$sql = "INSERT INTO logs (REMOTE_ADDR) VALUES ('$ip')";
mysql_query($sql);
}
initCounter();
?>

You aren't actually executing the query. You create the SQL but don't use mysql_query($sql)
You have a comma at this point in the SQL REMOTE_ADDR, <-- remove that
When you execute the query, use mysql_error() to test for an error message (and check the result of mysql_query() for a boolean false.
Finally I would suggest switching to MySQLi or PDO.

If that's you're full code... there is one thing missing you actually need to EXECUTE the query...
mysql_query($sql);
EDIT:
I have just noticed, you're connecting to the DB OUTSIDE of the function trying to run the Query... obviously it will fail as inside the function, it has no awareness of the DB connection.

Related

how to insert value from radio button into mysql using php

i have tried this code to insert value into database, but i don't Know why, the value was not send into the databases. The table i have created in the mysql :
<?php
require_once "connection.php";
$conn = connect();
$db = connectdb();
mysql_select_db($db,$conn) or die (mysql_error() . "\n");
$query_usr = "select * from soalselidik";
$usr = mysql_query($query_usr,$conn) or die(mysql_error()."\n".$query_usr);
$row_usr=mysql_fetch_assoc($usr);
//to insert in database
$a1=$_POST['a1'];
$a2=$_POST['a2'];
$a3=$_POST['a3'];
$a4=$_POST['a4'];
$b1=$_POST['b1'];
$b2=$_POST['b2'];
$b3=$_POST['b3'];
$b4=$_POST['b4'];
$c1=$_POST['c1'];
$c2=$_POST['c2'];
$c3=$_POST['c3'];
$c4=$_POST['c4'];
$d1=$_POST['d1'];
$d2=$_POST['d2'];
$d3=$_POST['d3'];
$d4=$_POST['d4'];
$e1=$_POST['e1'];
$f1=$_POST['f1'];
echo $query ="insert into soalselidik (a1,a2,a3,a4,b1,b2,b3,b4,c1,c2,c3,c4,d1,d2,d3,d4,e1,f1) values('$a1','$a2','$a3','$a4','$b1','$b2','$b3','$b4','$c1','$c2','$c3','$c4''$d1','$d2','$d3','$d4','$e1','$f1')";
$result = mysql_query($query);
echo "<script languange = 'Javascript'>
alert('thankyou ! Penilaian anda diterima ');
location.href = 'home.php';</script>";
?>
'$c4''$d1'
Find that in your query and fix it :) And please do some error checking, and please stop using MySQL_* for your own good. Why should people not run any error checking mechanism that's already provided in the language and expect others to debug typos?
In case you didn't get it, there's a comma missing
How can I prevent SQL injection in PHP?

php inserting into a MySQL data field

I am not sure what I am doing wrong, can anybody tell me?
I have one variable - $tally5 - that I want to insert into database jdixon_WC14 table called PREDICTIONS - the field is called TOTAL_POINTS (int 11 with 0 as the default)
Here is the code I am using. I have made sure that the variable $tally5 is being calculated correctly, but the database won't update. I got the following from an online tutorial after trying one that used mysqli, but that left me a scary error I didn't understand at all :)
if(! get_magic_quotes_gpc() )
{
$points = addslashes ($tally5);
}
else
{
$points = $tally5;
}
$sql = "INSERT INTO PREDICTIONS ".
"(TOTAL_POINTS) ".
"VALUES('$points', NOW())";
mysql_select_db('jdixon_WC14');
I amended it to suit my variable name, but I am sure I have really botched this up!
help! :)
I think you just need to learn more about PHP and its relation with MYSQL. I will share a simple example of insertion into a mysql database.
<?php
$con=mysqli_connect("localhost","peter","abc123","my_db");
// Check for errors in connection to database.
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query = "INSERT INTO Persons (FirstName, LastName, Age) VALUES ('Peter', 'Griffin',35)";
mysqli_query($con, $query);
mysqli_close($con); //Close connection
?>
First, you need to connect to the database with the mysqli_connect function. Then you can do the query and close the connection
Briefly,
For every PHP function you use, look it up here first.
(You will learn that it is better to go with mysqli).
http://www.php.net/manual/en/ <---use the search feature
Try working on the SQL statement first. If you have the INSERT process down, proceed.
You need to use mysql_connect() before using mysql_select_db()
Once you have a connection and have selected a database, now you my run a query
with mysql_query()
When you get more advanced, you'll learn how to integrate error checking and response into the connection, database selection, and query routines. Convert to mysqli or other solutions that are not going to be deprecated soon (it is all in the PHP manual). Good luck!
if(! get_magic_quotes_gpc() )
{
$points = addslashes ($tally5);
}
else
{
$points = $tally5;
}
mysql_select_db('jdixon_WC14');
$sql = "INSERT INTO PREDICTIONS (TOTAL_POINTS,DATE) ". //write your date field name instead "DATE"
"VALUES('$points', NOW())";
mysql_query($sql);

Warning: mysqli_query() [function.mysqli-query]: Empty query in C:\xampp\htdocs\option1\db_def.php on line 49

Can anyone help me on this? I am a php beginner. Error I am getting is:
Warning: "mysqli_query() [function.mysqli-query]: Empty query in C:\xampp\htdocs\option1\db_def.php on line 49"
i.e where if statement starts.
<?php
include ('config.php');
$con= mysqli_connect("localhost","root","") or die ("could not connect to mysql");
if(isset($_POST['submit']))
{
$date= $_POST["date"];
$sno= $_POST["sno"];
// and so on
$sql= mysql_query("INSERT INTO data(date,sno,block,name,so_wo_do,plot_size,hno,hno1,street,mohalla,ws_id,sid,ws_conn,s_conn,dispo_conn,elec_acc,residential_commercial,trade_licence,hno2,street2,mohalla2,contact,email,year_construction,structure,nature_unit,usage,basement,gnd_floor,first_floor,sec_floor,third_floor,any_floor,total,area_sft,oid_no,remarks) VALUES('$_POST[date]','$_POST[sno]','$_POST[block]','$_POST[name]','$_POST[so_wo_do]','$_POST[plot_size]','$_POST[hno]','$_POST[hno1]','$_POST[street]','$_POST[mohalla]','$_POST[ws_id]','$_POST[sid]','$_POST[ws_conn]','$_POST[s_conn]','$_POST[dispo_conn]','$_POST[elec_acc]','$_POST[residential_commercial]','$_POST[trade_licence]','$_POST[hno2]','$_POST[street2]','$_POST[mohalla2]','$_POST[contact]','$_POST[email]','$_POST[year_construction]','$_POST[structure]','$_POST[nature_unit]','$_POST[usage]','$_POST[basement]','$_POST[gnd_floor]','$_POST[first_floor]','$_POST[sec_floor]','$_POST[third_floor]','$_POST[any_floor]','$_POST[total]','$_POST[area_sft]','$_POST[oid_no]','$_POST[remarks]')");
if(!mysqli_query($con,$sql))
{
echo("Member Registered!");
}
else
{
echo("Input data is fail");
}
}
mysqli_close($con);
?>
you are using mysqli_* functions and also mixing it with mysql_query
here $sql= mysql_query(----) your are using again $Sql in mysqli_query(); that is incorrect.
please change it to $sql = "INSERT INTO data( // al col names) VALUES(//all vals)"
and use $sql it inside mysqli_query($con,$sql).
Remove mysql_query()
You should try this. Can you please define why you include('config.php') file? and you are making new connection also ..
<?php
//include ('config.php');
$con= mysqli_connect("localhost","root","") or die ("could not connect to mysql");
if(isset($_POST['submit']))
{
$date= $_POST["date"];
$sno= $_POST["sno"];
// and so on
$sql= "INSERT INTO data(date,sno,block,name,so_wo_do,plot_size,hno,hno1,street,mohalla,ws_id,sid,ws_conn,s_conn,dispo_conn,elec_acc,residential_commercial,trade_licence,hno2,street2,mohalla2,contact,email,year_construction,structure,nature_unit,usage,basement,gnd_floor,first_floor,sec_floor,third_floor,any_floor,total,area_sft,oid_no,remarks) VALUES('$_POST[date]','$_POST[sno]','$_POST[block]','$_POST[name]','$_POST[so_wo_do]','$_POST[plot_size]','$_POST[hno]','$_POST[hno1]','$_POST[street]','$_POST[mohalla]','$_POST[ws_id]','$_POST[sid]','$_POST[ws_conn]','$_POST[s_conn]','$_POST[dispo_conn]','$_POST[elec_acc]','$_POST[residential_commercial]','$_POST[trade_licence]','$_POST[hno2]','$_POST[street2]','$_POST[mohalla2]','$_POST[contact]','$_POST[email]','$_POST[year_construction]','$_POST[structure]','$_POST[nature_unit]','$_POST[usage]','$_POST[basement]','$_POST[gnd_floor]','$_POST[first_floor]','$_POST[sec_floor]','$_POST[third_floor]','$_POST[any_floor]','$_POST[total]','$_POST[area_sft]','$_POST[oid_no]','$_POST[remarks]')";
$query=mysqli_query($con,$sql);
if($query)
echo("Member Registered!");
}
else
{
echo("Input data is fail");
}
}
mysqli_close($con);
?>
please use only mysqli query
$sql = "INSERT INTO data(date,sno,block,name,so_wo_do,plot_size,hno,hno1,street,mohalla,ws_id,sid,ws_conn,s_conn,dispo_conn,elec_acc,residential_commercial,trade_licence,hno2,street2,mohalla2,contact,email,year_construction,structure,nature_unit,usage,basement,gnd_floor,first_floor,sec_floor,third_floor,any_floor,total,area_sft,oid_no,remarks) VALUES('$_POST[date]','$_POST[sno]','$_POST[block]','$_POST[name]','$_POST[so_wo_do]','$_POST[plot_size]','$_POST[hno]','$_POST[hno1]','$_POST[street]','$_POST[mohalla]','$_POST[ws_id]','$_POST[sid]','$_POST[ws_conn]','$_POST[s_conn]','$_POST[dispo_conn]','$_POST[elec_acc]','$_POST[residential_commercial]','$_POST[trade_licence]','$_POST[hno2]','$_POST[street2]','$_POST[mohalla2]','$_POST[contact]','$_POST[email]','$_POST[year_construction]','$_POST[structure]','$_POST[nature_unit]','$_POST[usage]','$_POST[basement]','$_POST[gnd_floor]','$_POST[first_floor]','$_POST[sec_floor]','$_POST[third_floor]','$_POST[any_floor]','$_POST[total]','$_POST[area_sft]','$_POST[oid_no]','$_POST[remarks]')";
mysqli_query($con,$sql);
I had the same problem, the problem was the range, I had to move the $query = ($con, "SELECT blah blah"); a couple of lines.
Never had this before in the old way of coding, this is msqli vs msql.
You just need to relearn everything you have learned if you only know how to code the old way.
This reply is for the topic title only, my post is not a reaction or solving answer to this topic.
It might help somebody else if ;)
I think it is a range or global problem, because it is returning an empty query.
But without more information on db_def.php on line 49 it is hard to say.
include ('config.php');
$con= mysqli_connect("localhost","root","") or die ("could not connect to mysql");
You need to create a global variable in "db_def.php" that declaires $con or create one every time you connect or query in 'db_def.php'

PHP SQL Truncate

I'm having a problem trying to truncate the 'requestID' field from my requests table.
This is my code.
<?php
include 'mysql_connect.php';
USE fypmysqldb;
TRUNCATE TABLE requestID;
echo "Request ID table has been truncated";
?>
I'm using server side scripting so no idea what error is coming back.
Anyone got an idea?
You aren't executing queries, you're just putting SQL code inside PHP which is invalid. This assumes you are using the mysql_*() api (which I kind of suspect after viewing one of your earlier questions), but can be adjusted if you are using MySQLi or PDO.
// Assuming a successful connection was made in this inclusion:
include 'mysql_connect.php';
// Select the database
mysql_select_db('fypmysqldb');
// Execute the query.
$result = mysql_query('TRUNCATE TABLE requestID');
if ($result) {
echo "Request ID table has been truncated";
}
else echo "Something went wrong: " . mysql_error();
Take a look at the function mysql_query which performs the query execution. The code to execute a query should look something like this.
$link = mysql_connect('host', 'username', 'password') or die(mysql_error());
mysql_select_db("fypmysqldb", $link) or die(mysql_error());
mysql_query("TRUNCATE TABLE requestID", $link) or die(mysql_error());
mysql_close($link);

PHP will not delete from MySQL

For some reason, JavaScript/PHP wont delete my data from MySQL! Here is the rundown of the problem.
I have an array that displays all my MySQL entries in a nice format, with a button to delete the entry for each one individually. It looks like this:
<?php
include("login.php");
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("<br/><h1>Unable to connect to MySQL, please contact support at support#michalkopanski.com</h1>");
//select a database to work with
$selected = mysql_select_db($dbname, $dbhandle)
or die("Could not select database.");
//execute the SQL query and return records
if (!$result = mysql_query("SELECT `id`, `url` FROM `videos`"))
echo 'mysql error: '.mysql_error();
//fetch tha data from the database
while ($row = mysql_fetch_array($result)) {
?>
<div class="video"><a class="<?php echo $row{'id'}; ?>" href="http://www.youtube.com/watch?v=<?php echo $row{'url'}; ?>">http://www.youtube.com/watch?v=<?php echo $row{'url'}; ?></a><a class="del" href="javascript:confirmation(<? echo $row['id']; ?>)">delete</a></div>
<?php }
//close the connection
mysql_close($dbhandle);
?>
The delete button has an href of javascript:confirmation(<? echo $row['id']; ?>) , so once you click on delete, it runs this:
<script type="text/javascript">
<!--
function confirmation(ID) {
var answer = confirm("Are you sure you want to delete this video?")
if (answer){
alert("Entry Deleted")
window.location = "delete.php?id="+ID;
}
else{
alert("No action taken")
}
}
//-->
</script>
The JavaScript should theoretically pass the 'ID' onto the page delete.php. That page looks like this (and I think this is where the problem is):
<?php
include ("login.php");
mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
mysql_select_db ($dbname)
or die("Unable to connect to database");
mysql_query("DELETE FROM `videos` WHERE `videos`.`id` ='.$id.'");
echo ("Video has been deleted.");
?>
If there's anyone out there that may know the answer to this, I would greatly appreciate it. I am also opened to suggestions (for those who aren't sure).
Thanks!
In your delete.php script, you are using this line :
mysql_query("DELETE FROM `videos` WHERE `videos`.`id` ='.$id.'");
The $id variable doesn't exists : you must initialize it from the $_GET variable, like this :
$id = $_GET['id'];
(This is because your page is called using an HTTP GET request -- ie, parameters are passed in the URL)
Also, your query feels quite strange : what about this instead :
mysql_query("DELETE FROM `videos` WHERE `videos`.`id` = '$id' ");
ie, removing the '.' : you are inside a string already, so there is nothing to concatenate (the dot operator in PHP is for concatenation of strings)
Note :
if this works on some server, it is probably because of register_globals
For more informations, see Using Register Globals
But note that this "feature" has been deprecated, and should definitely not be used !
It causes security risks
And should disappear in PHP 6 -- that'll be a nice change, even if it breaks a couple of old applications
your code has a big SQL injection hole : you should sanitize/filter/escape the $id before using it in a query !
If you video.id is a string, this means using mysql_real_escape_string
If you where using the mysqli or PDO extensions, you could also take a look at prepared statements
with an integer, you might call intval to make sure you actually get an integer.
So, in the end, I would say you should use something that looks like this :
$id = $_GET['id'];
$escaped_id = mysql_real_escape_string($id);
$query = "DELETE FROM `videos` WHERE `videos`.`id` = '$escaped_id'";
// Here, if needed, you can output the $query, for debugging purposes
mysql_query($query);
You're trying to delimit your query string very strangely... this is what you want:
mysql_query('DELETE FROM `videos` WHERE `videos`.`id` ='.$id);
But make sure you sanitize/validate $id before you query!
Edit: And as Pascal said, you need to assign $id = $_GET['id'];. I overlooked that.
In your delete.php you never set $id.
You need to check the value in $_REQUEST['id'] (or other global variable) and ONLY if it's an integer, set $id to that.
EDIT: Oh, also you need to remove the periods before and after $id in the query. You should print out your query so you can see what you're sending to the sql server. Also, you can get the SQL server's error message.
You add extra dots in the string.
Use
mysql_query("DELETE FROM `videos` WHERE `videos`.`id` ='$id'");
instead of
mysql_query("DELETE FROM `videos` WHERE `videos`.`id` ='.$id.'");
Also check how do you get the value of $id.
Thanks everyone. I used Pascal MARTIN's answer, and it comes to show that I was missing the request ($_GET) to get the 'id' from the precious page, and that some of my query was incorrect.
Here is the working copy:
<?php
include ("login.php");
$id = $_GET['id'];
mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
mysql_select_db ($dbname)
or die("Unable to connect to database");
mysql_query("DELETE FROM `videos` WHERE `videos`.`id` = $id ");
echo ("Video ".$id." has been deleted.");
?>
Thanks again!

Categories