I'm trying to update my tables with a total number of uses when a function is called. What I need to do is grab the former number of uses, and add one. I have a pretty good general idea how to go about this, but I don't quite know how to get unique ID's with their respective uses. This is what I have so far...
<?php
$query = $conn->query('select name, uses from users');
$i = 0;
while($r = $query->fetch(PDO::FETCH_OBJ)){
$name[$i] = $r->name;
$uses[$i] = $r->uses;
$i = $i+1;
}
if(isset($_POST['mName']))
{
$mName = urldecode($_POST['mName']);
$mUses = $uses + 1;
"UPDATE users
SET uses=:uses WHERE name=:name";
$stmt = $conn->prepare($sqlUPDATE);
$stmt->bindParam(':uses', $mUses);
$stmt->bindParam(':name', $mName);
$stmt->execute();
?>
I can see my issue is that I'm assigning the uses variable to an array, I don't know how to get it specific to the username. Is this a simple SQL query I'm missing?
You can store the data in an array called $uses with the key being the user name and the value being the number of uses. Then if you detect a POST with the mName parameter set, you can reference your $uses array with that name and get the number of uses, and add 1.
<?php
$query = $conn->query('select name, uses from users');
while($r = $query->fetch(PDO::FETCH_OBJ)){
$uses[$r->name] = $r->uses;
}
if(isset($_POST['mName'])) {
$mName = urldecode($_POST['mName']);
$mUses = $uses[$mName] + 1;
$sqlUPDATE = "UPDATE users SET uses=:uses WHERE name=:name";
$stmt = $conn->prepare($sqlUPDATE);
$stmt->bindParam(':uses', $mUses);
$stmt->bindParam(':name', $mName);
$stmt->execute();
}
?>
Though there is no error checking and handling in here. If there happens to be a POST with mName and that name doesn't exist, nothing will update, but nothing will insert for new users. Also, instead of using a name, it would be better to use an id for the user if possible.
Related
I want to Increment an integer in every time +1. Now my code just at first time work after that don't work it does not move to number 2.At first time I can see number 1 in my table but that number do not Increment at second time.
PHP code:
<?php
include 'connt.php';
$Id = $_POST['Id'];
$sql = "UPDATE student SET Posts =? WHERE Id=?" ;
$stmt = $con->prepare($sql);
$Posts =+1;
$stmt->bind_param("ss",$Posts,$Id);
$stmt->execute();
$result = $stmt->get_result();
$stmt->close();
?>
Your $Posts is never set. Incrementing it will always leave it at 1. You don't need to read values or increment in PHP, you can do it right in your query:
<?php
include 'connt.php';
$Id = $_POST['Id'];
$sql = "UPDATE student SET Posts = Posts+1 WHERE Id=?" ;
$stmt = $con->prepare($sql);
$stmt->bind_param("s",$Id);
$stmt->execute();
$result = $stmt->get_result();
$stmt->close();
You can simply use $Posts++ to increment your variable.
Your mistaken here,
$Posts =+1;
You probably meant something like this,
$Posts++;
// Or,
$Posts += 1;
Edit:
Hey You dont even have $Post defined in the first place !
With this code (if this is all the code), your $Posts variable is always 1.
You should first read the number of posts from the database, then increment it by one and then update it to the new value.
<?php
$sql = "SELECT * FROM team;";
$result = mysqli_query($conn, $sql );
$row = mysqli_fetch_row($result);
$teamname = $row[1];
echo $teamname;
Consider table in DB consists of 10 names from 1-10. That will be displayed on the screen as usually (using retrieving), but the problem is when I click any name from 1-10 displaying on the screen that should open a new page by displaying only the particular name I selected.
I tried this but, all the values are displaying.
First, add to your mysql table a column called "ID" to associate a number to each name.
After you can direct the user to your page like this
Name n.1 // etc..
so you can take the id of your name using GET and display to your page only that name
(Always use Prepared Statement even when it is not strictly necessary)
PHP script
$name_id = $_GET['id'];
// connect to your db
$stmt = $db->prepare("SELECT * FROM team WHERE ID = ?");
$stmt->bind_param("s",$name_id);
$stmt->execute();
$result = $stmt->get_result()->fetch_assoc();
echo $result['name'];
if you need anything else, comment below.
I am trying to get a piece of data from my database but would like to only get one cell using the PDO statement if this is possible.
Below is a screenshot of the table
The table name is called heating
I am trying to get the data from column called 'garage' and row id = 3
I have tried many ways but keep failing. The following is what I have so far but only returns the column name garage for some reason.
I am using the following which gives me the name garage
$room = 'garage';
require_once "connect.php";
$sql = 'SELECT :name FROM heating WHERE id = 3';
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':name', $room);
$stmt->execute();
$sw = $stmt->fetch();
echo $sw[0];
If I do the following I gives me the correct outcome but I would like to replace garage with a variable
$sql = 'SELECT garage FROM heating WHERE id = 3';
$stmt = $pdo->prepare($sql);
$stmt->execute();
$sw = $stmt->fetch();
echo $sw[0];
You can create a white list of your column names and use it to select the right column. You can check the column against a white list with the help of in_array. The third parameter is very important as it checks that string is a string. You can only then safely concatenate the SQL with your PHP variables using PHP concatenation operator. For the good measure, the column names should be enclosed in backticks `, in case any of your column names is a reserved word or contains special characters.
$whiteListOfHeating = [
'keyName',
'den',
'WC1',
'hallway',
'garage'
];
$room = 'garage';
if (in_array($room, $whiteListOfHeating, true)) {
$sql = 'SELECT `'.$room.'` FROM heating WHERE id = 3';
$stmt = $pdo->prepare($sql);
// ...
} else {
echo 'Invalid column name specified!';
}
Sometimes simplest solutions are best.
require_once "connect.php";
$room = 'garage';
$sql = 'SELECT * FROM heating WHERE id = ?';
$stmt = $pdo->prepare($sql);
$stmt->execute([3]);
$sw = $stmt->fetch();
echo $sw[$room];
Besides, every time you need such a functionality, in means that most likely your database structure is wrong. A room should be a row, not column
require_once "connect.php";
$room = 'garage';
$sql = 'SELECT value FROM heating_room WHERE heating_id=3 and room = ?';
$stmt = $pdo->prepare($sql);
$stmt->execute([$room]);
$sw = $stmt->fetchColumn();
echo $sw;
will make it straight
]i'm completely out of idea's as to why the code below does not return the value. I have 2 sql tables that related to one another. Within a class i have the following method, and within the scope of that method all is well. The var dump shows the correct data. The following code is stated in class.php.
public function getId($username, $password) {
if (isset($_SESSION['username'])) {
$sql = "SELECT person_id FROM user WHERE username = ?";
$stmt = $this->dbh->prepare($sql);
$stmt->bindParam(1, $_SESSION['username']);
$stmt->execute();
$id = $stmt->fetch(PDO::FETCH_NUM);
$id = $id[0];
}
ELSE {
echo "Failed to retreive person_id";
}
var_dump($id);
return $id[0];
}
However when i return that value to the showinfo.php which is the main document and state the following:
$user_id = $id[0];
var_dump($user_id);
Then the var dump echoes "NULL". And I need it for the follwing method which is also in class.php.
public function showInfo($user_id) {
$sql = "SELECT * FROM person WHERE person_id = ?";
$stmt = $this->dbh->prepare($sql);
$stmt->bindParam(1, $user_id);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
foreach ($result as $row) {
echo "<pre>".print_r ($row, true)."</pre>";
}
}
Could anybody be so kind as to show me ways to get this done?
Many thanks in advance for your time and effort in helping me.
I'm guessing you are trying to access the field with the index [0] twice.
Maybe try to return just $id and then access [0] on the outer class.
My PHP is a bit rusty and I don't have access to test right now, but don't you need single quotes around the question mark so it goes to SQL quoted?
i.e.
$sql = "SELECT * FROM person WHERE person_id = '?'";
or
$stmt->bindParam(1, "'" + $_SESSION['username'] + "'");
(but not both!)
so that SQL sees
SELECT * FROM person WHERE person_id = 'MyVal'
instead of
SELECT * FROM person WHERE person_id = MyVal
which it would interpret as a column name
You don't show where the method is called.
You tried this in showinfo.php:
$user_id = $id[0];
Shouldn't this be...
$user_id = getId('someusername', 'somepassword')
Or something similar? Sorry this isn't an answer, but I can't comment.
I'm building a simple bug tracking tool.
You can create new projects, when you create a project you have to fill in a form, that form posts to project.class.php (which is this code)
$name = $_POST['name'];
$descr = $_POST['description'];
$leader = $_POST['leader'];
$email = $_POST['email'];
$sql="INSERT INTO projects (name, description, leader, email, registration_date)
VALUES ('$name', '$descr', '$leader', '$email', NOW())";
$result = mysql_real_escape_string($sql);
$result = mysql_query($sql);
if($result){
header('Location: ../projectpage.php?id='.mysql_insert_id());
}
else {
echo "There is something wrong. Try again later.";
}
mysql_close();
(It's not yet sql injection prove, far from complete...)
Eventually you get redirected to the unique project page, which is linked to the id that is stored in the MySQL db. I want to show the name of that project on the page, but it always shows the name of the first project in the database.
(here I select the data from the MySQL db.)
$query = 'SELECT CONCAT(name)
AS name FROM projects';
$result = mysql_real_escape_string($query);
$result = mysql_query ($query);
(here I show the name of the project on my page, but it's always the name of the first project in the MySQL db)
<?php
if ($row = mysql_fetch_array ($result))
echo '<h5>' . $row['name'] . '</h5>';
?>
How can I show the name of the right project? The one that is linked with the id?
Do I have the use WHERE .... ?
Yes, You have to use the WHERE to specify which project You want to get. I'm also not sure why are You using CONCAT function when You want to get only one project.
Other important thing is that You have to use mysql_real_escape_string() function on parameters before You put them in the query string. And use apropriate functions for specific type of data You receive.
So Your statement for getting the project should look like this:
SELECT name FROM projects WHERE id = ' . intval($_GET['id'])
Also when before You use the mysql_fetch_assoc() function, check if there are any records in the result with
if(mysql_num_rows($result) > 0)
{
$project = mysql_fetch_assoc($result);
/* $project['name'] */
}
try this
// first get the id, if from the url use $_GET['id']
$id = "2";
$query = "SELECT `name` FROM `projects` WHERE `id`='".intval($id). "'";
$result = mysql_query(mysql_real_escape_string($query));
use mysql_fetch_row, here you'll not have to loop through each record, just returns single row
// if you want to fetch single record from db
// then use mysql_fetch_row()
$row = mysql_fetch_row($result);
if($row) {
echo '<h5>'.$row[0].'</h5>';
}
$row[0] indicates the first field mentioned in your select query, here its name
The might be of assistance:
Your are currently assing a query string parameter projectpage.php?id=
When you access the page the sql must pick up and filter on the query string parameter like this:
$query = 'SELECT CONCAT(name) AS name FROM projects WHERE projectid ='. $_GET["id"];
$result = mysql_real_escape_string($query);
$result = mysql_query ($query);
Also maybe move mysql_insert_id() to right after assigning the result just to be safe.
$result = mysql_query($sql);
$insertId = mysql_insert_id();
Then when you assign it to the querystring just use the parameter and also the
header('Location: ../projectpage.php?id='.$insertId);