how to fetch data from table using php and mysql - php

I am trying to fetch an email from a particular row or based on the id_code from people table... That is, say I enter a id_code = 456, if the id code exists the email of that specific id_code has to be retrieved, and generate a token number and insert the token number into the people table. After the token is generated and inserted, a URL link has to be sent with the token and an id.
How would i do that since i am a beginner, can someone tell me where I am going wrong?
Here is what I did so far:
<?php
error_reporting(1);
session_start();
include 'includes/db.php';
include 'includes/token.php';
//global
$id_code = strtoupper(trim($_POST['id_code']));
if ($_POST["Submit"] == "Submit") {
$sql = "SELECT * FROM people WHERE id_code = :id_code";
$stmt = $pdo->prepare($sql);
$stmt->bindValue(':id_code', $id_code);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if (!empty($_POST['id_code'])) {
$sql = "SELECT email FROM people WHERE id_code = $id_code";
$stmt = $pdo->prepare($sql);
$stmt->bindValue(':id_code', $id_code);
$stmt->execute();
$result2 = $stmt->fetch(PDO::FETCH_ASSOC);
} else {
//echo "<br/>Validated: FALSE<br/>"; die();
echo 'You are not Registered..Please Contact support';
}
}
?>

As far as I can see $id_code is not defined. The value you might want to use is stored in $_POST['id_code'] so you should do something like $id_code = $_POST['id_code']; in front of your IF condition, otherwise $id_code is undefined.
Update: you already did it with $ccode, use this for the binding and it should work.
$stmt->bindValue(':id_code', $id_code);
replaced by
$stmt->bindValue(':id_code', $ccode);
UPDATE
please try the following code and post the result of the var_dump():
<?php
error_reporting(1);
session_start();
include 'includes/db.php';
include 'includes/token.php';
//global
$id_code = strtoupper(trim($_POST['id_code']));
var_dump("ID: ".$id_code);
if ($_POST["Submit"] == "Submit") {
$sql = "SELECT * FROM people WHERE id_code = :id_code";
$stmt = $pdo->prepare($sql);
$stmt->bindValue(':id_code', $id_code);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
var_dump("Result: ".$result);
if (!empty($_POST['id_code'])) {
$sql = "SELECT email FROM people WHERE id_code = $id_code";
$stmt = $pdo->prepare($sql);
$stmt->bindValue(':id_code', $id_code);
$stmt->execute();
$result2 = $stmt->fetch(PDO::FETCH_ASSOC);
var_dump("Result2: ".$result2);
} else {
//echo "<br/>Validated: FALSE<br/>"; die();
echo 'You are not Registered..Please Contact support';
}
}
?>
Do you get any output from your script?

Use correct binding for second query too (you have assigned $id_code)
if (!empty($_POST['id_code'])) {
$sql = "SELECT email FROM people WHERE id_code = :id_code";
$stmt = $pdo->prepare($sql);
$stmt->bindValue(':id_code', $id_code);
echo $email;
$stmt = $pdo->prepare($sql);

Related

PHP Mysql how to retrieve product by category

When I enter category name manually, I'm able to get its product but when I insert a variable to like the code, I get success but data is empty.
Connection file:
<?php
//cnnection.php
$server = "localhost";
$user = "root";
$password = "";
$db = "db_ecommerce_shoes";
$connect = new mysqli($server,$user,$password,$db);
Main script:
<?php
include '../connection.php';
With this, request is successful but data is empty
$name= 'name';
$sql = "SELECT * FROM tb_shoes
WHERE
catName ='$name'
";
With this, request is successful, data is loaded successful
$sql = "SELECT * FROM tb_shoes
WHERE
catName ='Ladies Shoe'
";
$result = $connect->query($sql);
if($result) {
$data = array();
while($row = $result->fetch_assoc()) {
$data[] = $row;
}
echo json_encode(array(
"success"=>true,
"data"=> $data,
));
} else {
echo json_encode(array(
"success"=>false,
));
}
Any other way of doing this will be much appreciated.
Any other way of doing this will be much appreciated
You should never be directly concatenating variables into the SQL query making it vulnerable to SQL injections. That is a major security issue.
Read about a simple and easy to understand version of prepared statements here.
In your case, try this out
$category = "Ladies Shoe"
$statement = $connect->prepare("SELECT * FROM tb_shoes WHERE catName = ? ")
$statement ->bind_param("s", $category);
$statement ->execute();
$result = $statement ->get_result();
Then you can loop through the results as above. Check if it works!
Try to assign
$name = 'Ladies Shoe';
$sql = "SELECT * FROM tb_shoes
WHERE
catName ='$name'
";
Does this work?

query returns nothing php

I attempt to get the result of a very simple query with the function query but nothing appears. If I execute the query in PHPMyAdmin, with the same data, I have a result.
There is my code :
$sql = "SELECT * FROM users WHERE email='$email'";
$response = $conn->query($conn, $sql);
The $conn variable is correct, I did an Insert with that.
$response is null. I can do an echo and there is nothing.
What can I do to solve this problem ? What can I check ?
Thank you very much.
You don't need to pass connection in query.
Solution:
$sql = "SELECT * FROM users WHERE email='$email'";
$response = $conn->query($sql);
while($res = $response->fetch_array()){
$name=$res['nameofuser']; //just an example
}
echo $name;
Real solution (prepare stmt):
$sql = "SELECT * FROM users WHERE email=?";
$response = $conn->prepare($sql);
$response->bind_param('s',$email);
if(!$response->execute()){
echo "Error query: " . $response->error . ".";
}
$result=$response->get_result();
while($res = $result->fetch_array()){
$name=$res['nameofuser']; //just an example
}
echo $name;
'Tips' add to real solution check if query is done.
After execute query . fetch the results
$stmt = $conn->prepare( "SELECT * FROM users WHERE email= ? ");
$stmt->bind_param("s", $email);
$stmt->execute();
$result = $stmt->get_result();
if($result->num_rows === 0) exit('No rows');
while($row = $result->fetch_assoc()) {
// your code
}

mysqli_real_escape_string with mysqli_num_rows in php

My problem count sql .
<input name='d_n[]'>
<input name='d_n[]'>
php page
post value Adam's
foreach($ds_director as $key => $director){
// my problem here //
$DnumSql = "SELECT * FROM list WHERE ds_name = ?";
$stmt = $con -> prepare($DnumSql);
$stmt -> bind_param('s',$director);
$stmt -> execute();
$Dnum = $stmt->num_rows;
echo "$Dnum"; // result again '0'
/////////////
if($Dnum == 0){
$director_sql = mysqli_real_escape_string($con,ucwords($director));
$Dsql = "INSERT INTO movie_ds (ds_m_name, ds_name, ds_status) VALUES ('$director_sql', '$m_name', 'yönetmen')";
$Dquery = mysqli_query($con,$Dsql);
if($Dquery){
echo "<p style='color:green'>good</p>";
}else{
echo mysqli_error($con);
}
}else{
echo "<p style='color:red;'>not save</p>";
}
}
Because of this problem the same value is recorded
UPDATE PROBLEM editted = array input
Better to use prepare statement for this. It will automatically escape your string and prevent from sql injection
$sql = 'SELECT * FROM list WHERE d_n =?';
$stmt =$con->prepare($sql);
$stmt->bind_param('s', $_POST['d_n']);
$stmt->execute();
$numrows = $stmt->num_rows;

How can I manage to change a field in my SQL DB, after i checked a value before?

So. I Have this Table. I'm trying to update the value of the Availability filed from 0 to 1 after I checked that a code, for example 1234 exist in my DB.
Here is the code what I wrote:
<?php
if(isset($_POST['kodi'])) {
try {
$sql = "SELECT codevalue FROM codes WHERE codevalue = ? AND availability = 0";
$stmt = $dbh->prepare($sql);
$stmt->bindParam(1, $_POST['kodi']);
$stmt->execute(); }
catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();}
if($stmt->rowCount() > 0){
header('Location: http://mysite/userpage');
$q = "UPDATE codes SET availability = '1' WHERE codevalue= ?";
$stmt->bindParam(1, $_POST['kodi']);
$stmt = $dbh->prepare($q);
$stmt->execute($q);} else {
echo "Code Not Exists"; }
The part with the $dbh variable:
$dbh = new PDO("mysql:host=$hostname;dbname=x",$username,$password);
The HTML:
<form action ="thispage.php" method ="POST">
<input name="kodi" type="text" class="form-control" placeholder="Enter Code" aria-describedby="basic-addon1">
</form>
When I'm trying it, it redirects in my userpage but the field availability is still 0.
if(isset($_POST['kodi'])) {
$sql = "SELECT codevalue FROM codes WHERE codevalue = ? AND availability = 0";
$stmt = $dbh->prepare($sql);
$stmt->bindParam(1, $_POST['kodi']);
$stmt->execute();
$result = $stmt->fetchAll();
if(!empty($result)) {
header('Location: http://mysite/userpage');
$q = "UPDATE codes SET availability = '1' WHERE codevalue= ? AND availability = 0";
$stmt->bindParam(1, $_POST['kodi']);
$stmt = $dbh->prepare($q);
$stmt->execute($q);
} else {
echo "Code Not Exists";
}
}

How can I get the column of my sql database with $_GET?

I am successfull in getting the id as this is a page called shirt.php?id=2 which is a template to display a specific shirt based on its id. That works but in my database i have a column named "name" and that has the name of the shirt so "shirt2". How can I echo or grab this based on the current id of the shirt. is the code below too redundant? How can I simplify this?
<?php
require 'inc/header.php';
$streamId = (isset($_GET['id']) ? $_GET['id']:NULL);
if ($streamId) {
$sql = 'SELECT * FROM streams WHERE id = :id';
$query = $pdo->prepare($sql);
$query->execute(array(':id' => $streamId));
$listStreamEach = $query->fetchAll(PDO::FETCH_ASSOC);
}else {
echo "not working";
}
$streamIdName = (isset($_GET['name']) ? $_GET['name']:NULL);
if ($streamIdName) {
$sql = 'SELECT * FROM streams WHERE name = :name';
$query = $pdo->prepare($sql);
$query->execute(array(':name' => $streamIdName));
$listStreamEach1 = $query->fetchAll(PDO::FETCH_ASSOC);
print_r($listStreamEach1);
}else {
echo "not working";
}
?>
<?php
require 'inc/footer.php';
?>

Categories