I'm building a simple bug tracking tool.
When you create a new project, all the info you fill in in the form, gets stored in the database.
When you create the new project you get redirected to a unique project page.
On top of the page it shows the name of the project, but it's not the name of the project I just created, it always shows the name of the first project in the MySQL table.
How can I show the name of the project I just created?
With this query I retrieve the data from the database.
$query = "SELECT CONCAT(name)
AS name FROM projects";
$result = #mysql_query ($query)
With this I show the project name, but it always shows the name of the first record in the table.
<?php
if ($row = mysql_fetch_array ($result))
echo '<h5>' . $row['name'] . '</h5>';
?>
It isn't yet SQL Injection prove and is far from complete... But I'm really struggling with this problem.
You need an AUTO_INCREMENT field on your table for a unique identifier (at least, you really should). Then you can do something like this:
<?php
$sql = new MySQLi('localhost', 'root', '', 'database');
$sql->query('INSERT INTO `projects` (`name`) VALUES ("Test Project");');
$projectID = $sql->insert_id; // Returns the auto_increment field value of the last insert query performed
// So this assumes you have a field in your table called "id" in this example
$res = $sql->query('SELECT CONCAT(`name`) AS `name` FROM `projects` WHERE `id` = '.$projectID.';');
if ($row = $res->fetch_assoc()) {
echo '<h5>'.$row['name'].'</h5>';
}
?>
Since you were calling for a redirect to the unique project page, you should have something like this: header("Location: project.php?id=$projectID");
Then, on project.php, you can attempt to fetch the project with the query above, only your query's WHERE clause should be something like:
'`id` = '.intval($_GET['id']).';'
Technically, you could pass all the project info along to the next page as a request or a session cookie and save yourself a query altogether. Just make sure you keep the id handy so it's easy to update the record.
Try using ORDER BY.
$query = "SELECT CONCAT(name)
AS name FROM projects ORDER BY id DESC";
This would show the most recent project (assuming you have an ID column).
However, a much better way is to have an ID variable on the page.
$query = "SELECT CONCAT(name)
AS name FROM projects WHERE id=?";
Related
Hey I want to create like system in php But I am facing some problem on it ...
How can I create Like system that allow only one like per one user??
This is my code
<?php
if(isset($_POST['like'])){
$q = "SELECT * FROM likes WHERE `username` = '".$_SESSION['recieveruser']."'";
$r = mysqli_query($con, $q);
$count = mysqli_num_rows($r);
if ($count == "0") {
$q1 = "INSERT INTO likes (`username`, `likecount`)VALUES('".$_SESSION['recieveruser']."', '1')";
$result1 = mysqli_query($con, $q1);
} else {
while($row = mysqli_fetch_array($r)) {
$liked = $row['likecount'];
}
$likeus = ++$liked;
$q2 = "UPDATE likes SET likecount='".$likeus."' WHERE username = '".$_SESSION['recieveruser']."'";
$result2 = mysqli_query($con, $q2);
}
}
give me some suggestions
I want only one like per user
In this code every user can give Many likes to another user but I want only one like per one user and I want to display the name of the user who gave like if it's possible
This is only user like code...
I created simliar like system on my website. In my likes table, I had these columns:
Id of comment, that has been liked
Id of user who liked
Id of like (for removal)
When user clicked like, I inserted new row into likes table, with two known values. ID of like was autoincremented.
To show number of likes, I filtered by id of comment and grouped by users id (just to be sure). The number was obtained using count.
select count(*) from likes where comment_id = 666 group by user_id;
Even if you let user insert multiple times, the like counts only as one. But best would be to check, if current user already liked and dont let him do that. For this task, insert on duplicate key update could be used, to spare if exists db request (select).
You should not use the code you posted above. First of all, your code is vulnerable to SQL-Injections and therefore you should use Prepared Statements (https://www.php.net/manual/de/mysqli.quickstart.prepared-statements.php). Second, $_SESSION variables are depricated (https://www.php.net/manual/en/reserved.variables.session.php).
Lets assume you want users only to be able to like a post once. Then, instead of the column likecount you would need a post-id which uniquely identifies the post.
Define the combination post-id and username as a primary key in your database.
Now your code just have to check whether you find the username with the according post-id in the table likes.
In case you do not find the username with the according post-id in the table, you have to INSERT the username and the post-id
I would save the id of each user in a session for get later name ... in my login system. I would do that on each login.
But the problem: If i Select more columns with the sql i cant fetch a single column.
How i can fetch one column even tough i selected more columns in the sql.
I tried something like that:
$sth->fetch(PDO::FETCH_ASSOC)['password']
But it isnĀ“t working on my code:
$sth = $X['dbh']->prepare("SELECT `password` `id` FROM `users` WHERE `uid` = :uid; ");
if (! $sth->execute(array(
':uid' => $X['param']['uid'],
))) {
//check for right name, passwort ...
}
How i can fetch one column even tough i selected more columns in the sql.
Nohow.
Either select only one column, or fetch all that you have selected. Otherwise it would make no sense to select.
And after fetching an array, you can access its members all right.
$user = $sth->fetch(PDO::FETCH_ASSOC);
$pass = $user['password'];
then later in the code you can use $user['id'] as well.
I have a php script that displays records from a database. It's probably not the best script, as I'm very new to php.
I've added an additional column in my table and would like to keep a count in that column to show me how many times each of the records have been viewed.
Heres the part of the code I think i need to add the code to... if i need to post the entire page i will, but i just figured i could add the line to this part.
//Get the details from previous page
$SelectedCounty = $_POST["result"];
//set variable for next SEARCH
$option = '';
// Get the county names from database - no duplicates - Order A-Z
$query = "SELECT DISTINCT tradingCounty FROM offers ORDER BY tradingCounty ASC";
// execute the query, $result will hold all of the Counties in an array
$result = mysqli_query($con,$query);
while($row = mysqli_fetch_array($result)) {
$option .="<option>" . $row['tradingCounty'] . "</option>";
}
}
the new column name is 'views' and i just want to add 1 to it each time a record from the database is viewed.
any help greatly appreciated.
Add a new field views to the table.
When, user views the page, fire the SQL.
$query = "UPDATE offers SET views = views + 1";
mysqli_query($con,"update offers set views = views + 1");
If you have added the column, it probably has a NULL value. Either set the value to 0, by doing:
update offers
set views = 0;
Or use:
update offers
set views = coalesce(views, 0) + 1;
You can change your code with this rewritten code assuming that your Table has a column views (datatype int).
//Get the details from previous page
$SelectedCounty = $_POST["result"];
//set variable for next SEARCH
$option = '';
// Get the county names from database - no duplicates - Order A-Z
$query = "SELECT DISTINCT tradingCounty FROM offers ORDER BY tradingCounty ASC";
// execute the query, $result will hold all of the Counties in an array
$result = mysqli_query($con,$query);
if($result){
$query2 = "UPDATE offers SET views=views+1;
mysqli_query($con,$query2);
}
while($row = mysqli_fetch_array($result)) {
$option .="<option>" . $row['tradingCounty'] . "</option>";
}
Or if you need to track the view counts for individual records, you need to modify your code a bit. And probably you need to add one more field in the database for eg. id (datatype int) which can distinguish between different records.
Please clear your problem properly.
As far as i have analysed your code it brings out the following case.
There are different records for tradingConty, and whenever a user views that particular record(one of the tradingCounty record) by clicking that or any other action specified, the php script is set to increament the view count for that particular entry(we can get that by id) in the database.
If thats the scenario, we can easily generate a code accordingly.
I have a form that submits super basic information, just a new name (the name gets assigned a unique id). What I am trying to make happen is when the user submits the name it gets submitted into the database and they get redirected to a new page card.php where they can add more specific information. However the unique id associated with the row that was just submitted needs to follow in the URL (id=$id)
$query = "INSERT INTO name VALUES(NULL, '$name')";
mysqli_query($conn, $query);
$query2 = "SELECT * FROM name ORDER BY id DESC LIMIT 1";
$result = mysqli_query($conn, $query2);
while($row = mysqli_fetch_array($result)) {
$id = $row['id'];
}
header("Location: http://localhost/card.php?id=$id");
Process
addName.php -> user submits new name -> add to database -> redirect to card.php WITH unique id value of name that is just submitted
1.) Is there a way to retain the id of the row just submitted? In the fluke chance 2 or more people submit at the same time the second query of getting the last row inserted into the database will return the wrong row id
2). Having a while loop return 1 piece of info seems like a shitty way to do things, this might be the most basic of shit but i cant seem to return the 1 piece of data without doing this
Try using mysqli_insert_id which returns the AUTO_INCREMENT ID generated from the previous INSERT operation.
$query = "INSERT INTO name VALUES(NULL, '$name')";
mysqli_query($conn, $query);
$id = mysqli_insert_id();
header("Location: http://localhost/card.php?id=$id");
Reference: http://us1.php.net/manual/en/function.mysql-insert-id.php
You could use the mysqli function to retrieve the last inserted id (check mysqli_insert_id as suggested in a comment), but I wouldn't recommend you using the user id in the URL, people can try to get in, using other ids
also you can use the php function to generate a custom is check out: uniqid
I have a database listed as $db under mysqli. This database is contains into two tables, I listed them below as table and table2 (just for this example). Table2's rows requires an id from table. This is fine, but there might be a problem adding the columns into table2 thus requiring a rollback routine. However, it doesn't seem to be working.
I started with turning off the auto-commit. I then tried to put in the rollback command even though I am using the die command to signal a failure. As far as I am concerned the transaction could be blasted into oblivion in mid operation and the database should still be stable. So I am not sure what is going on here unless the database is completely ignoring the fact that I am trying to turn off auto-commit.
The basic structure of my code is listed below:
function problem($str)
{
global $db;
mysqli_rollback($db);
die($str);
}
mysqli_autocommit($db,false);
//Basic check if exists
$sqlstr = "SELECT * FROM table WHERE name = '$name';";
$r = mysqli_query($db,$sqlstr);
if (mysqli_num_rows($r)>0){problem("A row already exists under that id");}
//Insert the row
$sqlstr = "INSERT INTO table (name,v1,v2,v3) VALUES ('$name','$v1','$v2','$v3');";
$r = mysqli_query($db,$sqlstr);
if (!$r){problem("Could not insert into the table. $sqlstr");}
//Get the generated id part 1
$sqlstr = "SELECT id FROM table WHERE name = '$name';";
$r = mysqli_query($db,$sqlstr);
if (!$r){problem("Could not add into the table. $sqlstr");}
//Get the generated id part 2
$row = mysqli_fetch_assoc($r);
$eid = $row['id'];
//A simple loop
$count = count($questions);
for ($i=1;i<=$count;$i++)
{
//This is where it typically could die.
$r = mysqli_query($db,"INSERT INTO table2 VALUES (...);");
if (!$r){problem("Could not add to the table2. $sqlstr");}
}
mysqli_commit($db);
Is there something I am missing? I tried to follow the examples I found for the auto-commit as closely as I could.
Transactions only work if the table engine supports them, e.g. InnoDB.