Any reason why this MySQL query wouldn't run? - php

I have the following PHP script setup to run as a cron job every minute:
<?php
$con = mysql_connect("localhost", "user", "pass");
if (!$con) {
die("Database error");
}
mysql_query("TRUNCATE TABLE contact_ips");
mysql_close($con);
die();
?>
This script is to prevent a contact form being submitted from the same IP address more than once within 1 minute. Therefore, it should clear the contents of the table that submitted the form and it is not doing that.
Could it be my cron command that is working correctly?
Thanks

First of all, mysql_query is deprecated. Use mysqli instead.
Second, it seems like you might want to set a variable to the query, eg $result = mysqli_query() so you can do post-processing.
Have you tried adding a die() to the mysql query to check that that query is running?
Also, it seems like you haven't selected a DB. Add this after the connection code. mysql_select_db("databaseName", $con);

It should be
<?php
$con = mysql_connect("localhost", "user", "pass");
if (!$con) {
die("Database error");
}
mysql_select_db("database", $con);
mysql_query("TRUNCATE TABLE contact_ips");
mysql_close($con);
die();
?>

Related

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'

My php script is not using given username/pass/host rather using root#localhost (password: NO)

Got a problem! Though I found almost similar threads but none helped :(
I've written a php script to fetch the number of registered users from my MySQL database. The script is working great in my localhost; it is using the given username,pass and host name which are "root", "root", and "localhost" respectively, but the script is not using the given username/pass/host rather using root#localhost (password: NO) in Live server.
In the Live server I created a MySQL user, set an different password, and hostname there is of course not localhost. I updated the script with my newly created mysql users data. BUT, whenever I run the script, I see that the script is still using "root", "root", and "localhost"!!
take a look at the script:
//database connection
$conn = mysql_connect( "mysql.examplehost.com", "myusername", "mypass" );
$db = mysql_select_db ("regdb",$conn); //Oops, actually it was written this way in the script. I misstyped it previously. now edited as it is in the script.
//Query to fetch data
$query = mysql_query("SELECT * FROM regd ");
while ($row = mysql_fetch_array($query)):
$total_regd = $row['total_regd'];
endwhile;
echo $total_regd;
-- Some says to change the default username and pass in the config.ini.php file located in phpMyAdmin directory. Would this help?? I didn't try this because either my hosting provider didn't give me privilege to access that directory (because I am using free hosting for testing scripts) or I simply didn't find it :(
Please help....
Foreword: The MySQL extension is marked as deprecated, better use mysqli or PDO
Though you store the connection resource in $conn you're not using it in your call to mysql_query() and you're not checking the return value of mysql_connect(), i.e. if the connection fails for some reason mysql_query() "is free" to establish a new default connection.
<?php
//database connection
$conn = mysql_connect( "mysql.examplehost.com", "myusername", "mypass" );
if ( !$conn ) {
die(mysql_error()); // or a more sophisticated error handling....
}
$db = mysql_select_db ("regdb", $conn);
if ( !$db ) {
die(mysql_error($conn)); // or a more sophisticated error handling....
}
//Query to fetch data
$query = mysql_query("SELECT * FROM regd ", $conn);
if (!$query) {
die(mysql_error($conn)); // or a more sophisticated error handling....
}
while ( false!=($row=mysql_fetch_array($query)) ):
$total_regd = $row['total_regd'];
endwhile;
echo $total_regd;
edit: It looks like you're processing only one row.
Either move the echo line into the while-loop or (if you really only want one record) better say so in the sql statement and get rid of the loop, e.g.
// Query to fetch data
// make it "easier" for the MySQL server by limiting the result set to one record
$query = mysql_query("SELECT * FROM regd LIMIT 1", $conn);
if (!$query) {
die(mysql_error($conn)); // or a more sophisticated error handling....
}
// fetch data and output
$row=mysql_fetch_array($query);
if ( !$row ) {
echo 'no record found';
}
else {
echo htmlspecialchars($row['total_regd']);
}
First of all:
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Not connected : ' . mysql_error());
}
// make foo the current db
$db_selected = mysql_select_db('foo', $link);
if (!$db_selected) {
die ('Can\'t use foo : ' . mysql_error());
}
What is your mysql_error()? :)

Logging $_SERVER to mysql

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.

php, mysql server has gone away

What is wrong, when you connect to the DB on the LINE BEFORE THE QUERY, and you still get "MySQL server has gone away"?
check this example code:
mysql_connect("localhost", "xxx", "xxx") or die(mysql_error());
mysql_select_db("xxx") or die(mysql_error());
$sql = mysql_query("SELECT id FROM db");
while ($data = mysql_fetch_assoc($sql)) {
$ids[] = $data[id];
}
foreach ($ids as $id) {
$content = file_get_contents("http://www.id.com/?id=$id");
if (stristr($content, "the id is ok man")) {
mysql_connect("localhost", "xxx", "xxx") or die(mysql_error());
mysql_select_db("xxx") or die(mysql_error());
mysql_query("UPDATE db SET status = 'OK' WHERE id = '$id'");
}
}
mysql server is gone away, i get that in the foreach loop.
BTW i need to connect in the foreachloop, because it may take along time before it finds something to update (like 1-2 minutes), and then for sure i will get mysql server has gone away.
I assume your issue is that the script may execute for a very long time before sending the first UPDATE query.
You should check the wait_timeout value in my.cnf. You can check your wait_timeout by running the query "SHOW VARIABLES;"
You can also try to piece of code to do a reconnect:
if (!mysql_ping ($conn)) {
//here is the major trick, you have to close the connection (even though its not currently working) for it to recreate properly.
mysql_close($conn);
$conn = mysql_connect('localhost','user','pass');
mysql_select_db('db',$conn);
}
Combining with your code it would be:
mysql_connect("localhost", "xxx", "xxx") or die(mysql_error());
mysql_select_db("xxx") or die(mysql_error());
$sql = mysql_query("SELECT id FROM db");
while ($data = mysql_fetch_assoc($sql)) {
if (!mysql_ping ()) {
//here is the major trick, you have to close the connection (even though its not currently working) for it to recreate properly.
mysql_close();
mysql_connect("localhost", "xxx", "xxx") or die(mysql_error());
mysql_select_db("xxx") or die(mysql_error());
}
$ids[] = $data['id'];
$content = file_get_contents("http://www.id.com/?id=$id");
if (stristr($content, "the id is ok man")) {
mysql_query("UPDATE db SET status = 'OK' WHERE id = '$id'");
}
}
We got that error this week at work here is the official documentation from MySQL : http://dev.mysql.com/doc/refman/5.0/en/gone-away.html
This section also covers the related Lost connection to server during query error.
The most common reason for the MySQL server has gone away error is that the server timed out and closed the connection.

PHP Data Base Connection help with mysql

i am new in php and want to know the code for php mysql database connection code
Refer to the PHP documentation for mysql_connect.
<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($link);
Here is the bare bone of it:
$db1 = mysql_connect( ... );
mysql_select_db('existing_db',$db1);
$db2 = mysql_connect( ... );
mysql_select_db('not_existing_db', $db2);
mysql_query(... , $db2);
More Info:
http://php.net/manual/en/function.mysql-connect.php
MySQL PHP Connect Tutorial
A Detailed Tutorial:
http://www.phpf1.com/tutorial/php-mysql-tutorial.html?page=1
<?php
mysql_connect("localhost", "username", "password") or die(mysql_error());
echo "Connection to the server was successful!<br/>";
mysql_select_db("test") or die(mysql_error());
echo "Database was selected!<br/>";
?>
Watch also mysqli,it's the "new way" of connecting to mysql
http://php.net/manual/en/book.mysqli.php
it has more functions and there are rumors that in php6 mysql will be deprecated for the mysqli implementation.
you can use it as an object(but if you're new also to OO it may be a little more difficult to understand)like this:
//--connection to the database--
$db=mysqli_connect('sql.mysqlhost.com','database_username','password','database_name');//you can also use $db=new mysqli(....) but mysql_connect does the same thing and it's more cler on what it's doing
//--a simple query--
if($result=$db::query('SELECT name,value FROM mytable')){//query ok
echo 'Select returned ',$result->num_rows,'rows<br/>';
while($row=$result->fetch_assoc()){//get one row in an assoc.array
echo 'Name:',$row['name'],' Value:',$row['value'],'<br/>';//print each row
}
$result->close();
}
else//query error
die('MYSQL ERROR:'.$db->error);
or with functions like in mysql
//--connection to the database--
$db=mysqli_connect('sql.mysqlhost.com','database_username','password','database_name');
//--a simple query--
if($result=mysql_query($db,'SELECT name,value FROM mytable')){//query ok
echo 'Select returned ',mysql_num_rows($result),'rows<br/>';
while($row=mysqli_fetch_assoc($result)){//get one row in an assoc.array
echo 'Name:',$row['name'],' Value:',$row['value'],'<br/>';//print each row
}
mysql_free_result($result);
}
else//query error
die('MYSQL ERROR:'.mysqli_connect_error());
You can also use a persistent mysql connection prepending 'p:' to the sql host,for example if your host is sql.myhost.com:
$db=mysqli_connect('p:sql.mysqlhost.com','database_username','password','database_name');
Using a persistent connection should give you a great performance boost and mysqli should handle the persistent connection a lot better than the normal mysql extension.
Remember to sanitize the input of your query to avoid SQL INJECTION,you can do like this:
$result=mysql_query($db,"SELECT name,value FROM mytable where name='".mysqli_real_escape_string($input_name)."'");
or using a prepared statement that's a little more complicated and it's better only if you repeat the same command multiple times only changing the input data.

Categories