How do I display url [closed] - php

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have a site in which people can click on names and will be redirected to the corresponding URL
id | name | url
1 | facebook | www.fb.com
I have 1,200,000,023 URL I want to display. URLs which loggedin user have not visited.
My signup information are stored in userdb.php like this:
1|username|a84894gf5sag4f684gh68fh45g|email#gmail.com|NA
My display.php is
<?php
mysql_connect('mysql', '1', 'Py');
mysql_select_db('a5803761_add');
$query =mysql_query('select * from addimage order by ID DESC');
while( $row = mysql_fetch_assoc($query) )
{
echo '<div style="min-width:300px;height:100px;border:red 5px;float:left;">'.$row['name'].'</div>';
}
?>

First, you have to store which user visited which url already. This table should have a structure like that:
CREATE TABLE VISITED(ID INT AUTO_INCREMENT,
USER_ID INT,
URL_ID INT,
PRIMARY KEY(ID),
KEY(USER_ID),
KEY(URL_ID));
Then you have to interprep the users' click to store if they visit an url (with jQuery maybe, and send back this with AJAX) or use a redirecter PHP which logs the clicked url and then redirect the user to this.
If you consider the second one, this PHP should be something:
<?php
//You should check here for the URL to be an integer
$res = mysql_query('SELECT url FROM addimage WHERE id='.$url_id.';');
if (mysql_num_rows($res)>0) {
mysql_query('INSERT INTO VISITED VALUES(NULL,'.$_SESSION['logged_in_user_id'].','.$url_id.');');
$row = mysql_fetch_array($res);
Header('Location: http://'.$row[0]);
}
?>
After that, when you list your URLs, you have to check which are the user didn't visit yet:
<?php
mysql_connect('mysql', '1', 'Py');
mysql_select_db('a5803761_add');
$sql = 'select addimage.id, addimage.name, VISITED.USER_ID from addimage ';
$sql .= 'LEFT JOIN VISITED ON (addimage.id = VISITED.URL_ID) ';
$sql .= 'WHERE (VISITED.USER_ID='.$_SESSION['logged_in_user_id'].');';
$query =mysql_query('order by ID DESC');
while( $row = mysql_fetch_assoc($query) )
{
if ($row[2] == 'NULL') {
echo '<div style="min-width:300px;height:100px;border:red 5px;float:left;">'.$row['name'].'</div>';
}
}
?>
But I think it's not a good idea to list such a lot of urls in one HTML, probably the browser will eat up all the memory. Maybe you should do some kind of filter or paging mechanins.
Please consider this code as an example only, and modify it for your needs.
On the other hand, as others suggested, DO NOT use mysql_ extensions, use mysqli or PDO.

I would advise you to use mysqli or PDO. O, and write "http://" into link.

Related

Query with WHERE clause not working using mysqli bind_param() [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I am creating a webservice where I need to get some data from mysql and retrieve it in a mobile app.
I have been trying all day to do a query with a WHERE statement, but no success.
The normal query, without the WHERE is working perfectly though.
Also I went through all the similar questions on stack overflow and other forums, but none is the same problem as mine.
This is my current code:
<?php
$con=mysqli_connect("Hidden credentials");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if ($stmt = $con->prepare("SELECT
team.id as teamId,
team.team_name as teamName,
user.id as userId,
user.username as username,
team_members.role as role
FROM team_members
inner join user on team_members.user_id = user.id
inner join team on team_members.team_id = team.id
where user.id = ?
")) {
$stmt->bind_param("i", $id);
$stmt->execute();
$result = $stmt->get_result();
$resultArray = array();
$tempArray = array();
while($row = $result->fetch_object())
{
$tempArray = $row;
array_push($resultArray, $tempArray);
}
echo json_encode($resultArray);
$stmt->close();
}
?>
If I remove the line where user.id=? it gets the data correctly.
Running the query on phpMyAdmin is everything ok, so it's not any issue on the query.
The variable $id doesn't exist (in your code). If you want to set the variable dynamically you can use $id = $_GET['id'];. This will take the value from the url and put it in the variable!
Your QUERY doesn't work because your variable id doesn't exists (in code what you showing).
Fix: create variable id and put some data to this variable.
For example:
$id = 5;
Or dynamcially:
From URL with GET method:
$id = $_GET['id'];
this allows you to get parameter from URL. But you must set this parameter by link. For example: <a href="index.php?id=5">. By clicking on this a tag you will be redirected to page index.php with parameter id which equals to 5.
From POST method:
for example you have this FORM:
<form method="post">
<input type="number" name="id">
<input type="submit" name="submit">
</form>
after submiting this FORM values will be saved in $_POST. You can access them by $_POST["name"]. In this case $_POST["id"].
$id = $_POST["id"];
From SESSION:
$id = $_SESSION["id"];
but first you have define $_SESSION["id"]. You can access this variable ($_SESSION["id"]) in other pages of your domain.

PHP using $_GET['id'] to display database information [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I'm trying to build a forum with PHP and PDO at the moment and I have a link which takes you to the page for a category with the categories ID in the URL (eg. WEBSITE/category.php?id=1). When I get there, I want to display the name of the category you are looking at using this $_GET information, but it won't seem to do it for me.
Here is what I've got:
<?php
include 'dbconfig.php';
include 'header.php';
$sql = "SELECT cat_id, cat_name, cat_description FROM categories WHERE cat_id = " . $_GET['id'];
$query = $DB_con->prepare($sql);
$query->execute();
$numRows = $query->fetchColumn();
if (!$query) {
echo 'Something went wrong whilst getting the category from the database.';
} else {
if ($numRows == 0) {
echo 'Sorry, this category does not exist';
} else {
while($catRow = $query->fetch(PDO::FETCH_ASSOC)){
echo $catRow['cat_name'];
}
}
}
include 'footer.php';
?>
So as you can see, I have tried to make a while loop that creates an array using PDO::FETCH_ASSOC allowing me to print category details, but when I go to the page nothing shows up except the header.php and the footer.php. There also aren't any errors that come up. Can anybody see what I'm doing wrong? Or let me know if there's information that I have left out. Thanks.
The problem is with $numRows PDOStatement::fetchColumn does not count the rows that are in the result set. There is PDOStatement::rowCount for that.
As for the sql injection, It is not so much the class or functions you use that make it save, but the way you use the functions. To read more about it go here (link was in the top link in related for me)
Applying what we just learned to your code will give us something like this:
$sql = "SELECT cat_id, cat_name, cat_description FROM categories WHERE cat_id = :id"; // Parameterize query to prevent sql injection
$query = $DB_con->prepare($sql);
$query->execute([":id" => $_GET['id']]); // Binding parameter(s), could also be done using bindParam
$results = $query->fetchAll(PDO::FETCH_ASSOC); // For later use
$numRows = $query->rowCount();
if ($query->errorCode() == "00000") { // I don't think that PDOStatement ever fails to be created, so $query would never not be set
echo 'Something went wrong whilst getting the category from the database.';
} else {
if ($numRows == 0) {
echo 'Sorry, this category does not exist';
} else {
foreach ($results as $category){
echo $category['cat_name'];
}
}
}
Note that the way I bind my parameters (in the execute) is my preferred way, not nessesarily the best way

PHPMyAdmin Query error in php #1064 [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
<?php
//GET FACEBOOK LIKE DATA TO FACEBOOK SERVERS
function readFacebookLikes($url) {
$query = "select like_count from link_stat WHERE url ='" . $url ."'";
$s = file_get_contents("https://api.facebook.com/method/fql.query?query=".
urlencode($query)."&format=json");
preg_match("#(\"like_count\"):([0-9]*)#",$s,$ar);
if(isset($ar[2])) return $ar[2]; else return null;
}
mysql_connect('localhost','root','') or die(mysql_error());
mysql_select_db('odrinhasedm') or die(mysql_error());
$query=mysql_query("select nome, url from participacao") or die(mysql_error());
while($res=mysql_fetch_array($query))
{
$likes = "http://[ip]/evento-odrinhas-edm-open-air/".$res['url'];
$links = $res['url'];
$contador = readFacebookLikes($likes);
//echo'<tr><td>'.$res['nome'].'</td><td>'.$contador.'</td></tr>';
$query1 = "UPDATE participacao set likes = $contador WHERE url = $links ";
mysql_query($query1) or die (mysql_error());
}
?>
Why is this query1 not working? (PHPMyAdmin errror #1064)
I have a project that creates a page per user on a form and each page has its own Facebook like system, now I have a way to get that data and show it on a table, but I want to insert that data into my database to sort it. Is it easier to add the values to my db or sort the table directly in php?
I have a query that is working and its pulling the URLs to the PHP file, then I want to create another query to insert the data into the database with "update".
I think url is a string. So you must have quotes around the values:
UPDATE participacao set likes = $contador WHERE url = '$links'

Delete a post based upon an id variable - different user sessions

SOLVED
I have a problem that has been tearing me apart for the last two weeks.
I want to be able to delete a post in my table based upon a given variable. Because of the different user content it's pretty difficult to delete a post that belongs to that certain user.
What I really want to know is how to get that certain ID from $rad on the admin.php to the delete query on perform_remove_time.php. Should I use GET or POST or any other method? I will have "input sanitize" with real_escape_string later on and I'm also aware of mysqli vs mysql. My code isn't pretty please bear with me.
From perform_remove_time.php
<?
$user_id = $_SESSION['user_id'];
$time_id = ($_GET['time_id']);
$sql = "DELETE FROM time WHERE time_id = '$time_id' AND user_id = '$user_id'";
$result = mysql_query($sql);
if($result) {
echo "<h3>Time deleted!</h3>";
header("location:admin.php");
} else {
echo "Something is wrong!";
}
?>
This is where the posts is fetched and displayed - admin.php
$user_id = $_SESSION['user_id'];
$time_id = ($_GET['time_id']);
$sql = "SELECT * FROM time WHERE user_id = '$user_id' ORDER BY time_id DESC";
$result = mysql_db_query("database","$sql") or die (mysql_error());
while ($rad=mysql_fetch_array($result)) {
?>
<?='Work session: '.$rad["time_id"]?> | Time on projekt: <?=$rad["hours"]?> | Delete work session
Also from admin.php further up on the page
if (!isset($_SESSION['user'])) {
header("Location:default.php");
die();
}
From my observation, your delete link in 'admin.php' would not get you to 'perform_remove_time.php' with the right GET parameter (time_id) for your delete code to work.
So i made a little modification to your delete link:
<? echo "<a href='perform_remove_time.php?time_id=".$rad['time_id']."'> | Delete work session</a>"; ?>
That modification would enable your delete link get to 'perform_remove_time.php' with the right GET parameter for it to work
Update
The code snippet from perform_remove_time.php looks fine to me, and would work as long as $time_id and $user_id contains valid values and also if your sql statement is correct. Now, from the code snippet you posted, I discovered that in perform_remove_time.php $time_id would contain nothing because there was no time_id GET parameter in your delete link code | Delete work session, the GET Parameter there is id, so I simply changed id to time_id to get things working.
new delete link code
<? echo "<a href='perform_remove_time.php?time_id=".$rad['time_id']."'> | Delete work session</a>"; ?>

PHP site URL ID please Help!

Please could someone help im building my first website that pulls info from a MySQL table, so far ive successfully managed to connect to the database and pull the information i need.
my website is set up to display a single record from the table, which it is doing however i need some way of changing the URL for each record, so i can link pages to specific records. i have seen on websites like facebook everyones profile ends with a unique number. e.g. http://www.facebook.com/profile.php?id=793636552
Id like to base my ID on the primary key on my table e.g. location_id
ive included my php code so far,
<?php
require "connect.php";
$query = "select * from location limit 1";
$result = #mysql_query($query, $connection)
or die ("Unable to perform query<br>$query");
?>
<?php
while($row= mysql_fetch_array($result))
{
?>
<?php echo $row['image'] ?>
<?php
}
?>
Thanks
Use $_GET to retrieve things from the script's query (aka command line, in a way):
<?php
$id = (intval)$_GET['id']; // force this query parameter to be treated as an integer
$query = "SELECT * FROM location WHERE id={$id};";
$result = mysql_query($query) or die(mysql_error());
if (mysql_num_rows($result) == 0) {
echo 'nothing found';
} else {
$row = mysql_fetch_assoc($result);
echo $row['image'];
}
There are many things to consider if this is your first foray into MsSQL development.
SQL Injection
Someone might INSERT / DELETE, etc things via using your id from your url (be careful!, clean your input)
Leaking data
Someone might request id = 1234924 and you expected id = 12134 (so some sensitive data could be shown, etc;).
Use a light framework
If you haven't looked before, I would suggest something like a framework (CodeIgniter, or CakePHP), mysql calls, connections, validations are all boilerplate code (always have to do them). Best to save time and get into making your app rather than re-inventing the wheel.
Once you have selected the record from the database, you can redirect the user to a different url using the header() function. Example:
header('Location: http://yoursite.com/page.php?id=123');
You would need to create a link to the same (or a new page) with the URL as you desire, and then logic to check for the parameter to pull a certain image...
if you're listing all of them, you could:
echo "" . $row['name'] . ""
This would make the link.. now when they click it, in samepage.php you would want to look for it:
if (isset($_GET['id']) && is_numeric($_GET['id'])) {
//query the db and pull that image..
}
What you are looking for is the query string or get variables. You can access a get variable through php with $_GET['name']. For example:
http://www.facebook.com/profile.php?id=793636552
everything after the ? is the query string. The name of the variable is id, so to access it through your php you would use $_GET['id']. You can build onto these this an & in between the variables. For example:
http://www.facebook.com/profile.php?id=793636552&photo=12345
And here we have $_GET['id'] and $_GET['photo'].
variables can be pulled out of URL's very easily:
www.site.com/index.php?id=12345
we can access the number after id with $_GET['id']
echo $_GET['id'];
outputs:
12345
so if you had a list of records (or images, in your case), you can link to them even easier:
$query = mysql_query(...);
$numrows = mysql_num_rows($query);
for ($num=0;$num<=$numrows;$num++) {
$array = mysql_fetch_array($query);
echo "<a href=\"./index.php?id=". $row['id'] ."\" />Image #". $row['id'] ."</a>";
}
that will display all of your records like so:
Image #1 (links to: http://www.site.com/index.php?id=1)
Image #2 (links to: http://www.site.com/index.php?id=2)
Image #3 (links to: http://www.site.com/index.php?id=3)
...

Categories