I have this php script for posting announcements to a database using mySQL. I'd like to change it to use PDO.
The code I have originally is here:
<?php
require_once"connection.php";
session_start();
if(isset($_POST['annForm']))
{
$userID=$_SESSION['sessionUser'];
$idQuery=mysql_query("SELECT adminID FROM administrator WHERE username='$userID'");
$adminID=mysql_fetch_array($idQuery);
$genAnnouncement=$_POST['annForm'];
$genAnnouncement=mysql_real_escape_string($genAnnouncement);
$addGenAnnQuery="INSERT INTO generalannouncement (adminID, genAnnouncement) VALUES('$adminID[0]','$genAnnouncement')";
$announcementAdded=mysql_query($addGenAnnQuery);
if(!$announcementAdded)
{
echo 'Could Not Add Announcement, Try Again Later.<br>';
echo mysql_error();
}
else
echo 'Announcement Added Successfully.<br>';
header( "refresh:500;url=adminsHomepage.php" );
return;
mysql_close($con);
}
?>
I have modified the code to use PDO but I am getting errors now on line 24 with undefined index $adminID[0] and line 25 with Integrity constraint violation: 1048 Column 'adminID' cannot be null. The modified code is as follows:
require_once"connection.php";
session_start();
if(isset($_POST['annForm']))
{
$userID=$_SESSION['sessionUser'];
$idQuery= $conn->prepare("SELECT adminID FROM administrator WHERE username='$userID'");
$idQuery->execute();
$adminID= $idQuery->fetch();
$genAnnouncement=$_POST['annForm'];
if (isset($genAnnouncement))
{
$sql = "INSERT INTO generalannouncement (adminID, genAnnouncement)
VALUES (:adminID, :genAnnouncement)";
$stmt = $conn->prepare($sql);
$stmt->execute(array(
':adminID' => $_POST['$adminID[0]'],
':genAnnouncement' => $_POST['annForm']));
echo 'Announcement Added Successfully.<br>';
header( "refresh:500; url= adminsHomepage.php");
return;
}}
In your original MySQL_ query you have:
$addGenAnnQuery = "
INSERT INTO generalannouncement
(adminID, genAnnouncement)
VALUES ('$adminID[0]','$genAnnouncement')
";
So, if your old query work, new execute must be this:
$stmt->execute(array(
':adminID' => $adminID[0],
':genAnnouncement' => $genAnnouncement));
I think, you have problem here: $_POST['$adminID[0]']
Just try to delete apostrophes.
Related
Ok, so I've been trying to do this for days, and I've been reading all sorts of tutorials, but I seem to be missing something, because I still can't get it. I'm working on learning about web forms and inserting the form input into the respective database. I'm able to take the info from the form and echo it on the result page, so I know that all works. but I can't seem to get the form input to go into my database. I know the connection works, so there must be something wrong with my syntax.
PHP
//DB Configs
$username = null;
$password = null;
try {
$db = new PDO("mysql:host=localhost;dbname=Testing3", $username, $password);
//Set the PDO error mode to exception (what does this mean?)
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//Prepare SQL and bind parameters
$sql = $db->prepare("INSERT INTO `NFK_SPECIES` (`Name`)
VALUES (:name)");
//Insert a Row
$species = $_POST['Species'];
$sql->execute(array(':name'=>$species));
}
catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
$result = $db->query('SELECT * from `NFK_Species` ORDER BY `Id` DESC');
//Query
/*
$input = $db->query("INSERT INTO `NFK_Species` (`Id`, `Name`) VALUES (Null, `$species`)");
$result = $db->query('SELECT * from `NFK_Species` ORDER BY `Id` DESC');*/
//Kill Connection
$db = Null;
}
HTML/PHP (web page)
<h1>Inserting a New Species into Database:</h1>
<h3>Results</h3>
<?php
if ($sql->execute()){
echo "Data input was successful";
while ($rows = $result->fetch()){
echo $rows['Name']; echo ", ";
}
} else {
echo "Data input failed."; echo mysql_error();
}
?>
This is only my current attempt at doing this. I prefer the attempt I had before, with the bindParam and simple execute(), so if I could get that to work instead, I'd appreciate it. The following example also has the Id column for this table. This is an auto-increment column, which I read doesn't need to be included, so I excluded it from my recent attempt. Is that correct?
Past PHP
//Prepare SQL and bind parameters
$sql = $db->prepare("INSERT INTO `NFK_SPECIES` (`Id`, `Name`)
VALUES (Null, :name)");
$sql->bindParam(':name', $species);
//Insert a Row
$species = $_POST['Species'];
$sql->execute();
I've been reading a bunch of tutorials (or trying to), including attempting to decipher the php.net tutorials, but they all seem to be written for people who already have a good handle on this and experience with what's going on, and I'm very new to all of this.
Alright, I was able to figure out my problem, and then successfully insert a row using my code.
Debugging:
So the code posted above was breaking my code, meaning my page wouldn't load. I figured that meant that there was a syntax error somewhere, but I couldn't find it, and no one else had located it yet. Also, that meant that my Error Alerts weren't working to let me know what the problem was. If you look at my original PHP sample, you'll see down at the very bottom there is a single "}" just hanging out and serving no purpose, but more importantly, it's breaking the code (stupid, hyper-sensitive php code). So I got rid of that, and then my Error messages started working. It said I couldn't connect to my database. So I look over my database login syntax, which looked fine, and then you'll notice in my 1st php sample that somehow I'd managed to set my $username and $password to NULL. Clearly that isn't correct. So I fixed that, and next time I refreshed my page, I'd successfully entered a row in my database! (yay)
Note:
In my original php sample, I'd included the Id Column, which is auto-incremented, for the row insertion, with a value of NULL. This worked, and it inserted the row. Then I experimented with leaving it out altogether, and it still worked. So the updated working code below doesn't include the Species Id.
Working code:
<body>
<h1>Inserting a New Species into Database:</h1>
<h3>Results</h3>
<?php
//DB Configs
$username = root;
$password = root;
try {
//Connect to Database
$db = new PDO("mysql:host=localhost;dbname=Testing3", $username, $password);
//Enable PDO Error Alerts
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//Prepare SQL statement and bind parameters
$sql = $db->prepare("INSERT INTO `NFK_SPECIES` (`Name`) VALUES (:name)");
$sql->bindParam(':name', $species);
//Insert a Row
$species = $_POST['Species'];
$sql->execute();
// Echo Successful attempt
echo "<p class='works'><b>" . $species . "</b> successfully added to database.</p></br></br>";
}
catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
// Gather updated table data
$result = $db->query('SELECT * from `NFK_Species` ORDER BY `Id` DESC');
//Kill Connection
$db = Null;
while ($rows=$result->fetch()){
echo $rows['Id']; echo " - "; echo $rows['Name']; echo "</br>";
}
?>
<body>
Hello there am trying to insert data into MSSQL using PHP. I have tried many times to figure out what the problem might be but i seem not to find it. Is there something am not getting right or missing?
<?php
//pull form fields into php variables
$no = $_POST['no'];
$name= $_POST['name'];
$date = $_POST['date'];
$leave = $_POST['leave'];
$days= $_POST['days'];
$empno= $_POST['empno'];
//connect to sql
$dbc = mssql_connect('Server-PC','user','password','database')or die('Error connecting to
the SQL Server database.');
// Input into staff database
$query = "INSERT INTO dbo.[CAGD$Leave Plan] ([No_],[Employee No_],[Employee Name],
[Leave Name], [Start Date],[Leave Days],Satus) VALUES
('$no','$name','$leave','$date','days','empno')";
$r esult = mssql_query($query,$dbc)or die('Error querying MSSQL database');
//close to sql
mssql_close($dbc);
echo $name . 'Your submission has been received<br />';
echo 'If you need change this request please contact your HR Manager<br />';
echo 'Thank you <br />';
echo 'HR Manager';
?>
I get this error message:
Warning: mssql_query() [function.mssql-query]: message: Invalid object name 'dbo.CAGD Plan'.
(severity 16) in C:\xampp\htdocs\CAGD\leave_request.php on line 110
Warning: mssql_query() [function.mssql-query]: Query failed in C:\xampp\htdocs
\CAGD\leave_request.php on line 110
Error querying MSSQL database
You can use SQLSRV Driver instead of MSSQL Driver and then try this
<?php
$serverName = "serverName";
$options = array( "UID" => "sa", "PWD" => "Password", "Database" => "DBname");
$conn = sqlsrv_connect($serverName, $options);
if( $conn === false )
{
echo "Could not connect.\n";
die( print_r( sqlsrv_errors(), true));
}
$no = $_POST['no'];
$name= $_POST['name'];
$query = "INSERT INTO dbo.Test
(No_,FirstName)
VALUES(?, ?)";
$params1 = array($no,$name);
$result = sqlsrv_query($conn,$query,$params1);
sqlsrv_close($conn);
?>
This is more useful, and you can learn more here:
https://msdn.microsoft.com/en-us/library/cc626305(v=sql.105).aspx
First Specify your database Connection...
mssql_connect('Server-PC','user','password','database')
like -> "localhost","root","XXXX", "DBNAME"
then query like
$query = "INSERT INTO TABLENAME (id,name) VALUES
('$id','$name')";
$result = mssql_query($query,$dbc)
Hmm, it seems to me that you have 7 fields in the table but only 6 values submitted - you are missing the value for the first column, [No_].
Besides, the last column satus (i suppose it should be 'status') does not have de [] delimiters.
The error returned tells you that the name of the table is wrong.
And yes variable names are case sensitive in PHP, it should be $leave - best to exit the string and concatenate - something like "bla bla".$leave."anything here with spaces or not" .
Is this supposed to be a variable?
$query = "INSERT INTO dbo.[CAGD$Leave Plan] ([No_],[Employee No
^^^^^^
If so, then it's apparently undefined in your code, and the generated query string will contain dbo.[CAGD Plan], and not whatever value was supposed to be in that variable. If the $ is literally in your table name, then it should be CAGD\$Leave, so that $Leave isn't treated as a variable.
So Im trying to delete a record from a table using php and sql and check whether it has been deleted using a rowcount() function in an if statement.
Im having problems on both fronts...
<?php
echo $_GET['id'];
if (isset($_GET['id'])) {
$trainingID = $_GET['id'];
}
else {
die('There was a problem with the ID given.');
}
// include the connection file
require_once('./includes/connection.inc.php');
$conn = dbConnect();
// prepare SQL statement
$sql = 'DELETE FROM `trainingCourses` WHERE `trainingID` = "$trainingID"';
$stmt = $conn->prepare($sql);
try {
$stmt->execute();
echo "deleted";
echo $stmt->rowcount();
//check number of rows affected by previous insert
if ($stmt->rowCount() == 1) {
$success = "$trainingID has been removed from the database.";
}
}
catch(PDOException $e){
echo $e;
echo 'Sorry, there was a problem with the database.';
}
?>
I currently get 3 things outputted from my echo's throughout my code, firstly i get T0001, which is the primary key of the record i want to delete from another page. Secondly i get "deleted" which is from an echo within my 'try' statement but the record doesn't actually delete from the database. This is backed up from the rowcount() function which outputs 0.
I can't seem to get this working and im sure it should be simple and is something i am just overlooking!
Will the try method default to the catch if the "if" statement in it fails? As im also unsure what should be output from a rowcount() when a row has been deleted?
Any help you could offer would be really helpful! Thanks!
echo'ing this line
$sql = 'DELETE FROM `trainingCourses` WHERE `trainingID` = "$trainingID"';
will treat $trainingID as string and not variable.
$sql = "DELETE FROM `trainingCourses` WHERE `trainingID` = '$trainingID'";
will do the work BUT its not safe (sql injections). You should use PDO to bind varaibles like this
$sth = $dbh->prepare("DELETE FROM `trainingCourses` WHERE `trainingID` = :id");
$sth->bindParam(":id",$trainingID);
$sth->execute();
I have writen this pice of code that should insert into my Database some event data, but it does not insert a thing in the DB, can you tell me why?
try {
$pdo = new PDO("mysql:host={$dbhost};dbname={$dbname}", $dbuser, $dbpass);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch( PDOException $excepiton ) {
echo "Connection error :" . $excepiton->getMessage();
}
try{
$sql = "INSERT INTO events_DB (event_id, event_end_time, event_location, event_name) VALUES (:event_id, :event_end_time, :event_location, :event_name) ON DUPLICATE KEY UPDATE event_id = :event_id, event_end_time = :event_end_time, event_location = :event_location, event_name = :event_name";
$stm = $db->prepare($sql);
$stm->execute(array(":event_id" => $event[id], ":event_end_time" => $event[end_time], ":event_location" => $event[location], ":event_name" => $event[name]));
}
catch ( PDOException $exception )
{
// decomentati sa vedeti erorile
echo "PDO error :" . $exception->getMessage();
}
Thanks
The code you've posted is different than the code you're running as the posted code would result in a syntax error at parse time and never actually run.
However, what's happening is the SQL being sent to the prepare method is not valid in some way so that the result returned and stored in $stm is a boolean (false) rather than a valid statement object. Double check your SQL (you could try running it in another application such as phpMyAdmin or via the mysql command-line program) to ensure its validity. You could also add some error handling to find the cause with:
$stm = $db->prepare($sql);
if (!$stm) {
die($db->errorInfo());
}
Edit: You've modified the posted source code which now shows use of exception handling. However, you've commented out the line that echos the exception message. This information will be useful in telling you what's causing the error condition. Uncomment to see the message (which will most likely inform you that the SQL is invalid and which part of it caused the error).
Try to remove the <br> tag from the first line and a " is messing
$sql = "INSERT INTO events_DB (event_id, event_end_time, event_location, event_name);"
I'm new to PHP and MySQL and I'm trying to insert data in to a database, which had worked fine until i attempted to use PDO's prepare method. It returns the catch error and i cannot figure out why - i'd also like to know whether it's best practice to use unnnamed placeholders or named placeholders?
The username and password variables are defined earlier in my code and catches data from the user using $_POST.
EDIT: getMessage() error displays SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'username' cannot be null
if (!empty($user) && (!empty($password)) ) {
try {
$results = $db->prepare("INSERT INTO user_info (username, pass) VALUES (?,?)");
$results->bindParam(1,$username);
$results->bindParam(2,$password);
$results->execute();
} catch (Exception $e) {
echo "Could not insert data in to the database";
}
}
You have two different variable names. You're checking $user to make sure it's not empty() but then you tell bind $username to the first parameter. You'll just need to rename one of them to match the other.
Try this one.
if (!empty($user) && (!empty($password)) ) {
try {
$results = $db->prepare("INSERT INTO user_info (username, pass) VALUES (?,?)");
$results->bindParam(1,$user);
$results->bindParam(2,$password);
$results->execute();
} catch (Exception $e) {
echo "Could not insert data in to the database";
}
}
Please try yourself first to find the error.