Make dynamic sql to get data from session array - php

I am using PDO. I want to make a sql statement which gives the user_id of that user which name is in session array. When I get the data from session array in variable and write it in sql it gives nothing but when I write "jhon" it gives user_id that I required. But I want to dynamic sql prepare statement. I see some solution from net but I can't figure it out.
session_start();
if(isset($_SESSION["username"])){
$name=$_SESSION["username"];
function add_posts(){
if($posts_text != ""){
try {
$conn=parent::connect();
$sql1=$conn->prepare("select user_id from user_login
where username=:username ");
$arr=array ('username'=>$name );//when i write "jhon" it gives id 14,
// when i write $name it gives nothing
$sql1->execute($arr);
$fetch = $sql1->fetch();
echo $fetch['user_id'];
}
catch (PDOException $e){
die ("connection failed" .$e->getMessage() );
}
}
}

You need you pass $name argument in your function
function add_posts($name) {

Related

Can't delete rows from database

I want to delete some rows from my table. But when I click delete, this just show me a blank page. I'm sure about id value and my db connection.
This is my code:
// connect to the database
include('connect-db.php');
// confirm that the 'id' variable has been set
if (isset($_GET['id']) && is_numeric($_GET['id'])) {
// get the 'id' variable from the URL
$id = $_GET['id'];
// delete record from database
if ($stmt = $mysqli->prepare("DELETE FROM my_table WHERE id = ? LIMIT 1")) {
$stmt->bind_param("i",$id);
$stmt->execute();
$stmt->close();
} else {
echo "ERROR: could not prepare SQL statement.";
}
$mysqli->close();
// redirect user after delete is successful
header("Location: Dashboard.php");
} else {
// if the 'id' variable isn't set, redirect the user
header("Location: Dashboard.php");
}
There is a similar question MySQLi Prepared Statement not executing
. Basically, you can try running the SQL directly in the database to see if you get any errors. Also confirm that the database user has delete permissions and that the id is stored as an integer in your database.
First I'd suggest you use the $_POST method, you can read more about it GET vs. POST.
Try using bindValue() instead of bindParam(), I believe something else needs to be declared for bindParam() I forget (I'm new at PHP too).

how to insert PHPSESSID into db with PDO?

I am trying to insert $_COOKIE['PHPSESSID'] in db with pdo, but i am having issue, can somebody help out?
here is the db table design : db table name: unregistered_customer_orders
session_id (int)
sel_article_id (varchar, 32)
sel_article_qty(smallint)
sel_article_color(varchar)
sel_article_size(varchar)
order_date(datetime)
HERE IS THE CODE
session_start();
try {
include_once'../includes/connect.inc.php';
$q ="INSERT INTO unregistered_customer_orders SET
session_id = $_COOKIE['PHPSESSID'] ,
sel_article_id = :sel_article_id,
sel_article_qty =:sel_article_qty,
sel_article_color = :sel_article_color,
sel_article_size = :sel_article_size,
order_date = NOW()";
$stm = $pdo->prepare($q);
$stm->bindValue(':sel_article_id', $sel_article_id);
$stm->bindValue(':sel_article_qty', $sel_article_qty);
$stm->bindValue(':sel_article_color', $sel_article_color);
$stm->bindValue(':sel_article_size', $sel_article_size);
$stm->execute();
if ($stm) {
echo "Insert";
exit();
}
else{
echo "Insert failed";
exit();
}
} catch (PDOException $e) {
echo "sth got wrong with the insert".$e->getMessage();
}
Your code has a serious SQL injection problem!
You inject unescaped SQL code into the query - or at least are trying to do so, from the cookie.
The cookie variable should go into the bindValue part just like everything else. Create a new variable name that goes into the prepared statement part, and bind the cookie value to it.
Note that PHP can be configured to use a different name for the session cookie! You don't have to access the $_COOKIE variable after you started the session, you can simply call the session_id() function to get the currently used session id.
Before using session_start(), the configured cookie name can be read by calling session_name(). Don't hardcode the cookie name into your code - it will create hard to debug errors when a new server has a different configuration.

mysql Duplicate error handling

I'm trying to use PHP to enter data from a form. When I try to enter duplicate data a bad message pops like
Something went wrong with this:
INSERT INTO customer VALUES('jamie9422','Jamie Lannister','sept of baelor','jamie#cersei.com',9422222222,0) Duplicate entry 'jamie9422' for key 'PRIMARY' "
Instead, I want to display a clean error message. How can I do that. Here's my code I've written so far...
<?php
include_once "dbConnect.php";
$connection=connectDB();
if(!$connection)
{
die("Couldn't connect to the database");
}
$tempEmail = strpos("{$_POST["email"]}","#");
$customer_id=substr("{$_POST["email"]}",0,$tempEmail).substr("{$_POST["phone"]}",0,4);
//$result=mysqli_query($connection,"select customer_id from customer where customer_id='$customer_id' ");
//echo "customer_id is".$result;
$query = "SELECT * FROM CUSTOMER WHERE CUSTOMER_ID='$customer_id'";
$customer_idcip = $customer_id-1;
echo $customer_idcip;
if ( mysql_query($query)) {
echo "It seems that user is already registered";
} else {
$command = "INSERT INTO customer VALUES('{$customer_id}','{$_POST["name"]}','{$_POST["address"]}','{$_POST["email"]}',{$_POST["phone"]},0)";
$res =$connection->query($command);
if(!$res){
die("<br>Something went wrong with this:{$command}\n{$connection->error}");
}
echo "Welcome ".$_POST["name"]." \nCongratulations on successful Registration. Refill your Wallet here";
//$cutomerRetrival = mysql_query("select from customer where customer_id='$customer_id'");
echo "<br>Please note your customer ID :".$customer_id;
}
/*if($result)
{
echo "Query Fired";
$dupentry = mysqli_num_rows($result);
if($dupentry==1)
{
echo "You are already Registered";
exit;
}
}*/
?>
The error code (number) is 1022.
You can e.g. define a constant for that (so that somebody else in x months has a chance to understand the code) like
define('ER_DUP_KEY', 1022);
and then do something like
if(!$res){
if ( <error code>==ER_DUP_KEY ) {
handleDuplicateEntryError();
}
else {
die("<br>Something went wrong with this:{$command}\n{$connection->error}");
}
}
since I don't know how $res =$connection->query($command); works (and what $connection is I can't tell you exactly how to implement <error code>==ER_DUP_KEY, could be by using mysql_errno.
But it seems to be somehow intermingled with mysql_query($query), i.e. the old, deprecated mysql_* extension and some custom class. You might want to fix that first.... ;-)
see http://docs.php.net/manual/en/mysqlinfo.api.choosing.php
Your code doesn't check for existing record properly
Change
if (mysql_query($query)) {
echo "It seems that user is already registered";
}
to
$result = mysql_query($query);
if (mysql_num_rows($result)) {
echo "It seems that user is already registered";
}
Also, PLEASE do not use $_POST variables without escaping them first, use something like mysql_real_escape_string() to escape each variable passed from the user, otherwise your website will be hacked really fast with SQL Injection.
Make some update into your and then try to get error message 'customer already registered.'
$query = "SELECT * FROM CUSTOMER WHERE CUSTOMER_ID='$customer_id'";
$res= mysql_query($query);
$customer_count = mysql_num_rows($res);
$customer_idcip = $customer_id-1;
echo $customer_idcip;
if ( $customer_count > 0 ) {
echo "It seems that user is already registered";
} else {
...................................
Thank you all.
Actually I was using mysqli API in my connectDB.php file..
Hence I needed to call functions on mysqli.
Instead I was calling mysql. i.e I was creating a new connection, thus the query wasn't getting fired at all.
Changed to mysqli->query($result) that is object oriented style
and it worked fine....
Use Try Catch instead.
try{
$res =$connection->query($command);
}catch(Exception $e){
die( "Write your error appropriate message here");
}

Get all data after linking to other page using $_GET

I'am very glad to haveall of u programmers. I need your help for my code. Below is my code:
-survey.php
<td><center></b><font size="2">Not Complete</center></td></tr>';
While this is the page after I clink link where it GET the user_id.
-page.php
$staffid = (int)$_GET['user_id'];
In page.php, I only get user_id data only. My question is how do I want to get all data from $_GET['user_id'], such as their email, address, etc.
Any help would be much appreciated. Thank you.
In the page you want all the data, page.php, you need to run something like this (In this case a PDO prepared statement, you can do that with mysqli, too):
try {
$connection = new PDO('mysql:host=' . HOST . ';dbname=' . DB , USER_DB, PASS_DB); // replace with your credentials!
$state = $connection->prepare("SELECT * FROM usertable WHERE user_id = :id");
$state->execute(array('id' => $_GET['user_id']));
if ($state->rowCount() > 0) {
list ($username,$email /* catch all the fields you need ,*/ )=$state->fetch(PDO::FETCH_NUM);
}
else {
echo "Nothing found"; }
$state->closeCursor();
unset($state, $connection);
} catch (PDOException $e) {
die('Error!: ' . $e->getMessage() . '<br/>');
}
SIDENOTE:
There seems to be an error in your first line you posted here:
<td><center></b><font size="2">Not Complete</center></td></tr>';
^where does this come from?
passing the id alone cannot get all the fields you want. Instead create a query where you insert the staff id to get the fields you want
$staffid = (int)$_GET['user_id'];
SELECT * FROM users WHERE id= '".$staffid."'
And Run the query.

php mysqli FRUSTRATION

I have to following code:
session_start();
if(isset($_SESSION['Username']))
{
//User has selected auto sign-in re-fill session variables.
$mysqli = new mysqli('****','****','****','****');
if($mysqli->errno)
{
//Error connecting
}
else
{
//No error connecting to database
$stmt = $mysqli->prepare("SELECT Expires FROM Subscribers WHERE UName=?");
$stmt->bind_param('s', $_SESSION['Username']);
$stmt->execute();
$stmt->bind_result($Expires);
$stmt->store_result();
while($row = $stmt->fetch())
{
if($Expires < time())
{
//Deny user
$pageToShow = "Payment";
}
else
{
//Accept
$pageToShow = "Content";
}
}
}
}
else
{ ... }
I am getting the error Fatal error: Call to a member function bind_param() on a non-object in /home/content/42/7401242/html/****/wp-content/themes/****/archive.php on line 15
I just had an error like this about 30min ago on a different page, and I had for gotten the FROM from the sql query, but I have read, re-read, re-checked, every single letter of the code, over and over. I am about to pull all of my hair out...
What am I doing wrong?
That's simple.
You're not handling errors.
And not even asking how to do that.
In your other question they showed you error itself instead of showing you the way how can you see the error yourself.
In the present question the answer is "check your query" which is not too helpful too.
Instead of asking other people to find typos in your queries, you have to ask mysqli to do that. That's way more efficient, especially because there could be another mistake, not in the query but somewhere else.
So, you have to check every database interaction result and translate it into PHP error.
$sql = "SELECT Expires FROM Subscribers WHERE UName=?";
$stmt = $mysqli->prepare($sql) or trigger_error($mysqli->error);
...
$stmt->execute() or trigger_error($mysqli->error);
so, you will immediately know what's going wrong.
The error tells you that your SQL query is returning an empty result.
two things you must do:
check that you are connected to the database properly and that you
have the permissions to access the data in the database
check your query and see if it returns any results in your SQL
database.

Categories