Is there a prob with my MySQLi/PHP code? - php

I am new to all this MySQLi, and I can't seem to find any useful information that works for me.. I've tried the following code, but to no avail:
if(isset($_GET['submit']))
{
$stamp = date("D M d, Y G:i a");
$mysqli->query("INSERT INTO down (timestamp, username) VALUES ('" . $stamp . "', '" . USER_NAME . "')");
}
I am unaware as to what I'm doing wrong, so maybe some insight? Or it would be great if someone could reference me to some websites? Hence nothing seems to work for me!
HTML is:
<form method="post">
<b>Submit a downtime report*</b>: <input type="submit" name="submit" value="Report">
</form>

You don't have to use date() function in PHP. You can use NOW() or CURRENT_TIMESTAMP() in MySQL
$mysqli->query("INSERT INTO down (`timestamp`, `username`) VALUES (NOW(), '" . USER_NAME . "')");
More date functions you can find here
I guess USER_NAME is a constant and it's set.

As for useful resources, have you tried the official documentation ?
http://php.net/manual/en/book.mysqli.php
It seems to be pretty comprehensive.

Change this to
$mysqli->query("INSERT INTO down (timestamp, username) VALUES ('" . $stamp . "', '" . USER_NAME . "')");
to
$mysqli->query("INSERT INTO down (`timestamp`, `username`) VALUES ('" . $stamp . "', '" . USER_NAME . "')");
Reason: timestamp is also a type in SQL hence you should use it like that.

"timestamp" is a MySQL keyword and so is interpreted as a data type rather than a column name and then the syntax doesn't make any sense. You can solve this by escaping the column name using back ticks. This is a good practice for all table and column names by the way, regardless of whether they are keywords or not. So changing the query as follows should work:
$mysqli->query("INSERT INTO `down` (`timestamp`, `username`) VALUES ('" . $stamp . "', '" . USER_NAME . "')");

Related

Can't insert now() in PHP

I am a beginner programmer trying to insert the the now() value into my field date. I have achieved this before and copied the structure word by word but still does not work. I have also viewed other stackoverflow questions and I think that my database structure is correct. Here is INSERT php code:
try{
$conn = new mysqli("xxxxx", "xxxxx", "xxxxxxxx", "xxxxxxx");
$userid = $_GET['userid'];
$title = $_GET['title'];
$comment = $_GET['comment'];
$query = "INSERT into enquiries (userid, title, comment, Resolved, date)
values ('" . addslashes($userid) . "','" . addslashes($title) . "','" . addslashes($comment) . "', N, now() )";
$result = $conn->query($query);
if (!$result){
$json_out = "[" . json_encode(array("result"=>0)) . "]";
}
else {
$json_out = "[" . json_encode(array("result"=>1)) . "]";
}
echo $json_out;
$conn->close();
}
This set of codes worked and inserted values before I added now()
Here is my table structure:
Here is my other table structure that inserted now() just fine:
Your "Resolved" value needs to be in quotes, because you have it defined as a varchar. This would be the case for any of the "char" family of datatypes.
$query = "INSERT into enquiries (userid, title, comment, Resolved, date)
values ('" . addslashes($userid) . "','" . addslashes($title) . "','" . addslashes($comment) . "', 'N', now() )";
Hope this helps!
Sometimes database has some restrictions.. So try using like this NOW() than now() or else use CURDATE().

PHP inserting the type datetime into sql

I have made a sql row as type: datetime.
The input for datetime should be like: 2013-02-02 10:13:20
You get the drill like: 0000-00-00 00:00:00
Now In php I use date("Y-m-d H:i:s");(current date and time) to insert it into my database. There are other variables as well. Those variables get inserted,but the datetime row stays: 0000-00-00 00:00:00
I first got this code when everything except the date worked:
$resultaat = $mysqli2->query("INSERT INTO questions (title, description, username, date_made) VALUES ('" . $title . "','" . $description . "', '".$username ."','".date("Y-m-d H:i:s")."')");
but all the information in the databases will get "" around them.(Which could have caused the date to jump to 0000-00-00 00:00:00
Now when I try to insert again with other information, it wont even insert anymore. My problems:
What is the real problem for the date to set to 0000-00-00 00:00:00? Is it the automatic ""?
If it is the "", how can I lose them?
EDIT:
Nvm I lost the "" It wasn't the problem that cause the insert to fail at the second try.
- Why wont it insert in it anymore after I inserted once?
Now these aren't really different questions because it's about the same problem but here's my code and yes I know SQL Injection, I'll fix it later:
if (isset($_POST['title'])) {
$alles_goed=true;
$description=$_POST['description'];
$title=$_POST['title'];
$username=$_SESSION['username'];
if ($title=''){
$alles_goed=false;
echo'title is empty';
}
if($alles_goed==true){
$resultaat = $mysqli2->query("INSERT INTO questions (title, description, username, date_made) VALUES ('" . $title . "','" . $description . "', '".$username ."','".date("Y-m-d H:i:s")."')");
}
}
Try this:
$a=date("Y-m-d H:i:s");
if (!$resultaat = $mysqli2->query("INSERT INTO questions (title, description, username, date_made) VALUES ('$title','$description','$username','$a')"))
{
printf("Errormessage: %s\n", $mysqli2->error);
exit;
}
and check if there is any error produced.
As to why is inserting it only once, you might have unique field.
Just use a now() on MySQL
$resultaat = $mysqli2->query("INSERT INTO questions (title, description, username, date_made) VALUES ('" . $title . "','" . $description . "', '".$username ."',now()");

Escaping SQL queries in Codeigniter

I am inserting some data into a MySQL table using CodeIgniter. Because I am using INSERT IGNORE INTO and do not want to edit the active records class to enable this feature, I am generating the SQL query manually.
$this->db->query("INSERT IGNORE INTO my_table(lat, lng, date, type)
VALUES ('" . $data['lat'] . "', '" . $data['lng'] . "', '" . $data['date'] . "', '" . $data['type'] . "')");
Problem: The query failed when the string in $data['type'] contained a single quote. How can I make it such that these characters that need to be escaped gets escaped automatically, like when using Active records?
Another way is to use Query Binding which automatically escapes all the values:
$sql = "INSERT IGNORE INTO my_table(lat, lng, date, type) VALUES (?,?,?,?);";
$this->db->query($sql, array($data['lat'], $data['lng'], $data['date'], $data['type']));
use $this->db->escape(); it will escape the string automatically
This function determines the data type so that it can escape only
string data. It also automatically adds single quotes around the data
so you don't have to:
$this->db->query("INSERT IGNORE INTO my_table(lat, lng, date, type)
VALUES ('" . $this->db->escape($data['lat']) . "', '" . $this->db->escape($data['lng']) . "', '" . $this->db->escape($data['date']$this->db->escape . "', '" . $this->db->escape($data['type']) . "')");
Here is the reference Click Here

PHP / MYSQL Date will not insert

I am trying to insert a date from a variable into a mysql database. The format of the column is date and it has dates in the column. The dates in the column look like yyyy-mm-dd
my date variable also looks like this however it will not insert the date into the column and even i do not get an error just a white screen.
<?php
//here is the code to insert this does not work
mysql_query("INSERT INTO `invoices` (account_id, purchased_date, sales_rep, INV_ID)
VALUES ('".$acctid."', '".$date"','".$row['8']."', '".$invid."' )") or die("load1 -" . mysql_error());
<?php
//this does work but it does not have the date.
mysql_query("INSERT INTO `invoices` (account_id, sales_rep, INV_ID)
VALUES ('".$acctid."', '".$row['8']."', '".$invid."')") or die("load1 -" . mysql_error());
not sure what the problem is. I have displayed the $date variable onto the screen and it looks fine ex. 2012-06-01
so I am not sure why it can not insert this into the database.
Your error is that you have a parse error in this line:
VALUES ('".$acctid."', '".$date"','".$row['8']."', '".$invid."' )")
Your server has display_errors turned off, so you're not seeing the fatal error output.
You can fix it by adding a concatenation operator (.) like so:
VALUES ('".$acctid."', '".$date."','".$row['8']."', '".$invid."' )")
Also, in the future, I find it more readable to write my queries like so:
VALUES ('{$acctid}', '{$date}', '{$row['8']}', '{$invid}')
If you prefer not to use interpolation (that's the method of string "injection" used above), you could still use concatenation (your original method) but use spaces to make it more readable (and easier to find syntax errors before you try to execute it):
"VALUES ('" . $acctid . "', '" . $date . "' , '" . $row['8'] . "', '" . $invid . "')";
And before all the haters shun me for suggesting interpolation over concatenation, let me refer you to this tweet by #rasmus stating that interpolation is actually faster than concatenation, these days.
<?php
//here is the code to insert this does not work
mysql_query("INSERT INTO `invoices` (account_id, purchased_date, sales_rep, INV_ID) VALUES ('".$acctid."', '".$date"','".$row['8']."', '".$invid."' )") or die("load1 -" . mysql_error());
?>
the error is:
PHP Parse error: syntax error, unexpected T_CONSTANT_ENCAPSED_STRING on line 1
There is no . after $date.
Try to use new \DateTime('yyyy-mm-dd')
<?php
//here is the code to insert this does not work
mysql_query("INSERT INTO `invoices` (account_id, purchased_date, sales_rep, INV_ID)
VALUES ('".$acctid."', '".new \DateTime('yyyy-mm-dd')."','".$row['8']."', '".$invid."' )") or die("load1 -" . mysql_error());
You can use
mysql_query("INSERT INTO `vipanda2`.`invoices` (account_id, purchased_date, sales_rep, INV_ID)
VALUES ('".$acctid."', '".date('Y-m-d',mktime(0, 0, 0, date("m", $date), date("d", $date), date("Y", $date)))."','".$row['8']."', '".$invid."' )") or die("load1 -" . mysql_error());

What's the best way to insert multiple rows into a mysql database using php?

The php code below get's the results from a form and inserts them into a table.
I have to used this table structure where each row corresponds to a different value from the form eg First Name.
I've written the code below but it's cumbersome.
Can you help me with a better way? Thanks heaps!
$lists = $_POST['form']['lists'][0];
$first_name = $_POST['form']['first_name'];
$last_name = $_POST['form']['last_name'];
$idu = $db->insertid();
$db->setQuery("INSERT INTO #__rsmail_subscriber_details (`IdList`, `FieldName`,
`FieldValue`, `IdSubscriber`) VALUES ('" . $db->getEscaped($lists) . "', 'First Name'
, '" . $db->getEscaped($first_name) . "', '" . $db->getEscaped($idu) . "')");
$db->query();
$db->setQuery("INSERT INTO #__rsmail_subscriber_details (`IdList`, `FieldName`,
`FieldValue`, `IdSubscriber`) VALUES ('" . $db->getEscaped($lists) . "', 'Last Name'
, '" . $db->getEscaped($last_name) . "', '" . $db->getEscaped($idu) . "')");
$db->query();
You can perform bulk insert:
INSERT INTO table (field1, field2) VALUES ('val1', 'val2'), ('val3', 'val4'), ...
In your case it is something like:
$db->setQuery("INSERT INTO #__rsmail_subscriber_details (`IdList`, `FieldName`,
`FieldValue`, `IdSubscriber`) VALUES ('".$db->getEscaped($lists)."', 'First Name'
, '".$db->getEscaped($first_name)."', '".$db->getEscaped($idu)."'), ('".$db->getEscaped($lists)."', 'Last Name'
, '".$db->getEscaped($last_name)."', '".$db->getEscaped($idu)."')");
To answer your SQL question:
INSERT INTO `table` (foo, bar)
VALUES (1, 2),
(3, 4),
(5, 6),
(7, 8)
In regards to your PHP code, burn it and start over. It reeks of security issues and bad practices.

Categories