for the past few i have been trying to get the ID of the event a user registers to inside the URL in order to show all details in that event.
Ive tried Get data from MySQL database by specific id in url
But it doesnt seem to work for what i am trying to do.
Or i am doing it wrong, i got more progress with this code
<?php
if(isset($_SESSION['user_id'])){
$userid = $_SESSION['user_id'];
$QUERY3 = mysqli_query($DB, "SELECT * FROM `registration` WHERE `user_id`='$userid'");
$GETEVENTZ = mysqli_fetch_array($QUERY3);
}
?>
<?php
$eventid = $GETEVENTZ['event_id'];
echo '<li> <i class="icon icon-list"></i><span>Leaderboards</span> </li>'
?>
Just to try and get the ID in but im getting a normal page
with the url being
leaderboard.php?eventid=
and no ID after, no errors are popping up, page and everything loads, just doesnt add ID. cant seem to find the issue
Since your are using: $GETEVENTZ = mysqli_fetch_array($QUERY3);
Your code is expecting an array return. So you cannot just simply use:
$eventid = $GETEVENTZ['event_id'];
A quick fix can be $eventid = $GETEVENTZ[0]['event_id'] if you are expecting a single row return from your query.
But the proper way to handle this is to use mysqli_fetch_row() instead.
You can also dump the result set first to debug what your query is returning.
The session super global is not the one to use. Use $_GET to get information from the URL.
<?php
if(isset($GET['user_id'])){
$userid = $GET['user_id'];
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query3 = "SELECT * FROM `registration` WHERE `user_id`=?";
if($stmt = $mysqli->prepare($query3)) {
$stmt->bind_param("s", $userid);
$stmt->execut();
$result = $stmt->get_result();
}
}
?>
<?php
// this section does not demonstrate getting the value from $result
// I will update answer later, must research mysqli more.
echo '<li> <i class="icon icon-list"></i><span>Leaderboards</span> </li>'
?>
Disclaimer: I don't use mysqli, so my answer is a best guess on that portion. Be sure to research how to properly use prepared statements at http://php.net/manual/en/mysqli.prepare.php
Try this, Hopefully it will work.
<?php
$DB = new mysqli("localhost", "my_user", "my_password", "my_db");
/* check connection */
if ($DB->connect_errno) {
printf("Connect failed: %s\n", $DB->connect_error);
exit();
}
if(isset($_SESSION['user_id'])) {
$userid = $_SESSION['user_id'];
$QUERY3 = "SELECT * FROM registration WHERE user_id='$userid'";
$result = $DB->query($QUERY3);
$GETEVENTZ = $result->fetch_array(MYSQLI_ASSOC);
$eventid = $GETEVENTZ['event_id'];
printf ("%s", $eventid);
}
echo '<li> <i class="icon icon-list"></i><span>Leaderboards</span> </li>';
?>
Answer -
Session id was labeled (userid) instead of (user_id)
then after i stated if user session has user ID then print the event ID and then show page, which then it redirects me to the correct page with ID of event
<?php
if(isset($_SESSION['user_id'])){
$GETUSRID = $_SESSION['user_id'];
$GETRANKD = mysqli_query($DB, "SELECT * FROM `registrations` WHERE `user_id`='$GETUSRID'");
$GETRD = mysqli_fetch_assoc($GETRANKD);
$eventid = $GETRD['event_id'];
printf ("%s", $eventid);
}
echo '<li> <i class="icon icon-list"></i><span>Leaderboards</span> </li>';
Related
I have a form handler (I believe that is the correct terminology) called insert.php, this is used to post form data to a MySQL database on localhost. I have different tables each containing a single record and would like to choose which table the data goes to. I could duplicate the insert.php file for each table but that seems messy. How do I choose which table the data goes to via post?
current insert.php:
<?php
require_once 'login.php';
$con=mysqli_connect($hh,$un,$pw,$db);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
echo 'Connected successfully';
$sql = "UPDATE PiBQ_Temp SET reqdTemp = '$_POST[setTemp]' WHERE tempKey = 1";
mysqli_query($con,$sql);
echo "1 record added";
header ('location: index.php');
mysql_close($con)
?>
What I think is needed for the $sql = variable:
$sql = "UPDATE '$_POST[myTable]' SET '$_POST[myField]' = '$_POST[myValue]' WHERE tableKey = 1"
My html is this:
<form action="insert.php" method="post">
<input type="text" name="myField" value="<?= $myValue ?>"/>
<input type="submit" value="Submit" />
what html should I be using to feed my revised insert.php file above, if that is correct? Thanks.
try this format
$sql = "UPDATE `".$_POST['myTable']."` SET `".$_POST['myField']."` = '".$_POST['myValue']."' WHERE `tableKey` = 1";
or
$mysqli = new mysqli("host", "user", "password", "db");
$stmt = $mysqli->prepare("UPDATE `".$mysqli->real_escape_string(str_replace(" ", "", strtolower($_POST['myTable'])))."` SET `".$mysqli->real_escape_string(str_replace(" ", "", strtolower($_POST['myField'])))."` = ? WHERE `tableKey` = 1");
$stmt->bind_param("s",$_POST['myValue']);
$stmt->execute();
You should use prepared statement instead
There's some wider practices that could be improve, but based on your current code/structure, I would use something like this:
<?php
require_once 'login.php';
try {
$con = new mysqli("host", "user", "password", "db");
} catch (mysqli_sql_exception $e) {
echo "Failed to connect to MySQL: ".$e;
}
$table = (isset($_POST['myTable'])) ? $_POST['myTable'] : null;
$reqdTemp = (isset($_POST['setTemp'])) ? $_POST['setTemp'] : null;
$tempKey = (isset($_POST['setKey'])) ? $_POST['setKey'] : null;
switch($table) {
case "thisTable":
$qry = "UPDATE `thisTable` SET thisField = ? WHERE thisKey = ?";
break;
case "thatTable":
$qry = "UPDATE `thatTable` SET thisField = ? WHERE thisKey = ?";
break;
case "anotherTable":
$qry = "UPDATE `anotherTable` SET thisField = ? WHERE thisKey = ?";
break;
default:
// do something?
break;
}
$stmt = $conn->prepare($qry);
$stmt->bind_param("si", $reqdTemp, $tempKey);
$stmt->execute();
if(!$stmt->execute()) {
echo $stmt->error;
}
else {
echo "1 record added";
}
header ('location: index.php');
mysql_close($con)
?>
Two things to note: The switch statement allows you to provide a different query based on the table name, but it assumes that the same structure is in place (i.e. update String Where Integer).
I've also assumed the thisKey is posted too, as 'setKey'.
Secondly, prepared statements.
This is more of a hint, rather than a whole solution, and you probably need to tidy it up and make it work for you outside of my assumptions
When I run the page with an empty database, it will insert the data correctly. When I run the page again, it displays there is already an ID in the database, but it inserts it anyway. Not sure how or why but I've tried every combination of booleans inside the if statements and cant get it to chooch correctly.
//pass in an ID to compare:
function checkOrderID($orderID) {
//Connect to the database:
$mysqli = new mysqli("localhost", "root", "", "price");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
//Ask the database for some sweet, sweet data:
$stmt1 = "SELECT orderID FROM orders";
$result = $mysqli->query($stmt1);
//flag (we want to believe that there are no similar IDS so lets make it true):
$flag = true;
//while we got some data, display that shit
while ($row = $result->fetch_assoc()) {
//asign data to variable:
$rowOrderID = $row['orderID'];
//Does it match? if it does set the flag to false so it doesnt get inserted.
if ($rowOrderID == $orderID) {
echo "Row ID" . $row["orderID"] . " Passed ID: " . $orderID . "<br>";
echo "This order is already in the database" . "<br>";
$flag = false;
}
}
//hand the flag over to who ever needs it
return flag;
}
.
if (checkOrderID($orderID) == true) {
//some mysql insert logic here
}
Why are you making this complicated. just do something like this:
$con=mysqli_connect("localhost","root","","price");
$check_query = mysqli_query($con,"SELECT * FROM orders WHERE orderID = $orderID");
if (mysqli_num_rows($check_query) == 0) {
//mysql insert logic here
}
(Noted of course you are going to have your connection logic as well)
Note: You are using Mysqli in object oriented manner but in this example i have not used object oriented manner of DB connection. The connection variable $con must be passed to mysqli_query() method.
Also... random side note, but it's generally a good idea to have a password for your root mysql user.
Here better and short, but please try to use DB connection globally not inside your mothod and try to use prepared statements. But except those you can use following code.
//pass in an ID to compare:
function checkOrderID($orderID) {
//Connect to the database: I suggest use global DB connection
$mysqli = new mysqli("localhost", "root", "", "price");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
//gets recodrs based on $orderID passed to this method
$stmt1 = "SELECT * FROM orders where orderID=$orderID"; //Try to use prepared statement
$result = $mysqli->query($stmt1);
//Store number of rows found
$row_count = $result->num_rows;
if($row_count>0){
return true;
}
else{
return false;
}
}
I am very new to PHP and have been trying to find out where I am going wrong in the statement below:
if(empty($_POST['datepickere']))
{
$purchaseorderdate = mysql_query("SELECT purchaseorderDMY FROM purchaseorders WHERE Servicetag = '$_POST[stage]'");
}
else
{
$purchaseorderdate = "$_POST[datepickere]";
}
The else statement executes just fine however the if statement does not save the output of the query to "$purchaseorderdate"
Can someone please give me a pointer as to where I am going wrong? Sorry if there is syntax error or something like that.
datepickere = A field in my HTML form.
purchaseorderDMY = The field in the DB where the datepickere is saved
when a new content is added
Start by making a mysqli connection (this is right out the docs):
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
Now update your code snippet with more exact copies from the documentation:
if (empty($_POST['datepickere'])) {
$myvar = mysqli_real_escape_string($link, $_POST['stage']);
$result = mysqli_query("SELECT purchaseorderDMY FROM purchaseorders WHERE Servicetag = '$myvar'");
$row = mysqli_fetch_assoc($result);
$purchaseorderdate = $row['purchaseorderDMY'];
} else {
// you don't need to quote a variable to use it
// but it must be quoted starting at PHP4 (a decade ago)
$purchaseorderdate = $_POST['datepickere'];
}
I am really new on php and I am trying to create my own php shop cart. After some research I got myself stuck in the "function products" below because seems to me it is not working properly. I expect to see the names of my products on my mysql database but it is not showing anything. My user name is noivaemd_etalhes, I am using my correct password and my database name is noivaemd_cart and I created on this database the table called Products with my list of products available. Can anybody help me to figure out what am I doing wrong on the php instructions below???? I appreciate any help.
<?php
session_start();
$page = 'index.php';
function products() {
$con = mysqli_connect("localhost", "noivaemd_etalhes", "mypassword", "noivaemd_cart") or die (mysqli_error());
$res = mysqli_query($con, "SELECT id, name, description, price FROM Products WHERE quantity > 0 ORDER BY id DESC");
if (mysqli_num_rows($res)==0) {
echo "<font family=verdana><font size=6px><font color= #90882C><font style=normal><font variant= normal><br>No products available<br></font>";
}
else{
while($get_row = mysqli_fetch_assoc($res)) {
echo '<p>'.$res['name'].'</p>';
}
}
}
?>
This code:
while ($get_row = mysqli_fetch_assoc($res)) {
echo '<p>'.$res['name'].'</p>';
}
Should be:
while ($get_row = mysqli_fetch_assoc($res)) {
echo '<p>'.$get_row ['name'].'</p>';
}
As your title ask also tell how to check if the mysqli database connection is successful you can use the below code:
$con = mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
Reference link: http://www.php.net/manual/en/function.mysqli-connect.php
It's not good practice to connect to your database directly in your code. Open another file, and save it has 'dbconnect.php' or whatever you choose to name it. Save it in the same root.
Inside DB connect, you connect to the database like this:
<?php
$mysql_host = "localhost";
$mysql_user = "username";
$mysql_pass = "";
$mysql_dbname = "Products";
$conn_error = "Sorry, Could Not Connect";
if(!#mysql_connect($mysql_host,$mysql_user,$mysql_pass)||!#mysql_select_db($mysql_dbname)){
die($conn_error);
}
?>
In your index.php, inside your php tags, write 'require "dbconnect.php";'.
Then you get your values like this:
$InfoQuery = " SELECT id, product, name FROM table_name WHERE quantity>0 ORDER BY id DESC";
$Info = mysql_query($InfoQuery);
while($InfoRow=mysql_fetch_assoc($Info)){echo "<p>".$InfoRow['id']."<br>". $InfoRow['product']"."<br>". $InfoRow['name']."</p>";}
Edit: What you did wrong is in your while loop, you fetched the table data from $res when it should be fetched from $get_row
I am trying to acces my connection variable while I run a while loop, yet when I try to call a function, it bogus out on me and PHP gives me the so called boolean error when I try to prepare my statement within the function.
I debugged it to the point that I know my variable $CategorieId is being pushed on and I do get a array return of $con when I do a print_r in the function itself. However when I try to acces it when I prepare my statement, it just returns me a boolean, thus creating the error in the dropdown, not being able to fill it up.
The setup is as followed.
dbControl.php
$con = mysqli_connect('localhost','root','','jellysite') or die("Error " . mysqli_error($con));
function OpenConnection(){
global $con;
if (!$con){
die('Er kan geen verbinding met de server of met de database worden gemaakt!');
}
}
functionControl.php
function dropdownBlogtypeFilledin($con,$CategorieId){
echo "<select name='categorie' class='dropdown form-control'>";
$sql = "SELECT categorieId, categorieNaam
FROM categorie";
$stmt1 = mysqli_prepare($con, $sql);
mysqli_stmt_execute($stmt1);
mysqli_stmt_bind_result($stmt1,$categorieId,$categorieNaam);
while (mysqli_stmt_fetch($stmt1)){
echo "<option value='".$categorieId."'.";
if( $categorieId == $CategorieId){
echo "selected='selected'";
}
echo ">".$categorieNaam."</option>";
}
echo "</select>";
}
Blogedit.php
<?php
require_once '../db/dbControl.php';
require_once '../db/functionControl.php';
session_start();
OpenConnection();
$id = $_SESSION['user'];
?>
// some html up to the while loop
<?php
$a = $_GET['a'];
$sql = "SELECT blog.blogId,
blog.blogTitel,
blog.blogCategorieId,
blog.blogSynopsis,
blog.blogInhoud
FROM blog
WHERE blog.blogId = ? ";
$stmt1 = mysqli_prepare($con, $sql);
mysqli_stmt_bind_param($stmt1,'i',$a);
mysqli_stmt_execute($stmt1);
mysqli_stmt_bind_result($stmt1, $blogId, $Titel, $CategorieId, $Synopsis, $Inhoud );
while (mysqli_stmt_fetch($stmt1)){
$Synopsis = str_replace('\r\n','', $Synopsis);
$Inhoud = str_replace('\r\n','', $Inhoud);
?>
// again some HTML
<?php dropdownBlogtypeFilledIn($con,$CategorieId); ?>
// guess what, more html!
<?php
}
?>
Does anyone know how I can solve it? I tried it with the global variable (the OpenConnection() function) but it didn't seem to work.
Edit
I confirm it has indeed to do with the $con variable. I tested it by defining the $con variable again in the function, and it printed perfectly what I wanted. Its a bad solutions. I just prefer to have it defined once.
The weird thing is that it happens only when i put it in a while loop. I have a create form which is exactly the same, except there is no while loop, since I create it all from scratch and there is no PHP involved on that part. I have there a dropdown function as well, which also requires the $con variable, but there it works. I really think it has to do with the while loop.
I solved it for now by creating a new instance of the connection variable before i initiated the prepared statement of the page retrieving the information.
<?php
$connection = $con;
$a = $_GET['a'];
$sql = "SELECT blog.blogId,
blog.blogTitel,
blog.blogCategorieId,
blog.blogSynopsis,
blog.blogInhoud
FROM blog
WHERE blog.blogId = ? ";
mysqli_stmt_init($con);
$stmt1 = mysqli_prepare($con, $sql);
mysqli_stmt_bind_param($stmt1,'i',$a);
mysqli_stmt_execute($stmt1);
mysqli_stmt_bind_result($stmt1, $blogId, $Titel, $CategorieId, $Synopsis, $Inhoud );
mysqli_stmt_store_result($stmt1);
while (mysqli_stmt_fetch($stmt1)){
$Synopsis = str_replace('\r\n','', $Synopsis);
$Inhoud = str_replace('\r\n','', $Inhoud);
<?php dropdownBlogtypeFilledIn($connection ,$CategorieId); ?>
?>
With the variable $connection I could initiate the function that required the connection details within the while call. I am not sure if there is a cleaner option here, but indeed I read somewhere that I couldn't use the same connection variable if I am already using it in a prepared statement. Appearantly I cannot ride this one the same connection variable, and that seemed to be the problem. I will look into this and hope I dont have to write a while bunch of connection variables whenever I have multiple dropdowns for example that pull information from the database.