Why does Mozilla insert duplicate rows? php/sql - php

So, i got this code:
<?php
$servername = "localhost";
$username = "**";
$password = "**";
$dbname = "TestDB";
// Create connection
$conn = new mysqli($servername, $username, $password,$dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully<br>";
$ip = $_SERVER['REMOTE_ADDR'];
$sql = "INSERT INTO testdata (id,address,count) VALUES (DEFAULT,'$ip',1) ON DUPLICATE KEY UPDATE count=count+1";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully<br>";
} else {
echo "Error: " ;
}
$conn->close();
?>
With this code ip-addresses of customers are saved and it should increase count by 1 every time they return to the website. When i visit database.php directly it works like it should in every browser, but when i call the php-file via the index.html-page it counts up twice (most of the times, not always) in Mozilla, other browsers no problem, the code in html-file:
<img style="display: none;" src="http://servername/database.php?">
Anyone know why? Please help, i'm really stuck here

Related

Is my hosting company messing me up here: Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)?

I use the hosting company aPlus.net, and I can't seem to get past a connection error I'm getting when trying to process some php to write database content to a webpage, and I am curious as to if this is because my database appears to not be on the same server as the entire rest of my hosting account, and if there is a way to resolve this in my code? This is my first attempt at writing PHP, and it would be good to know if my code is wrong, or if my hosting company is messing me up. (and either way, how to fix it)
Here's the code that's failing to pull from the database:
{
$con = mysql_connect("localhost","2p5dq9vxmy240651","MY_PASSWORD");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("felineasthma_2p5dq9vxmy240651", $con);
$users_name = $_POST['name'];
$users_comment = $_POST['requests'];
$users_name = mysql_real_escape_string($users_name);
$users_comment = mysql_real_escape_string($users_comment);
$inputid = $_GET['id'];
$query = "
INSERT INTO `felineasthma_2p5dq9vxmy240651`.`submissions` (`id`,
`name`, `requests`, `inputid`) VALUES (NULL,
'$users_name', '$users_comment', '$inputid');";
mysql_query($query);
echo "<h2>Your request has been processed, reload page.</h2>";
mysql_close($con);
}
and here's some screen captures from inside my hosting account (links because I don't have enough posts here yet to upload images, sorry):
felineasthma_2p5dq9vxmy240651 doesn't appear in my hosting account
yet it clearly exists in MySQL Manager, but on a different server
I was even more confused while making the user for this database, as the control panel didn't allow me to make a username, it just randomly assigned one. Help? Advice?
I found a more modern tutorial to learn PHP with, and now everything works, I just need to add security measures now. Here's the working code snippets, if anyone ever comes here asking the same questions.
here's the form action that places the entries into the database:
<?php
$servername = "sql5c40n.carrierzone.com";
$username = "my_username";
$password = "my_password";
$dbname = "my_database";
$users_name = $_POST['name'];
$users_request = $_POST['requests'];
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO submissions (name, requests)
VALUES ('$users_name', '$users_request')";
if (mysqli_query($conn, $sql)) {
header("Location: clv.php");
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
here's the include that puts the database entries onto the page:
<?php
$servername = "sql5c40n.carrierzone.com";
$username = "my_username";
$password = "my_password";
$dbname = "my_database";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT id, requests, name FROM submissions";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "" . $row["requests"]. " - by " . $row["name"]. "<br>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>

mySQL Fails When executed from PHP without Error Message

I'm trying to execute an SQL Statement but it fails without producing an error message. Please can you let me know what is going wrong?
I'm using the same database connection that I've used successfully in other pages for SELECT, and INSERT statements. I've tested the SQL statement successfully in phpMyAdmin. But when executed from php it fails without error message, all other statement in the site work fine.
Database connection include
<?php
$servername = "xxxxxx";
$username = "xxxxxx";
$password = "xxxxxx";
$dbname = "xxxxxx";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
// Connect to DB
include 'incDBConnection.php';
$SQL = "SELECT * from tbl_Properties";
echo "<br/> <br />";
if ($conn->query($SQL) === TRUE) {
echo "Record updated successfully";
} else {
echo "<br/> <br />Error updating record: " . $conn->error;
}

Create connect.php with require at .htx file

"add.htx"
<?php
$servername = "my_server_name";
$username = "my_username";
$password = "my_pwd";
$dbname = "my_db_name";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO Drama_Gr (Date, Time, Cont, Temp, Hum, Pres, Rain_Y, Rain_M, Rain, Rain_Rate, Wind, Wind_Dir)
VALUES ('<!--date-->', '<!--time-->', '<!--ForecastStr--> frc', '<!--outsideTemp-->', '<!--outsideHumidity-->', '<!--barometer-->', '<!--totalRain-->', '<!--monthlyRain-->', '<!--dailyRain-->', '<!--rainRate-->', '<!--windSpeed-->', '<!--windDirection-->bfr')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
run this file with weatherlink
and output the result file
"add.php"
<?php
$servername = "my_server_name";
$username = "my_username";
$password = "my_pwd";
$dbname = "my_db_name";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO Drama_Gr (Date, Time, Cont, Temp, Hum, Pres, Rain_Y, Rain_M, Rain, Rain_Rate, Wind, Wind_Dir)
VALUES ('17/08/16', ' 0:11', ' Increasing clouds with little temperature change. frc', '24.6', '52', '1012.6', '291.2', '11.2', '0.0', '0.0', '1.6', 'SSEbfr')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
its ok with this way i create a database with my weather station
the problem is i want to give this code to run with weather station and other people from my area and create in to my database tables from other weather station but i don't want to include this code my database connection.
i think the correct way is to create a file like
"connect.php"
<?php
$servername = "my_server_name";
$username = "my_username";
$password = "my_pwd";
$dbname = "my_db_name";
mysql_connect($hostname, $username, $password) OR DIE("Unable to connect to database! Please try again later.");
mysql_select_db($dbname);
?>
and call this file like
<?php include("connect.php");?>
i try to add this code in "add.htx"
but get bellow error in "add.php"
Connection failed: Access denied for user ''#'localhost' (using password: NO)
why? maybe i think because the file "add.htx" start from weatherlink by local C:\WeatherLink\ but the weatherlink upload this file and convert to "add.php" at server at folder like http://my_website/weather/ ,this folder also include and the file "connect.php"
please any help
and if is easy give me the correct code at "add.htx" with the wright way to add at "add.htx"
<?php include("connect.php");?>
thanks
Was this what you did?
<?php
Include('connect.php');
$servername = "my_server_name";
$username = "my_username";
$password = "my_pwd";
$dbname = "my_db_name";
......
?>
Php is not running your include('connect. Php') file.
Bt then, I think the problem is not with the code. I think the problem is with your privileges. Compare ur server username and password with the ones you defined in your script.
// Connection failed: Access denied for user ''#'localhost' (using password: NO)// pls do check ur privileges
for other people i give the solution
first thanks to Script47 (open my eyes and see mysql_* must change to mysqli_*)
second i create i think the better way to call
"config.php"
here the fresh change at code "add.htx"
<?php
include("config.php");
include("opendb.php");
$sql = "INSERT INTO Drama_Gr (Date, Time, Cont, Temp, Hum, Pres, Rain_Y, Rain_M, Rain, Rain_Rate, Wind, Wind_Dir)
VALUES ('<!--date-->', '<!--time-->', '<!--ForecastStr--> frc', '<!--outsideTemp-->', '<!--outsideHumidity-->', '<!--barometer-->', '<!--totalRain-->', '<!--monthlyRain-->', '<!--dailyRain-->', '<!--rainRate-->', '<!--windSpeed-->', '<!--windDirection-->bfr')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
include("closedb.php");
?>
i create 3 files
to connect with db and close the db
"config.php"
<?php
$servername = "my_host_name";
$username = "my_username";
$password = "my_pwd";
$dbname = "_my_database_name";
?>
after i create a script
"opendb.php"
<?php
// Create my Weather db connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check my Weather db connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
and i think is correct to create and script to close a connection when upload data to db ,name this script
"closedb.php"
<?php
// close my weather db connection
mysqli_close($conn);
?>
and finally the result to
"add.php"
New record created successfully
thanks and i hope this usefull and for others
now the last problem is with this code "add.php" the records update the db rows when refresh this page
i create a below script to auto refresh multiple files from weather stations in one page but must this page is open to auto update the new result to db and name this page
"send_db.html"
<html>
<head>
<!-- For ease i'm just using a JQuery version hosted by JQuery- you can download any version and link to it locally -->
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function() {
$("#responsecontainer").load("http://www.dramaweather.gr/weather2/uploadwl/mysql/add.php");
var refreshId = setInterval(function() {
$("#responsecontainer").load('http://www.dramaweather.gr/weather2/uploadwl/mysql/add.php?randval='+ Math.random());
}, 900000);
$.ajaxSetup({ cache: false });
});
</script>
<script>
$(document).ready(function() {
$("#responsecontainer").load("http://www.dramaweather.gr/weather2/uploadwl/mysql/add_Serres.php");
var refreshId = setInterval(function() {
$("#responsecontainer").load('http://www.dramaweather.gr/weather2/uploadwl/mysql/add_serres.php?randval='+ Math.random());
}, 900000);
$.ajaxSetup({ cache: false });
});
</script>
</head>
<body>
<div id="responsecontainer">
</div>
</body>
</html>
is any other way to send the results of "'add.htx" to db auto every 10 minutes without a code from "send_db.html"
;
thanks again for the first problem if anyone know and my for my second problem the solution please help

How do I display different images using MySQL/PHP when database connected/not connected?

I'm new to PHP and MYSQL, and I have what I think is going to be a relatively easy question.
My objective is to show one image (a green flashing light) when the database is connected, and display another image (a red flashing light) when there is no database connection.
I imagine it should be a simple variation on this:
<?php
$servername = "localhost";
$username = "root";
$password = "";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
But if I attempt to add an image to where it echos "Connected successfully" I receive an error.
I'm attempting to add the image like this:
<?php
$servername = "localhost";
$username = "root";
$password = "";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("<img src="Red_Light.gif" style="width:10px;height:10px;"> " . $conn->connect_error);
}
echo "<img src="Green_Light.gif" style="width:10px;height:10px;">";
?>
I probably have the completely wrong syntax but any help is appreciated.
Many thanks,
Leif
You can use Janno answer or you may use this (by changing " to ':-
if ($conn->connect_error) {
die("<img src='Red_Light.gif' style='width:10px;height:10px;'> " . $conn->connect_error);
}
echo "<img src='Green_Light.gif' style='width:10px;height:10px;'>";
if ($conn->connect_error) {
die("<img src=\"Red_Light.gif\" style=\"width:10px;height:10px;\"> " . $conn->connect_error);
}
echo "<img src=\"Green_Light.gif\" style=\"width:10px;height:10px;\">";
Whole problem seems to be related to not escaping the quote marks.

php store session variable in mysql database

I have a website in PHP. I try to store the session variable $_SESSION['user_name'] to a mysql database when a logged in user visits a specific webpage on my site.
<?php
$servername = "localhost";
$username = "user1";
$password = "user1";
$dbname = "payment";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = 'INSERT INTO users
VALUES ('.$_SESSION['user_name'].')';
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Error message:
Notice: Undefined variable: _SESSION in /opt/lampp/htdocs/succes.php on line 16
Tried a bunch of things but can't figure it out. What is wrong here?
You need to call session_start() at the beginning of your script (before using any $_SESSION variables). Also, you need quotes around the variable in you query:
$sql = 'INSERT INTO users
VALUES ("'.$_SESSION['user_name'].'")';
Please note that this is not safe; you are wide open to SQL injection. Instead, you should use prepared statements:
<?php
$servername = "localhost";
$username = "user1";
$password = "user1";
$dbname = "payment";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = 'INSERT INTO users
VALUES (?)';
$stmt = $conn->prepare($sql);
$stmt->bind_param('s', $_SESSION['user_name']);
if ($stmt->execute()) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Before you use any $_SESSION variables you need to call session_start().
Of topic a bit though, something to look into PDO. It can be a bit a tad slower than mysqli() however supports many more Database types. Here is a good article on Tuts+ explaining some of the differences as well as explaining essential security steps.
If I could be a bit biased I have created a PHP Class for PDO Connections which can be found on GitHub

Categories