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';
?>
Related
I'm self-learning, so pardon my ignorance.
I have 2 SQL tables: user and product, both tables contain "user_id" fields.
I have successfully created a login system that uses email and password fields from the first table (user).
I want to show specific information from the "product" table to the logged-in user. This information should be identified from the user_id field. (user with user_id of 1 should see the product with user_id of 1
login page has:
<?php
session_start();
$message = "";
require_once('account/pdoconnect.php');
if(isset($_POST["login"])) {
if (empty($_POST["email"]) || empty($_POST["password"])) {
$message = '<label>All fields are required</label>';
}
else {
$query = "SELECT * FROM user WHERE email = :email AND password = :password";
$statement = $pdotestconn->prepare($query);
$statement->execute(
array(
'email' => $_POST['email'],
'password' => $_POST['password']
)
);
$count = $statement->rowCount();
if($count > 0) {
$_SESSION["email"] = $_POST["email"];
header("location:account/index.php");
}
else {
$message = '<label>Wrong Email or Password</label>';
}
}
}
?>
Index page has:
<?php session_start();
if(!isset($_SESSION["email"]))
{
header("location:../login.php");
exit;
}
?>
<?php
include("pdoconnect.php");
$id = $_GET['user_id'];
$result = $pdotestconn->prepare("SELECT * FROM product inner join user on
user.user_id = product.user_id");
$result->execute(array($id));
$row = $result->fetch(PDO::FETCH_ASSOC);
?>
Where I insert values with:
<?php
echo $row['amount'];
?>
Problem:
I get the same value in the first row (with user_id = 2) for every user logged in
First it's probably best to store the user id in the session, so in your first source...
if($count > 0) {
$row = $statement->fetch(PDO::FETCH_ASSOC);
$_SESSION["email"] = $_POST["email"];
$_SESSION["userID"] = $row['ID']; // Make sure ID is the column name from the user table
header("location:account/index.php");
}
then to display the data, fetch the user ID from the session...
$id = $_SESSION["userID"];
$result = $pdotestconn->prepare("SELECT * FROM product
WHERE product.user_id =:id");
$result->execute(['id'=> $id]);
$row = $result->fetch(PDO::FETCH_ASSOC);
BTW you don't need to join to the user table if the user_id is in the product table
You don't have any parameter on your query.
<?php
include("pdoconnect.php");
$id = $_GET['user_id'];
$result = $pdotestconn->prepare("SELECT * FROM product inner join user on
user.user_id = product.user_id WHERE product.user_id =:id");
$result ->bindParam(':id', $id, PDO::PARAM_INT);
$result ->execute();
$row = $result->fetch(PDO::FETCH_ASSOC);
?>
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);
im using php to insert into the review table.ive given the variables $email, $starcount, $bookid fixed values for now just to test the file. the $res query checks to see if there is a row with that book id and email in it. if theres not The $sql query inserts it, and then the $nex query loops through taking any starcount columns where the book column = $book.
if i change the the email at the top of the file it should insert into the new info database and pull out the new and existing starcount, but it does not post, it just returns the already existing starcount. i dont understand why its not working .... im using the array to return to my file.
<?php
mysql_connect("localhost","root","");
mysql_select_db("FunReads");
$email = "sd";
$starcount = "2";
$bookid = "5";
$res = mysql_query("SELECT * FROM Review WHERE book_id='$bookid' AND user_email='$email'");
if (mysql_num_rows($res) != 0) {
$array[]= array("starcount" => "already entered");
} else {
$sql = mysql_query("INSERT INTO Review(book_id,starcount,user_email) values('.$bookid.','.$starcount.','.$email')");
$nex = mysql_query("SELECT * FROM Review WHERE book_id='$bookid'");
while($row = mysql_fetch_array($nex)){
$star = $row["starcount"];
$array[] = array("starcount" => $star);
}
}
echo json_encode($array);
//echo "[{"name":"n1","city":"NY"},{"name":"n2","city":"Paris"}, ...]
?>
It seems to me "book_id" in "Review" table is primary key, as you have tried to add it multiple time, system shows the error duplicate key. Check the error & post it. Also check whether insert query is working or not.
you should not pass the primary key value manually
try this it will helps you
<?php
mysql_connect("localhost","root","");
mysql_select_db("FunReads");
$starcount="2";
$email = "vinodh#gmail.com";
$res=mysql_query("SELECT * FROM Review WHERE email ='$email'");
if(mysql_num_rows($res)!=0){
$array[]= array("starcount" => "already entered");
}else{
$sql=mysql_query("INSERT INTO Review (starcount,email) values('.$starcount.','.$email')");
$nex=mysql_query("SELECT * FROM Review WHERE email='$email'");
while($row=mysql_fetch_array($nex)){
$star = $row["starcount"];
$array[] = array("starcount" => $star);
}
}
echo json_encode($array);
?>
I just updated your code and it is working fine for me.
<?php
mysql_connect("localhost","user","");
mysql_select_db("xyz");
$email = "hari#gmail.com";
$starcount = "2";
$bookid = "5";
$sql = "SELECT * FROM review WHERE book_id='$bookid' AND user_email='$email'";
$res = mysql_query($sql);
if (mysql_num_rows($res) != 0) {
$array[]= array("starcount" => "already entered");
} else {
$sql = "INSERT INTO review(book_id,starcount,user_email) values('$bookid','$starcount','$email')";
$sql = mysql_query($sql);
$nex = mysql_query("SELECT * FROM review WHERE book_id='$bookid'");
while($row = mysql_fetch_array($nex)){
$star = $row["starcount"];
$array[] = array("starcount" => $star);
}
}
echo json_encode($array);
sample output :
[{"starcount":"2"},{"starcount":"3"},{"starcount":"1"},{"starcount":"2"},{"starcount":"1"}]
I updated the insert query, please try to update the same and test.
<?php require_once("Database.php"); ?>
<?php
if (isset($_POST['submit'])) {
$name = $_POST['username'];
$sql = "SELECT * FROM list ";
$query = mysqli_query($conn, $sql);
$blacklist = mysqli_fetch_array($query);
// BLACKLISTS
if (in_array($name, $blacklist)) {
die("Sorry! $name is not found");
}
else {
$api1 = file_get_contents("API");
echo "$name's ip is: $api1";
}
}
?>
So I've been at this for hours and I have decided that I need help. So what I am trying to do is simply us the if statement to create a blacklist using the strings or names I have saved in my database. The problem is it only black lists the first id or name and it wont accept or acknowledge the other names in my database. I was wondering if anyone maybe could give me a suggestion as to how I could write the code so I use all the names in said database instead of only the first one.
Also tried this and i still dont get the die statement.
<?php require_once("Database.php"); ?>
<?php
if (isset($_POST['submit'])) {
$name = $_POST['username'];
$sql = 'SELECT count(*) FROM list WHERE names = ?';
$name = $_POST['username'];
if ($stmt = mysqli_prepare($conn, $sql)) {
mysqli_stmt_bind_param($stmt, "s", $name);
mysqli_stmt_bind_result($stmt, $count);
mysqli_stmt_fetch($stmt);
if ($count) die("Sorry! $name is not found");// ITS BLACKLISTED
mysqli_stmt_close($stmt);
} else {
$api1 = file_get_contents("api");
echo "$name's ip is: $api1";
}
}
?>
I think the problem is you are returning * which will return all fields from the table. You only want to return an array of names and check those.
Ideally you want an array from the list table that looks like this:
//['tom', 'jim', 'sam', 'bob']
I've just checked the docs for mysql_fetch_array here and it returns a multidimensional array. You're probably getting something like this back:
[
[
'id' => 1,
'name' => 'tom'
],
[
'id' => 2,
'name' => 'jim'
]
]
In the array above you don't have a list of names therefore name is not in the array.
As #Ziumin mentions we need to get the "name" key out of the array so I've updated the in_array part below:
<?php require_once("Database.php"); ?>
<?php
if (isset($_POST['submit'])) {
$name = $_POST['username'];
$sql = "SELECT name FROM list";
$query = mysqli_query($conn, $sql);
$blacklist = mysqli_fetch_array($query);
// BLACKLISTS
//get all the names from all the rows into one array
$nameList = array_column($blacklist, 'name');
//check that the posted name is in this list
if (in_array($name, $nameList)) {
die("Sorry! $name is not found");
}
else {
$api1 = file_get_contents("API");
echo "$name's ip is: $api1";
}
}
?>
Let me answer this question. As far as you have a database with blacklisted users, and you want to check if some username is blacklisted I suggest you to make this check without fetching all the blacklist table (which can be quite big).
$sql = 'SELECT count(*) FROM list WHERE names = ?';
$name = $_POST['username'];
if ($stmt = mysqli_prepare($conn, $sql)) {
mysqli_stmt_bind_param($stmt, "s", $name);
mysqli_stmt_bind_result($stmt, $count);
mysqli_stmt_fetch($stmt);
if ($count) die("Sorry! $name is not found");// ITS BLACKLISTED
mysqli_stmt_close($stmt);
$api1 = file_get_contents("api");
echo "$name's ip is: $api1";
}
<?php error_reporting(0); ?>
<?php require_once("Database.php"); ?>
<?php
if (isset($_POST['submit'])) {
$name = $_POST['username'];
$sql = "SELECT * FROM username WHERE username = '$name' ";
$query = mysqli_query($conn, $sql);
$blacklist = mysqli_fetch_array($query);
// BLACKLISTS
if (in_array($name, $blacklist)) {
die("Sorry! $name is not found");
}
else {
$api1 = file_get_contents("API");
echo "$name's ip is: $api1";
}
}
?>
So what i did is i added WHERE username ='$name' to $sql in order for it to accurately see what exactly i want to be extracted from the database. i disabled the error reporting because it was giving me a null parameter for the in array, ill enable it when i keep disabling, but disable it when i display it to the public.
I am learning PHP and MySQL and am having one or two problems with the build.
I have an HTML form that the user inputs their details and the details of a dog. The script then checks the database for the users name and the dogs name. If both exist within the database then the user_ID on the dog table is changed to change the ownership. If the User does not exist then the users details will be inputted into the database and the ownership changed.
I did have the whole thing working but was not using bindParam for the collection from the form and was advised this would be a much better option. This is where the fun started. I am now able to count the rows on the table using the script below, however, I am not able to use the WHERE clause within the SELECT query. I have tried placing "WHERE name_first = :name_first" but this failed with a "Parameter not defined" error.
I need to be able to user both the first and last name of the user to be able to select that users ID from the database.
I also have an other question in regards to the use of prepared statements. If I use the statement at the top of the script to SELECT from the database and all the forms inputs are bound to $STH, how do I then run a different query, for instance how do I INSERT the user details into the database using the same binds?
Could someone please have a look at the script and tell me where I am going wrong please?
<?php
/***mysql username***/
$user = 'root';
/***mysql password***/
$pass = '';
if ($_SERVER['REQUEST_METHOD'] == "POST") {
try {
$DBH = new PDO('mysql:host=localhost;dbname=kennel_cert;', $user, $pass);
$DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$DBH->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
//Queries
$sql1 = "SELECT user_ID FROM user_details";
$sql2 = "SELECT dog_ID FROM dog_details";
$STH = $DBH->prepare("SELECT * FROM user_details"); //Needs a WHERE clause to work
//var_export($STH);
//User details form
$STH->bindParam(':name_first', $_POST['name_first']);
$STH->bindParam(':name_last', $_POST['name_last']);
$STH->bindParam(':email', $_POST['email']);
$STH->bindParam(':telephone', $_POST['telephone']);
$STH->bindParam(':name_number', $_POST['name_number']);
$STH->bindParam(':street', $_POST['street']);
$STH->bindParam(':city', $_POST['city']);
$STH->bindParam(':county', $_POST['county']);
$STH->bindParam(':postcode', $_POST['postcode']);
//Dog details form
$STH->bindParam(':dog_reg', $_POST['dog_reg']);
$STH->bindParam(':name', $_POST['name']);
$STH->bindParam(':microchip', $_POST['microchip']);
$STH->bindParam(':gender', $_POST['gender']);
$STH->bindParam(':day', $_POST['day']);
$STH->bindParam(':month', $_POST['month']);
$STH->bindParam(':year', $_POST['year']);
$STH->execute(); //Execute the select script
//Use this to count the users - However without the WHERE it is counting all users not the one submitted into the form
if($STH->rowCount() > 0) {
echo "Exists <br>"; }
else {
echo "Doesn't exist <br>"; }
//var_export($userQuery); //Displays the contents of the query for testing
//Find if user exists in database - Again another way of counting the total but not the one inputed into the form
$userResult = $DBH->query($sql1);
if ($userResult !== false) {
$count = $userResult->rowCount();
echo 'Number of users: '.$count. '<br>';
foreach($userResult as $row) {
echo $row['user_ID'].'<br>';
}
}
//Find if dog exists in database - Again another way of counting the total but not the one inputed into the form
$dogResult = $DBH->query($sql2);
if ($dogResult !== false) {
$count = $dogResult->rowCount();
echo 'Number of dogs: '.$count. '<br>';
foreach($dogResult as $row) {
echo $row['dog_ID'].'<br>';
}
}
} catch (PDOException $e) {
echo $e->getMessage();
}
//echo "<p>Data submitted successfully</p>";
}
//Disconnect from the server
$DBH = null;
?>
OK so I have changed the query to look like this:
$sql = "SELECT user_ID
FROM user_details
WHERE name_first = :name_first
AND name_last = :name_last";
$STH = $DBH->prepare($sql);
When I run this I get this error:
PDOStatement::__set_state(array( 'queryString' => 'SELECT user_ID FROM user_details WHERE name_first = :name_first AND name_last = :name_last', ))
SQLSTATE[HY093]: Invalid parameter number: parameter was not defined
I am completely lost, I am going round in circle and can not find anything that is helping me to solve this.
I did have the script running as I stated using this setup, however, I was told to use the bindParam for the form and this is killing both the script and me.
<?php
/***mysql username***/
$user = 'root';
/***mysql password***/
$pass = '';
if ($_SERVER['REQUEST_METHOD'] == "POST") {
try {
$DBH = new PDO('mysql:host=localhost;dbname=kennel_cert;', $user, $pass);
$DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$DBH->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
//Queries
$userQuery = $DBH->query("SELECT user_ID FROM user_details WHERE name_first = '$first' AND name_last = '$last'"); //Checks if the user exists in the database
$dogQuery = $DBH->query("SELECT dog_ID FROM dog_details WHERE dog_ID = '$dog_reg' AND name = '$name' AND gender = '$gender'");
//User details form
$first = $_POST['name_first'];
$last = $_POST['name_last'];
$email = $_POST['email'];
$telephone = $_POST['telephone'];
$name_number = $_POST['name_number'];
$street = $_POST['street'];
$city = $_POST['city'];
$county = $_POST['county'];
$postcode = $_POST['postcode'];
//Dog details form
$dog_reg = $_POST['dog_reg'];
$name = $_POST['name'];
$microchip = $_POST['microchip'];
$gender = $_POST['gender'];
$day = $_POST['day'];
$month = $_POST['month'];
$year = $_POST['year'];
$u = ""; //Variable for counting users
$d = ""; //Variable for counting dogs
//var_export($userQuery); //Displays the contents of the query for testing
//Find if user exists in database
foreach($userQuery as $row1) { //Count the number of users in the database
$u++;
}
//Find if dog exists in database
foreach($dogQuery as $row2) { //Count the number of dogs in the database
$d++;
}
//The echos are for testing purposes
echo "Dog ID is: ".$row2['dog_ID']."<br>"; //Finds the ID of the dog and displays it
echo "User ID is: ".$row1['user_ID']."<br>"; //Finds the ID of the user and displays it
$newUserID = $row1['user_ID']; //Store the ID for future use
$newDogID = $row2['dog_ID']; //Store the ID for future use
//Perform if both user and dog exist
if ($u > 0 && $d > 0) { //If both the user and the dog exist in the database change the owner of the dog
echo "Both Match"; //Confirm both exist
$q = $DBH->prepare("UPDATE dog_details SET user_ID = '$newUserID' WHERE dog_ID = '$newDogID'"); //update the table to change ownership
$q->execute(); //Execute the change
}
// Perform if only dog exists
elseif ($u == 0 && $d > 0) { //If the user does not exist but the dog does.
echo "Dog matches but user does not exist"; //Confirm what exists
//Insert user details into user_details table and set the foreign user_ID key in the dog_details table
$q1 = $DBH->prepare("INSERT INTO user_details (name_first,name_last,email,telephone,name_number,street,city,county,postcode) VALUES ('$first','$last','$email','$telephone','$name_number','$street','$city','$county','$postcode')");
$q1->execute();
echo "<br>Insert complete<br>";*/
}
elseif ($u > 0 && $d == 0) {
echo "The dog does not exist - this is a problem";
//Form needs returning with values and asks user to check details
}
elseif ($u == 0 && $d == 0) {
echo "Both don't match";
}
} catch (PDOException $e) {
echo $e->getMessage();
}
//echo "<p>Data submitted successfully</p>";
}
//Disconnect from the server
$DBH = null;
?>
Check the manual you need to put the placeholders in the sql before binding parameters:
$query = "SELECT * FROM user_details
WHERE name_first = :name_first
AND name_last = :name_last
AND email = :email
etc...";
$STH = $DBH->prepare($query);