Database not updating with PDO statement? - php

Is there something wrong with the syntax of the statement? I've been messing around with inserting different variables into the code and it still wont update in phpmyadmin. Pretty new with this language so please bear with me.
Pretty sure the line giving me the issue is:
$pdoQuery ="UPDATE `Lab4` SET `ActiveUser`=".$Yes." WHERE UserName=".$Email."";
I just don't know what the issue is...
<?php
//connect to the database
session_start(); //this must be the very first line on the php page, to register this page to use session variables
$_SESSION['timeout'] = time();
//if this is a page that requires login always perform this session verification
//require_once "inc/sessionVerify.php";
require_once "dbconnect.php";
require_once "inc/util2.php";
require_once "mail/mail.class.php";
include "header.php";
// $EmailCode = $_GET["Code"];
if (isset($_SESSION['Code'])){
echo $_SESSION['Code'];
echo $_SESSION['Email'];
}
?>
<?php
if (isset($_POST['Submit'])){
try {
$pdoConnect = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
}
catch (PDOException $exc) {
echo $exc->getMessage();
exit();
}
//$NotAnActiveUserYet = "No";
// mysql query to insert data
$Email = $_SESSION['Email'];
$Yes = "Yes";
$pdoQuery ="UPDATE `Lab4` SET `ActiveUser`=".$Yes." WHERE UserName=".$Email."";
$pdoResult = $pdoConnect->prepare($pdoQuery);
$pdoResult->execute();
if ($pdoResult) {
echo 'Data Inserted';
} else {
echo 'Data Not Inserted';
}
}
?>

_Try something along these lines:
$params = array(
'ActiveUser' => $Yes,
'UserName' => $Email,
);
$pdoQuery ='UPDATE `Lab4` SET `ActiveUser`=:ActiveUser WHERE `UserName`=:UserName';
$pdoResult = $pdoConnect->prepare($pdoQuery);
$pdoResult->execute($params);
And as tadman said,... NEVER trust anything from a browser. (includes $_REQUEST, $_GET, $_POST, $_COOKIE, etc.)

Related

How to get a message id based on the ticket id

I'm making a ticket system and trying to add an edit feature.
and I was wondering how do I get the selected message-id that I have chosen to select.
The far as I have got is hard coding the id into the code.
<?php
session_start();
if($_SESSION['loggedin'] == true)
{
require '../../config.php';
$ticketMsg = $conn->query("SELECT * FROM ticket_msgs WHERE ticket_id='".mysqli_real_escape_string($conn, $_GET['id'])."'");
$edit = $conn->query("UPDATE `ticket_msgs` SET `ticket_msg` = 'Testing' WHERE `ticket_msgs`.`id` = ");
if($edit)
{
header("location: ./index.php");
}
else
{
}
}
?>
With mysql PDO:
$sql = 'UPDATE ticket_msgs SET ticket_msg=:msg WHERE id=:id';
// prepare statement
$statement = $conn->prepare($sql);
// bind params
$statement->bindParam(':msg', $ticketMsg);
$statement->bindParam(':id', $_GET['id'], PDO::PARAM_INT);
// execute the UPDATE statement
if ($statement->execute()) {
// updated, go to your index page
header("location: ./index.php");
}

Update value using php

I want to update the marks of a student in php.
All the values are fetching properly from the table.
But after changing the value it is not updating.
<?php
session_start();
error_reporting(0);
include('includes/config.php');
if(strlen($_SESSION['alogin'])=="")
{
header("Location: index.php");
}
else
{
$stid=intval($_GET['stid']);
if(isset($_POST['submit']))
{
$rowid=$_POST['id'];
$ct=$_POST['ct'];
$wt=$_POST['wt'];
$pro=$_POST['pro'];
$ter=$_POST['ter'];
foreach($_POST['id'] as $count => $id)
{
$c=$ct[$count];
$iid=$rowid[$count];
for($i=0;$i<=$count;$i++)
{
$sql="update tblresult set ct=:c,wt=:w,pro=:p,ter=:t where id=:iid ";
$query = $dbh->prepare($sql);
$query->bindParam(':c',c,PDO::PARAM_STR);
$query->bindParam(':w',w,PDO::PARAM_STR);
$query->bindParam(':p',p,PDO::PARAM_STR);
$query->bindParam(':t',t,PDO::PARAM_STR);
$query->bindParam(':iid',$iid,PDO::PARAM_STR);
$query->execute();
$msg="Result info updated successfully";
}
}
}
}
?>
enter image description here
It looks like the values you're using for bindParam aren't correct.
$query->bindParam(':c',c,PDO::PARAM_STR); for example looks like it should be:
$query->bindParam(':c', $ct, PDO::PARAM_STR);
I would also look at being more consistent with your variable names and maybe the 'Result info updated successfully' message is possibly a little presumptuous.

Delete row of MySQL database with $_GET parameter

So I have a table named recept_felhasznalok_pending with four columns one of which is email. I want to be able to delete a row from the table using a link I can send anyone. I have the following PHP code in deny.php:
<?php
include('database.php');
///////////////////////////////////
function azonositott_e() {
return ($_SESSION["email"] === "This is the email address of the person I want to be able to use the link.");
}
session_start();
if (!azonositott_e()) {
header("Location: login.php");
exit();
}
function db($kapcsolat, $email) {
$torol = vegrehajtas($kapcsolat,
"DELETE FROM `recept_felhasznalok_pending` WHERE `email` = :email",
[ ":email" => $email ]
);
}
if ($_GET['email']) {
db($kapcsolat, $_GET['email']);
header("Location: index.php");
exit();
}
?>
The database.php file has the connection and execute parts of the code:
<?php
function kapcsolodas($kapcsolati_szoveg, $felhasznalonev = '', $jelszo = '') {
$pdo = new PDO($kapcsolati_szoveg, $felhasznalonev, $jelszo);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $pdo;
}
function lekerdezes($kapcsolat, $sql, $parameterek = []) {
$stmt = $kapcsolat->prepare($sql);
$stmt->execute($parameterek);
return $stmt->fetchAll();
}
function vegrehajtas($kapcsolat, $sql, $parameterek = []) {
return $kapcsolat
->prepare($sql)
->execute($parameterek);
}
$kapcsolat = kapcsolodas(
'mysql:host=*********;dbname=************;charset=utf8',
'********', '***********');
?>
When I open domain.com/deny.php?email=example#example.com (logged in) that row should be deleted from the table, but it doesn't, I just get redirected to index.php. What am I doing wrong?
EDIT: There is no mistake in database.php as it works everywhere else in my project. Also, I don't get any error messages.

Why mysql Insert into query not working in php application

When execute the query it's not working, it will print error. $q also not coming when i'm print it. but $_SESSION["username"]; is working?
<?php
session_start();
$_SESSION["username"];
include 'Db_Connection.php';
$q= $_GET[q];
$username= $_SESSION[username];
echo $username;
echo $q;
$sql="INSERT INTO search(searcher,searched_time,searched_email)
VALUES ('$username',NOW(),'$q')";
$result = mysqli_query($con,$sql);
if($result)
{
echo "Success";
}
else
{
echo "Error";
}
?>
Couple of things I can pick up from your provided code.
Your second line $_SESSION["username"]; is superfluous as it does nothing
You are using the mysql_* functions which are deprecated
You are not using prepared statements for inserting variables into your query
try something like this:
session_start();
//start assuming this is in your connection file
$con = new mysqli("db-ip-address", "db-user", "db-pass", "db-name")
//end assuming
$q= $_GET[q];
$username= $_SESSION[username];
echo $username;
echo $q;
$sql="INSERT INTO search(searcher,searched_time,searched_email) VALUES (?,NOW(),?)";
$stmt = $con->prepare($sql);
$stmt->bind_param("ss", $username, $q);
$result = $stmt->execute();
if($result) {
echo "Success";
} else {
echo "Error";
}
//remember to cleanup connections etc
as far as the value $q not printing out, make sure that the value is set via the GET query string http://someurl.com/somefile.php?q=some-value and that $q is not some weird non-printable value. If you want to confirm that the value is set, try running var_dump($_GET) to output the contents of your $_GET array to ensure there is actually a value being set.
I believe this is your problem:
$q= $_GET[q];
q should be surrounded in quotes, e.g.:
$q = $_GET['q'];
Other than that, what Damon said was completely correct.

Unable to get session in different PHP page

Unable to get session from different PHP page other than where i initialized it
This is my first PHP page where i initialize the session.
<?php
$i =1;
$team = htmlentities($_POST['team']);
$id = htmlentities($_POST['id1']);
$mobile = htmlentities($_POST['mobile1']);
if(isset($_POST['id2']))
{
$ids = htmlentities($_POST['id2']);
$mobiles = htmlentities($_POST['mobile2']);
$i=2;
}
if(isset($_POST['id3'])){
$ids = $ids.','.htmlentities($_POST['id3']);
$mobiles = $mobiles.','.htmlentities($_POST['mobile3']);
$i=3;}
echo $team;
echo $i;
$connect =new mysqli('localhost', 'root', 'password','test');
if($connect->connect_error)
{
die("connection failed : ".$connect->connect_error);
}
$data = "INSERT INTO `Users`(`team_name`, `id`, `mobile`, `ids`, `mobiles`) VALUES ('$team','$id','$mobile','$ids','$mobiles')" ;
$createData="CREATE TABLE `$id`(
`id` INT NOT NULL ,
`ansOpChoosen` INT NOT NULL,
`realAns` INT NOT NULL
);";
echo 'pass';
$link ="/test.html";
$link2 = "/signups.html";
if(mysqli_query($connect,$data) && mysqli_query($connect,$createData) )
{
session_start();
$_SESSION['user'] = $id;
header('Location: '.$link);
echo "new record created successfully";
}
else{
header('Location: '.$link2);
echo "error";
}
$connect->close();
?>
This is another php page where i try to retrive data but it doesnt fetch any thing
<?php
$id = $_SESSION['user'];
$quesNo = $_POST['questionNo'];
$optionCho = $_POST['optionchoosen'];
$optionReal =$_POST['optionreal'];
echo $id;
//echo "hbbhkhb";
$connect =new mysqli('localhost','root','password`','test');
if($connect->error){
echo "connection error";
}
$check ="SELECT * FROM `$id` WHERE `id`=$quesNo";
if($res=mysqli_query($connect,$check)){
$count = mysqli_num_rows($res);
if($count>0)
{
$data ="UPDATE `$id` SET `ansOpChoosen`=$optionCho,`realAns`=$optionReal WHERE `id`=$quesNo";
}
else{
$data = "INSERT INTO `$id`(`id`,`ansOpChoosen`,`realAns`) VALUES ($quesNo,$optionCho,$optionReal)";
}
$store=mysqli_query($connect,$data);
}
?>
Put session_start(); at the top of every page that you want to use sessions on.
You always have to call session_start() before doing something with the session.
session_start() creates a session or resumes the current one based on a session identifier passed via a GET or POST request, or passed via a cookie.
Source: http://php.net/manual/en/function.session-start.php
A session is started with the session_start() function.
Be careful : it must be top of every page.
For example :
<?php
session_start();
if (!isset($_SESSION['count'])) {
$_SESSION['count'] = 0;
} else {
$_SESSION['count']++;
}
?>
Manual : http://php.net/manual/en/session.examples.basic.php

Categories