I'm working on a Pastebin clone kind of a thing (from scratch, not literally cloning pastebin, just making an alternative) and I've ran into an issue inserting time into the database.
<?php
require 'connection.php';
$paste = $_POST['paste'];
$title = $_POST['title'];
//$sql = "INSERT INTO pasteinfo (title, paste) VALUES (:title, :paste)";
$stmt = $con->prepare("INSERT INTO pasteinfo (title, paste) VALUES (:title, :paste)");
echo "hi";
$stmt->bindParam(':paste', $paste);
$stmt->bindParam(':title', $title);
$stmt->execute();
echo "Pasted!";
$pastetime = new DateTime();
$timeQuery = $con->prepare("INSERT INTO pasteinfo (pastetime) VALUES (:pastetime)");
$time->bindParam(':pastetime', $pastetime);
$con->exec($timeQuery);
//$con = null;
?>
So that's insert.php. I'm hoping that when a user 'pastes' their paste it will record time, and then on my viewpaste.php it will display the title, paste, and time the paste was made.
What's wrong with it?
By the way, just ignore the little echo "hi"; thrown in there. It's helped me troubleshoot a lot and continues to do so.
connection.php source:
<?php
try {
$con = new PDO('mysql:host=;dbname=;charset=utf8mb4','','');
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$con->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
catch (PDOException $ex){
echo $ex->getMessage();return false;
}
function retrieve($query,$input) {
global $con;
$stmt = $con->prepare($query);
$stmt->execute($input);
$stmt->setFetchMode(PDO::FETCH_OBJ);
return $stmt;
}
#Drew:
<?php
require 'connection.php';
$paste = $_POST['paste'];
$title = $_POST['title'];
$timeQuery = "SELECT NOW()";
//$sql = "INSERT INTO pasteinfo (title, paste) VALUES (:title, :paste)";
$stmt = $con->prepare("INSERT INTO pasteinfo (title, paste, pastetime) VALUES (:title, :paste, :pastetime)");
echo "hi";
$stmt->bindParam(':paste', $paste);
$stmt->bindParam(':title', $title);
$stmt->bindParam(':pastetime', $timeQuery);
$stmt->execute();
echo "Pasted!";
//$timeQuery = $con->prepare("INSERT pasteinfo(pastetime) SELECT NOW()");
//$timeQuery->execute();
//$con = null;
?>
Schema and end-state after running script once:
Schema:
drop table if exists pasteinfo2;
CREATE TABLE pasteinfo2
( ai INT AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(200) NOT NULL,
paste TEXT NOT NULL,
pastetime DATETIME NOT NULL
);
PHP script:
<?php
// turn on error reporting, or wonder why nothing is happening at times
error_reporting(E_ALL);
ini_set("display_errors", 1);
// Begin Vault
// credentials from a secure Vault, not hard-coded (so the below is just for testing)
$servername="localhost";
$dbname="so_gibberish";
$username="nate";
$password="cannonBall##)x";
// End Vault
try {
$pdo = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$paste="Four score and seven years ago, our fore....";
$title="Gettysburg Address";
$stmt = $pdo->prepare("INSERT INTO pasteinfo2 (title, paste, pastetime) VALUES (:title, :paste, now())");
$stmt->bindParam(':paste', $paste);
$stmt->bindParam(':title', $title);
$stmt->execute();
echo "Yo I am here<br>";
} catch (PDOException $e) {
echo 'pdo problemo: ' . $e->getMessage(); // dev not production code
exit();
}
?>
Related
getting error for mysql when i am using if else in there. i dont know what should i do and when i am using duplicate condition to update then it not woring i am not be able to find where is error
this is the error which is i am getting.
ERROR:SQLSTATE[HY093]: Invalid parameter number: parameter was not
defined
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt=$conn->prepare("SELECT uniqueid FROM hotelcarttemp WHERE uniqueid=:uniqueid");
$stmt->execute(array(':uniqueid'=>$uniqueid));
$count=$stmt1->rowCount();
echo "count-".$count;
if($count>0)
{
$sql = "UPDATE hotelcarttemp SET `hotelname`='".$hotelname."',`roomtype`='".$roomtype."',`checkin`='".$checkin."',`checkout`='".$checkout."',`Country`='".$Country."',`Destination`='".$Destination."',`price`='".$price."' WHERE uniqueid='".$uniqueid."'";
echo "sql- ".print_r($sql);
$stmt = $conn->prepare($sql);
// echo print_r($stmt);
$stmt->execute();
}
else
{
$sql = "INSERT INTO hotelcarttemp (timestamp, packageid, uniqueid, hotelname, roomtype, checkin, checkout, Country, Destination, hoteldetail, price)
VALUES ('"
.$timestamp."','"
.$packageid."','"
.$uniqueid."','"
.$hotelname."','"
.$roomtype."','"
.$checkin."','"
.$checkout."','"
.$Country."','"
.$Destination."','"
.addslashes($hoteldetail)."','"
.$price."'
)";
// echo "sql- ".print_r($sql);
$stmt = $conn->prepare($sql);
// echo print_r($stmt);
$stmt->execute();
}
}
catch(PDOException $e) {
echo 'ERROR:' . $e->getMessage();
} here
Your SELECT query where condition is WHERE uniqueid=:uniqueid
And you are binding username to it
$stmt->execute(array(':username'=>$uniqueid));//:username invalid parameter
Change this to
$stmt->execute(array(':uniqueid'=>$uniqueid));
The first example will add data to mysql database without any issue. The second block of code - where I try to use variables wont. Can someone please explain where I am going wrong?
<?php
$query = "INSERT INTO subjects (menu_name,position,visible) VALUES ('Edit me',4,1)";
$result = mysqli_query($connection, $query);
Problem CODE:
<?php
$menu_name = "TEST";
$position = 5;
$visible = 1;
$query = "INSERT INTO subjects (menu_name,position,visible)
VALUES ('{menu_name}',{position}, {visible})";
$result = mysqli_query($connection, $query);
*Answer updated with MySQLi prepare statement, thanks #h2ooooooo
<?php
//Open a new connection to the MySQL server
$db = new mysqli('host','username','password','database_name');
//Output connection errors
if ($db->connect_error) {
die('Error : ('. $db->connect_errno .') '. $db->connect_error);
}
$sql = "INSERT INTO subjects (menu_name, position, visible) VALUES (?, ?, ?)";
if (!$stmt = $db->prepare($sql)) {
echo 'Database prepare error';
exit;
}
$stmt->bind_param('sss', $menu_name, $position, $visible);
if (!$stmt->execute()) {
echo 'Database execute error';
exit;
}
$stmt->close();
I'd say for you to take a look in the many tutorials thorugh net, like these:
http://markonphp.com/simple-insert-mysqli/ and
http://www.sanwebe.com/2013/03/basic-php-mysqli-usage
$query = "INSERT INTO subjects (menu_name,position,visible) VALUES
('".$menu_name."','".$position."', '".$visible."')";
try this
I looked all over for solutions but couldn't find any. I checked my code and can't seem to find any errors with it.
try
{
$handle = new PDO("mysql:dbname=" . DATABASE . ";host=" . SERVER, USERNAME, PASSWORD);
$handle->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$handle->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
catch (Exception $e)
{
trigger_error($e->getMessage(), E_USER_ERROR);
exit;
}
$sendData = $handle->prepare("INSERT INTO 'posts' (body, user, comments, likes, username, datetime) VALUES(:body, :userid, 'none', 'none', :username, :datetime)");
$sendData->bindParam(':body',$this->body);
$sendData->bindParam(':userid',$this->userID);
$sendData->bindParam(':username',$this->username);
$sendData->bindParam(':datetime',$this->datetime);
$sendData->execute();
I determined that the code stops before it even reaches the "bindParam" part. It stops right after the prepare call.
EDIT: As it turns out the error was in the $handle part. I declared handle elsewhere and didn't use "global" to add it inside this function. I feel so stupid.
Try:
try {
$db = new PDO('mysql:host=localhost;dbname=DATEBASE;charset=utf8', 'USER', 'PASSWORD');
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, FALSE);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $ex) {
echo "something";
die();
}
$body = $_POST['body'];
$userID = $_POST['userID'];
$username = $_POST['username'];
$datetime = $_POST['datetime'];
$none = "none";
$sendData = $sb->prepare("INSERT INTO `posts` (body, user, comments, likes, username, datetime) VALUES(:body, :userid, :none, :none, :username, :datetime)");
$sendData->bindValue(':body', $body);
$sendData->bindValue(':none', $none);
$sendData->bindValue(':userid', $userID);
$sendData->bindValue(':username', $username);
$sendData->bidnValue(':datetime', $datetime);
$sendData->execute();
Edited:
`posts` instead 'posts'
I have the following PHP code:
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
$insert_query = mysql_query("INSERT INTO articles(articleTitle, articleContent, typeID)
VALUES
('$_POST[articleTitle]','$_POST[articleContent]',$_POST[articleType])");
}
typeID => is number, the other values are text.
There is no error in this code, but the insert query doesn't work (I have no idea why because I don't get any error message).
How can I fix it?
There are a number of problems with your code.
It's open to SQL injectoion
mysql_* functions have been deprecated
This code is untested but should give you an idea:
try
$dbh = new PDO('mysql:host=localhost;dbname=your_database_name', $user, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sth = $dbh->prepare('INSERT INTO Persons (articleTitle, articleContent, typeID) VALUES (:articleTitle, :articleContent, :articleType)');
$sth->execute($_POST);
$dbh = null;
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
}
Have a look at this article on Why you Should be using PHP’s PDO for Database Access
Try this
if(isset($_POST[articleTitle])) {
$insert_query = mysqli_query("INSERT INTO Persons (articleTitle, articleContent,typeID)
VALUES
('$_POST[articleTitle]','$_POST[articleContent]',$_POST[articleType])");
}
I am brand new to php and I ran into a problem that has already taken a few hours of poking around and researching and I could not find anything like it anywhere around the net.
Database:MyPHPAdmin winserver
Goal: Create a new row in table 'photo'. Take the last insert p_id for the current user and update the table accessible_to by creating a new row with that p_id.
I know I can create a trigger, and no it does not work either don't know why. Run out of ideas how.
What I found out by simply printing before-in-after the if statement
if ($stmt = $mysqli->prepare("insert into accessible_to values(?, ?, ?)"))
is that it just bypasses it.
Please post your suggestions.
P.S. The if statement above to which I am referring has been twisted in several ways and yet it does not work.
The connection is already imported.
Thank you a lot.
if(!isset($_SESSION["id"])) {
echo "You are not logged in. ";
echo "You will be returned to the homepage in 3 seconds or click here.\n";
header("refresh: 3; index.php");
}
else {
//if the user have uploaded a photo, insert it into database
if(isset($_POST["ext"])) {
//insert into database, note that p_id is auto_increment
if ($stmt = $mysqli->prepare("insert into photo (ext, owner_id) values (?,?)")) {
$stmt->bind_param("ss", $_POST["ext"], $_SESSION["id"]);
$stmt->execute();
$stmt->close();
$id = htmlspecialchars($_SESSION["id"]);
}
//The following function is fetching the last added p_id in PHOTO by the user with the current SESSION
//Do not simply get the last p_id in PHOTO because someone else might have just added another picture meanwhile
if ($stmt = $mysqli->prepare("select MAX(p_id) from photo where owner_id = ?")){
$stmt->bind_param("s", $id);
$stmt->execute();
$stmt->bind_result($p_id);
if ($stmt->fetch()){
$p_id = htmlspecialchars($p_id);
}
}
echo "BEFORE accessible_to insertion";
echo '<br />';
if ($stmt = $mysqli->prepare("insert into accessible_to values(?, ?, ?)")){
echo "Finally inside accessible_to insertion";
echo '<br />';
$stmt->bind_param("iss", $p_id, $id, 'T');
$stmt->execute();
$stmt->close();
}
echo "AFTER accessible_to insertion";
echo '<br />';
}
//if not then display the form for posting message
else {
echo "Something";
You can't boolean test an assignment and expect it to return a different result. What you want to test for is if $stmt->execute successfully executed or not.
$stmt = $mysql->prepare("insert into foo values (?,?)");
$stmt->bind_param(1,$f1);
$stmt->bind_param(2,$f2);
if ($stmt->execute()) {
... worked
} else {
... fubar
}
You have to start by calling mysqli::connect($server, $user, $pw, $db). The best way to do that is by constructing an object like:
$connection = new mysqli($server, $user, $password, $db);
if ($connection->errno)
{
echo "Connection failed";
echo $this->connection->error;
}
else
{
$stmt = $connection->prepare("insert into photo (ext, owner_id) values (?,?)")) {
$stmt->bind_param("ss", $_POST["ext"], $_SESSION["id"]);
$stmt->execute();
$stmt->close();
}