Current Time Stamp - php

I have read many of the postings regarding current time stamp and tried many of the solutions provided, however none of them fixed my issue. I need a current time stamp to be added to the database. I think my code may be the reason why the other solutions are not working. Everything else post perfectly. The time stamp just gives me all "0", the other solutions I tried gave me a "line 6 error".
Here is my current code
<?php
$con = mysql_connect("mysql","username","password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
/* Prevent duplicate submissions */
if (isset($_COOKIE['FormSubmitted']))
{
show_error('You may only submit this form once per session!');
}
mysql_select_db("seller", $con);
$sql="INSERT INTO listing (name, email, website, url, dropdown, price, date, visitors, income, host, description)
VALUES
('$_POST[name]', '$_POST[email]', '$_POST[website]', '$_POST[url]', '$_POST [dropdown]', '$_POST[price]', '$_POST[date]','$_POST[visitors]', '$_POST[income]', '$_POST[host]', '$_POST[description]', 'CURRENT_TIMESTAMP[subdate]' )";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "Thank you for listing with us. Explore Now";
mysql_close($con)
?>

Using CURRENT_TIMESTAMP in the PHP context has no sense!
You have to include the needed default value in your table definition.
Something like this:
CREATE TABLE listing
...
description VARCHAR(...)
creation_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP
...
Then in PHP you should only write:
$sql="
INSERT INTO listing (name, ..., description)
VALUES ('$_POST[name]', ..., '$_POST[description]')
";

Related

allow duplicate entries for all posts in php

How do i allow duplicate entries in my php file from this file ... i have the html file which is a form to track radios for a company. I have text boxes and radio buttons and all the fields need to be able to have duplicate entries except for the serial number field. i keep getting and error saying i cannot have duplicate entries.
<?php
$con = mysql_connect("localhost","Jason","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("test", $con);
$sql="INSERT INTO test (
firstname,
lastname,
department,
radiomodel,
serialnumber,
issuedate
)
VALUES(
'$_POST[firstname]',
'$_POST[lastname]',
'$_POST[department]',
'$_POST[radiomodel]',
'$_POST[serialnumber]',
'$_POST[issuedate]'
)";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con);
header( "refresh:150;url=testinput.php" );
?>
Your serialnumber is a primary key and thus you can not have duplicate values.
You should remove the primary key from the serialnumber field and add in a new id column to put the primary key on this or use multiple columns together as the key, for example use firstname, lastname and date and serialnumber as the key.
Really you should split this off into multiple tables though.

Can not send information from PHP form to multiple mysql database tables

I am trying to insert data into 4 tables ( asset, asset_details, invoice and location). When I submit the form, it tells me that all the data has been submitted successfully but when I check the MySQL database the information is only submitted to the location tables.
Any help will be appreciated, Thank you .
mysql_query("START TRANSITION");
$query1 =("INSERT INTO .asset (asset_tag, asset_number, cap_ex, asset_type_id, invoice_id, status)
Values(".$_POST['asset_tag'] .",,,".$_POST['asset_type'] . ",".$_POST['invoice_number']."," . $_POST['status_id'] .")");
$query2 =("INSERT INTO .asset_details (asset_type_id, asset_tag, asset_type, physical_asset_id, manufacturer, os, os_version, make, model, serial_number, processor, ram, memory, hdd, host_name, notes)
Values(" .",".$_POST['asset_tag']."," .$_POST['asset_type'].",,
,".$_POST['os'].",".$_POST['os_version'].",".$_POST['make'].",".$_POST['model'].",".$_POST['serial_number'].",".$_POST['processor'].",,".$_POST['memory'].",".$_POST['hdd'].",,".$_POST['notes'].")");
$query3 =( "INSERT INTO .invoice (invoice_number, invoice_date, purchas_price, quantity, order_date, vender, warrenty_end, notes)
Values(" .$_POST['invoice_number'].",". $_POST['invoice_date'].",". $_POST['purchase_price'].",,,". $_POST['vender'].")");
$query4 =( "INSERT INTO .location (location_name, rack, row, unit)
Values(" .$_POST['location_name'].",".$_POST['rack'].",".$_POST['row'].",".$_POST['unit'].")");
echo "$query1 $query2 $query3 $query4";
$result1= mysql_query($query1);
$result2= mysql_query($query2);
$result3= mysql_query($query3);
$result4= mysql_query($query4);
$result = mysql_query("COMMIT");
if (!$result)
{
mysql_query("ROLLBACK");
die('Invalid query: ' . mysql_error());
}
else
{
echo "<script>alert('SUCCESS!');</script>";
}
}
mysql_close($con);
?>
There are some strange things;
START TRANSITION should probably be START TRANSACTION.
You're not quoting any of your string values. Strings need to be quoted using ' a'la INSERT INTO TEST VALUES ('olle');
An empty field cannot be indicated by just skipping it, you're doing INSERT INTO TEST (a,b,c) VALUES (1,,2); which is not valid syntax for not setting b.
Also, I recommend using a more modern mysql api than mysql_query, as for example PDO or mysqli, since injecting POST values into a string as you do can be pretty dangerous, you may cause SQL injection problems.
Use '`'s around each attributes(columns) and ''' around each values, it should work
During development, I'd echo each query-expressions before it is sent to the database..
...by the way, mysql_error() is a useful function in php, which returns the last error information of mysql....U may use that for debugging

How to Obtain Users ID and Put it in a Table

I'm trying to make a football betting system based on the WordPress CMS. I apologize if this is a redundant question, but I've been searching through Google and a few Wiki's all day, and I haven't been able to find any clue to how this question is answered.
BACKGROUND INFORMATION:
I use:
MySQL
PHP
Navicat
Every time the user inputs two integers, corresponding to the goalscorings in a football match, on the php-scripted website, the two integers get sent off to the database table "bets", through an insert.php-file.
The insert.php looks like this:
<?php $con = mysql_connect("host","username","password"); if (!$con) { die('Could not connect: ' . mysql_error()); }
mysql_select_db("database", $con);
$sql="INSERT INTO bets (homebet, awaybet) VALUES ('$_POST[homebet]','$_POST[awaybet]')";
if (!mysql_query($sql,$con)) { die('Error: ' . mysql_error()); } echo "Thanks for betting!";
mysql_close($con); ?>
The php-form looks like this:
I have the following self-made tables: bets, teams, matches, and I have the WordPress table, wp-users, where each member is listed.
The bets table looks like this:
As you can see, the userid is empty - which it shouldn't be. It should contain the ID of the user, who entered the bet.
My two-part question is then..
How should I obtain the ID of the user and display it in the database table, bets? Perhaps WordPress have a code-snippet for it.
And finally, how should I attach a gameid to each match? Should I create a new form for each new match?
Thanks SO much in advance - I hope I was able to make this thread readable and easy to understand.
Frederick Andersen
You're missing quite some things here. I can't advise you how to manage the different games since I don't know what the rest of your application looks like.
Here are some pointers to get you going:
Don't create your own DB connection
Remove:
$con = mysql_connect("host","username","password"); if (!$con) { die('Could not connect: ' . mysql_error()); }
mysql_select_db("database", $con);
Add instead:
require_once($_SERVER['DOCUMENT_ROOT'].'/wp-load.php');
WordPress current user ID
Add this to top off script:
global $wpdb, $current_user;
get_currentuserinfo();
Change $sql code to this:
$sql= $wpdb->prepare("INSERT INTO `bets` (`userid`, `homebet`, `awaybet`) VALUES (%d, %d, %d)", $current_user->ID, $_POST['homebet'], $_POST['awaybet']);
I've also used the wpdb prepare function so your post data will be escaped before getting queried.
Also change this to use WP native querying.
Remove:
if (!mysql_query($sql,$con)) { die('Error: ' . mysql_error()); } echo "Thanks for betting!";
mysql_close($con);
Add instead:
$wpdb->query($sql)

Prevent multiple data entries in MySQL

So here is the deal. I have looked around everywhere, and all other techniques relate to refreshing the browser, and methods to prevent the php page from resubmitting the post data. I am new to this (obviously :p) But anyways, my questions I believe is simple. I just want a method, possibly an if else statement that would check the post data entries, and if there is a match already in my table, than do not execute the query. I am not worried about querying all of the results of the table, as I only suspect this table will ever have 50-60 entries.
Here is the php page that handles the form submission:
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$email = $_POST['email'];
$city = $_POST['city'];
$state = $_POST['state'];
$submitDate = date("Y-m-d");
mysql_connect ("localhost", "abc", "123") or die ('Error: ' . mysql_error());
mysql_select_db ("members");
$query = "INSERT INTO persons (ID, firstName, lastName, email, city, state, submitDate)VALUES (
'NULL',
'".$firstName."',
'".$lastName."',
'".$email."',
'".$city."',
'".$state."',
'".$submitDate."'
)";
mysql_query($query) or die ('Error Updating database');
echo "Database Updated With: " .$firstName ." " .$lastName ." " .$email ." " .$city ." " .$state;
mysql_close($con);
Sorry, cant ever seem to get my php to format correctly with those code braces. Anyways. just to re-iterate, looking for a way to maybe based on the first and last name. if those already exist, then do not allow the submission of the data. I have tried a few if then statements but i do not think I am getting the concept down of comparing the result to my query. I hope this all makes sense!!!
I would suggest adding a UNIQUE index on the columns you want to have unique.
You can just use INSERT IGNORE INTO ... and let MySQL handle it.
$query = "INSERT IGNORE INTO persons (ID, firstName, lastName, email, city, state, submitDate) VALUES (
'NULL',
'".$firstName."',
'".$lastName."',
'".$email."',
'".$city."',
'".$state."',
'".$submitDate."'
)";
Is your problem only that refreshing the page resends the POST data? The pretty much standard way to prevent that is to redirect the browser after having processed the form data, like so:
header('Location: ' . $_SERVER['PHP_SELF']);
Keep in mind, changing headers has to be done before any output is sent to the browser, so this should be above your doctype, and be sure there is no white space before either.
One way of doing this is to make sure your table has appropriate primary keys set (firstname and lastname at least), and then just trying the insert and seeing whether it fails on duplicate. You can check the error message using the mysql_error() function for this purpose.
You can do a select on the database with those two fields to check if a row already exists, but if this is something that needs to be unique there should also be a unique index on those two columns in your MySQL table.
I had this issue as well. Basically what I did is before the insert, do a select on the criteria that would qualify as a duplicate and check for it to return; if it does not we are ok to enter.
$query = "SELECT COUNT(id) AS mycount FROM persons WHERE firstName = '".$firstnName."' AND lastName = '".$lastName."'";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
if($row['mycount'] == 0) {
//Do insert
}

Check if email address already exists if so show message if not then add to table

I was hoping to get a little insight on this.
What I have is a form collecting firstname, lastname, city, state, and email address. This form is using jquery validation plugin and the form plugin.
I would like to check if email already exists... if so then spit out a message that tells them they already exist.
This is what I have for my update.php script in which the form if using to add names to the mysql database:
<?php
$con = mysql_connect("host","username","password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("table", $con);
$sql="INSERT INTO wallnames (ID, firstname, lastname, city, state, email)
VALUES('NULL','$_POST[firstname]','$_POST[lastname]','$_POST[city]','$_POST[state]','$_POST[email]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "<p style=\width:350px; height:200px; vertical-align:middle;\><strong>Thank you for adding your info</strong></p>";
mysql_close($con);
?>
You should create a unique index on the email column, then the insert will fail if you try to insert the same email twice.
CREATE UNIQUE INDEX ux_wallnames_email ON wallnames (email)
You can also run this query to test if an email already exists:
SELECT EXISTS (SELECT NULL FROM wallnames WHERE email = 'test#example.com')
It will return either 0 if the email is unused, or 1 if it already exists in the table.

Categories