PHP - Is It Possible To Insert Into Database The Session Name? - php

So I'm making a posting system with PHP.
When the user wants to create a post, all the fields need to be complete, and what I'm trying to do is to insert into the database the name of the session, for example, to insert to the database 'Edward', because that would be the name of the session.
Here's what I'm trying to do:
<?php
session_set_cookie_params(86400*30, "/");
session_start();
require 'admin/config.php';
require 'functions.php';
if (isset($_SESSION['user'])) {
require 'view/new.view.php';
} else {
header('Location: index.php');
}
$connection = connect($bd_config);
if (!$connection) {
header('Location: error.php');
}
$errors = '';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$title = cleanData($_POST['title']);
$demo = cleanData($_POST['demo']);
#$project_type = $_POST['project_type'];
$content = $_POST['content'];
$post_by = $_SESSION['user'];
$errors = '';
if (empty($title) or empty($demo) or empty($project_type) or empty($content)) {
$errors .= '<p>Complete all the fields!</p>';
} else {
$statement = $connection->prepare("
INSERT INTO posts (ID, title, demo, content, post_type)
VALUES (null, :title, :demo, :content, :project_type)
");
$statement->execute(array(
':title' => $title,
':demo' => $demo,
':project_type' => $project_type,
':content' => $content,
));
$statement2 = $connection->prepare("
INSERT INTO posts (post_by)
VALUES ($post_by)
");
$statement2->execute(array(
$post_by
));
header('Location: main.php');
}
}
?>
As you can see, I'm doing 2 statement variables for 2 SQL consults, but when I do that, it throws this error:
<b>Fatal error</b>: Uncaught PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'cesar' in 'field list' in C:\xampp\htdocs\bider\test2\new.php:52
Stack trace:
#0 C:\xampp\htdocs\bider\test2\new.php(52): PDOStatement->execute(Array)
#1 {main}
thrown in <b>C:\xampp\htdocs\bider\test2\new.php</b> on line <b>52</b><br />
It marks 'cesar' cause that's the session name, I guess.
Can someone help?

Your second query is the problem - you're not using parameters properly. Compare it to your first one and spot the difference in the structure. You need to specify a placeholder :post_by in the INSERT statement so PDO knows where to bind the variable, and you need to give the $post_by entry in the parameter array the same name as an index, so they match up.
Here's a version which will work:
$statement2 = $connection->prepare(
"INSERT INTO posts (post_by)
VALUES (:post_by)"
);
$statement2->execute(array(
":post_by" => $post_by)
);

Related

Uncaught TypeError: mysqli_query(): Argument #2 ($query) must be of type string, mysqli_stmt given in PHP [duplicate]

This question already has answers here:
how to use $_GET inside mysqli_query? [duplicate]
(7 answers)
PHP: Inserting Values from the Form into MySQL
(2 answers)
PHP MySQLInsert prepared statements
(4 answers)
Closed last year.
I created a prepared statement in my PHP script but when I submit my form to insert, I get this error, Fatal error: Uncaught TypeError: mysqli_query(): Argument #2 ($query) must be of type string, mysqli_stmt given in C:\xampp\htdocs\7058\insert.php:100 Stack trace: #0 C:\xampp\htdocs\7058\insert.php(100): mysqli_query(Object(mysqli), Object(mysqli_stmt)) #1 {main} thrown in C:\xampp\htdocs\7058\insert.php on line 100.
It is my first time trying prepared SQL statements, so I am not sure what I am doing wrong.
<?php
session_start();
// servername => localhost
// username => root
// password => empty
// database name => staff
$conn = mysqli_connect("localhost", "root", "", "survey");
// Check connection
if ($conn === false) {
die("ERROR: Could not connect. "
. mysqli_connect_error());
}
$name = $_SESSION['name'];
$paygoid = $_SESSION['paygoid'];
$product_exist_satisfaction = $_SESSION['product_exist_satisfaction'];
$system_battery_runout = $_SESSION['system_battery_runout'];
$rank_appliances = $_POST['rank_appliances']; //return an array.
$checkboxvalue = implode(",", $rank_appliances);
$sql = $conn->prepare("INSERT INTO cus_survey (name,paygoid,product_exist_satisfaction,system_battery_runout,rank_appliances) VALUES (?, ?, ?, ?, ?)");
$sql->bind_param("sssss", $name, $paygoid, $product_exist_satisfaction, $system_battery_runout, $checkboxvalue);
if (mysqli_query($conn, $sql)) { **//this is line 97**
echo "<h3>Your survey was captured successfully. Thank You!"
} else {
echo "<h3>Sorry, Your ID has already been used. Please enter a valid ID</h3> "
echo "<h3><a href='/7058/index.php'>Click here to edit your ID</a></h3>";
}
// Close connection
mysqli_close($conn);
?>
I hope the following will help point you in the right direction. Initially you should make a sanity check that the variables you intend to use are actually available to avoid silly errors and then, using the considerably less verbose OO style of mySQLi, prepare the sql statement, bind the placeholders, execute the statement and then find if it succeeded.
<?php
session_start();
if( isset(
$_SESSION['name'],
$_SESSION['paygoid'],
$_SESSION['product_exist_satisfaction'],
$_SESSION['system_battery_runout'],
$_POST['rank_appliances']
)){
$conn = new mysqli("localhost", "root", "", "survey");
$name = $_SESSION['name'];
$paygoid = $_SESSION['paygoid'];
$product_exist_satisfaction = $_SESSION['product_exist_satisfaction'];
$system_battery_runout = $_SESSION['system_battery_runout'];
$rank_appliances = $_POST['rank_appliances'];
$checkboxvalue = implode(",", $rank_appliances);
$stmt = $conn->prepare( "INSERT INTO `cus_survey` ( `name`, `paygoid`, `product_exist_satisfaction`, `system_battery_runout`, `rank_appliances` ) VALUES (?, ?, ?, ?, ?)" );
$stmt->bind_param("sssss", $name, $paygoid, $product_exist_satisfaction, $system_battery_runout, $checkboxvalue );
$stmt->execute();
if ( $stmt->affected_rows==1 ) {
echo "<h3>Your survey was captured successfully. Thank You!"
} else {
echo "<h3>Sorry, Your ID has already been used. Please enter a valid ID</h3> "
echo "<h3><a href='/7058/index.php'>Click here to edit your ID</a></h3>";
}
$stmt->close();
$conn->close();
exit();
}
?>

Prepared Statement MySQL UPDATE Not Updating the DB Values

I am trying to make a script to update the values stored in the DB with the new values typed in the form
GET the values from the form:
$reviewTitle = $_POST['reviewTitle'];
$storeScore = $_POST['storeScore'];
$reviewContent = $_POST['reviewContent'];
UPDATE Values to the DB
$sql = "UPDATE reviews SET reviewTitle=?, storeScore=?, reviewContent=? WHERE reviewID=?";
$stmt = $db->prepare($sql);
$stmt->bind_param('sisi', $reviewTitle, $storeScore, $reviewContent, $_POST['edit']);
$stmt->execute();
if ($stmt->error) {
echo "FAILURE!!! " . $stmt->error;
}
else echo "Updated {$stmt->affected_rows} rows";
header("Location: review?store=" . $store['storeName']);
I cannot see a reason why this would not work, am i missing something in the syntax? Any help appreciated
EDIT: I have added the Error that is outputted by the script
Fatal error: Uncaught Error: Call to undefined method
PDOStatement::bind_param() in .
/home/o2q4e1ph6yl2/public_html/editreview.php:38 Stack trace: #0
/home/o2q4e1ph6yl2/public_html/review.php(54): include() #1 {main} .
thrown in /home/o2q4e1ph6yl2/public_html/editreview.php on line 38
Answer to the question is:
$query = $db->prepare("UPDATE reviews SET reviewTitle=:reviewTitle, storeScore=:storeScore, reviewContent=:reviewContent WHERE reviewID=:reviewID");
$query->execute(array(':reviewTitle' => $reviewTitle, ':storeScore' =>
$storeScore, ':reviewContent' => $reviewContent, ':reviewID' => $reviewID));
It only took 4h to figure out

How to Convert mySQL to PDO

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.

Insert Data into MSSQL DB using PHP

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.

If an error occurs, how do i insert the incident in to the db using the following script?

If a duplicate id error occurs i want to record it into the db. I am using this snippet below, how do i make room for it to insert the error information in the db?
Code:
if ( $postedid === $storedid ) {
require("error.php");
die("");
}else{
echo("");
}
You have to insert it before you close the script ( die() ). You insert a db query to log the error.
You simply pass the MySQL Query into the die(); function.
You would get the errors using
mysqli.errno.php and mysqli.error.php
DB QUERY -
INSERT INTO error (type, page) VALUES ('{mysqli_error($dbc)}','{$_SERVER['PHP_SELF']}')
<?php
if ( $postedid === $storedid ) {
require("error.php");
$type = mysqli_error($dbc); //Where $dbc is your connection resource.
$file = $_SERVER['PHP_SELF'];
$q = "INSERT INTO error (type, page) VALUES ('{$type}','{$file}')";
die( $r = mysqli_query ($dbc, $q) );}
else{
echo("");
}
?>

Categories