I have a database "test" the rows are username, category and testnr.
I want to use php to cross out any buttons/links on my website that user A has already done. For example username: userA finished testnr:1, so the link test1 in category A gets a line through. The following is as far as I got- (I am sorry, I am a beginner).
However, it would be terribly inefficient. I would have to "if" call for every category and, more annoyingly, testnr in each category. I also would need a next $text everytime, since otherwise every button would be crossed off.
There has to be a better way to do it, but I can not think of anything.
$curuser = $membersite->UserName();
$con = mysqli_connect("$host", "$username", "$password","$db_name");
$sql = "SELECT * FROM test WHERE user='$curuser'";
$text = "";
if ( !mysqli_query( $con,$sql ) ) {
die('Error: ' . mysqli_error($con));
}
$results = mysqli_query( $con, $sql );
while( $row = mysqli_fetch_array( $results ) ) {
$category = $row['category'];
$tnr = $row['testnr'];
if( $category = "Categname" && $tnr = 1 ) {
$text="style='text-decoration:line-through'";
}
}
mysqli_close( $con );
Problem is in your if case!!!
change this
if( $category = "Categname" && $tnr = 1 ) {
to
if( $category == "Categname" && $tnr == 1 ) {
You are assigning the values instead of checking!!! thats why all the links get line-through. See this ref
Related
I am trying to pull dynamic content from a database based on the wildcard subdomain.
Please see the code below.
<?php
$data = $_GET['get'];
$data = addslashes(str_replace('-',' ',$data));
$town_result = $database->getData("select * from nationwide where town = '$data' ");
if( is_object( $town_result ) )
{
$area = $town_result->fetch_assoc();
}
else
{
$region_result = $database->getData("select * from nationwide where region = '$data' ");
if( !is_object( $region_result ) ) {
header('Location: http://example.com');
}
$area = $region_result->fetch_assoc();
$area['town'] = $area['region'];
}
?>
I have tried changing = '$data' "); to LIKE '%" . $data . "%'"); but this only pulls the first row in my database.
You can review how to use fetch_assoc to get associative records.
https://www.php.net/manual/en/mysqli-result.fetch-assoc.php
You can print $area, then you can verify either array count is 1 or more than 1.
Or best way, you can print sql query and run directly in your db.
This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
mysqli_query() expects at least 2 parameters, 1 given in? [duplicate]
(3 answers)
Closed 4 years ago.
I wanted to create a search bar, Final.php is a display page for every event the user has inputted into the database but I want to add a search bar to query the list to find the result they want faster (the event names and four scores for each team). I don't understand where I have gone wrong, I hope someone can help.
<?php
$con = mysqli_connect("localhost", "id5052875_signuplogin", "Meganruby2") or die("cannot connect");
mysqli_select_db($con, "id5052875_signuplogin") or die ("couldnt connect");
$output = '';
//collect
if (isset($_POST['search'])) {
$searchq = $_POST['search'];
$searchq = preg_replace("#[^0-9a-z]#i","",$searchq);
print("$searchq");
$query = mysqli_query($con, "SELECT * FROM event WHERE event name LIKE '%$searchq%'") or die("could not search");
$count = mysqli_num_rows($query);
echo($searchq);
if($count == 0 ) {
$output = 'There was no search';
}else {
while($row = mysqli_fetch_array($query)) {
$event = $row['event name'];
$num1 = $row['Score1'];
$num2 = $row['Score2'];
$num3 = $row['Score3'];
$num4 = $row['Score4'];
$output .= '<div> '.$event.' '.$num1.' '.$num2.' '.$num3.' '.$num4.'</div>';
}
}
}
?>
<form action="Final.php" method="post">
<input type = "text" name = "search" placeholder = "search for event.."/>
<input type = "submit" value = "search"/>
</form>
Your first condition, change
if ( isset( $_POST['event'] ) ) { to if ( isset( $_POST['search'] ) ) {
and
$searchq = $_POST['search']; to $searchq = $_POST['search'];
The name of the search text input is 'search', but for some reason, you are looking for event.
Also, please not that you are taking direct user input and inserting it into a DB query. Please be careful of SQL injection. This is a common question to check and learn more about preventing it.
I have tried to get a cleaner URL by adding a .htaccess file to my directory. However I have stumbled upon a small problem which I haven't been able to figure out yet how to solve. I provide an opportunity for my members to post content on my website. When posting the content, the title is saved and modified to be used to get a cleaner URL. For example
/dir/post.php?id=362 with the title [Hello friends] becomes ->
/dir/Hello-friends
My problem is how can I prevent that the same URL gets produced over and over again. I want that the following URLs with the same title, to get something added to it, like a number. For example
/dir/Hello-friends (The first post)
/dir/Hello-friends-2 (The second post, but here a number is added).
This is my php code
$conn = new mysqli($servername, $username, $password, $dbname);
if (mysqli_connect_error()) {
die("Database connection failed: " . mysqli_connect_error());
}
function php_slug($string)
{
$slug = preg_replace('/[^a-z0-9-]+/', '-', trim(strtolower($string)));
return $slug;
}
$title = mysqli_real_escape_string($conn,$title1);
$text1 = mysqli_real_escape_string($conn,$text0);
$text2 = mysqli_real_escape_string($conn,$text00);
$text3 = mysqli_real_escape_string($conn,$text000);
$text4 = mysqli_real_escape_string($conn,$text0000);
$text5 = mysqli_real_escape_string($conn,$text00000);
$text6 = mysqli_real_escape_string($conn,$text000000);
$pid = $_POST['pid'];
$post_title = $title;
$post_title = htmlentities($title);
$sql_titel = "SELECT post_title FROM posts WHERE title = '$title'";
$result_titel = mysqli_query($con, $sql_titel);
$resultsFound = mysqli_num_rows($result_titel);
if ($resultsFound > 0) {
$resultsFound++;
$post_title .= '-'.$resultsFound;
}
$sql = "INSERT INTO posts (title, text1, text2, text3, text4, text5, text6, post_title, pid)
VALUES ('$title', '$text1', '$text2', '$text3', '$text4', '$text5', '$text6', '".php_slug($post_title)."', '$pid')";
if ($conn->query($sql) === TRUE) {
echo "<script>alert('controlling post...!')</script>";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
If you want to add a random number:
if($_POST['submit']) {
$post_title = $title;
$post_title = htmlentities($title);
$sql_titel = "SELECT post_title FROM posts WHERE post_title = '$post_title'";
$result_titel = mysqli_query($con, $sql_titel);
if(mysqli_num_rows($result_titel) > 0) {
$post_title = $post_title . '-' . mt_rand(1, 1000);
}
}
A simple extension to your code is to use the number of rows returned, like this:
if($_POST['submit']) {
$post_title = htmlentities($title);
// !!! You should use parameterized queries here !!!
$sql_titel = "SELECT post_title FROM posts WHERE title = '$title'";
$result_titel = mysqli_query($con, $sql_titel);
// Using the number of rows returned as our collision ID:
$sameNameID = mysqli_num_rows($result_titel);
if ($sameNameID > 0) {
// Bump it up by 1 (so we essentially get 0,2,3,4,5..):
$sameNameID++;
// Add it to the post title:
$post_title .= '-'.$sameNameID;
}
}
Importantly, notice that it's checking the title field rather than post_title.
Also be aware that you're probably vulnerable to SQL injection. I.e. a random person on the internet could do whatever they want to your database. htmlentities does not protect you from injection. You should use PDO instead.
But having said that, you might want to take inspiration from websites like StackOverflow itself, where a number (the article ID) is always present in the URL.
In StackOverflow's case, it's the ID which actually routes the request - this makes it possible to change the question (or title, in your case) later. For example, all of these link to this question:
https://stackoverflow.com/questions/41537052/
https://stackoverflow.com/questions/41537052/prevent-the-same-url-occuring
https://stackoverflow.com/questions/41537052/prevent-the-same-url-occuring-renamed
The idea is to obtain in a javascript variable an array provided by a mysql query. It works fine, but the result of the variable shows minus 1 row than the query.
Below I have provided just the code ref the problem, skipping all of the rest, I suppose isn't needed.
Thanks in advance for help!
The query:
$search_qryvalAltnsRotas = "-1";
if (isset($_GET['search'])) {
$search_qryvalAltnsRotas = $_GET['search'];
}
mysql_select_db($database_connect, $connect);
$query_qryvalAltnsRotas = sprintf("SELECT altn, destino FROM tblalternativos WHERE destino = %s ORDER BY destino ASC", GetSQLValueString($search_qryvalAltnsRotas, "text"));
$qryvalAltnsRotas = mysql_query($query_qryvalAltnsRotas, $sado_leitor) or die(mysql_error());
$row_qryvalAltnsRotas = mysql_fetch_assoc($qryvalAltnsRotas);
$totalRows_qryvalAltnsRotas = mysql_num_rows($qryvalAltnsRotas);
(...) below is the variable (part of a javascript function):
var alternatesq =
<?php
while( $row_qryvalAltnsRotas = mysql_fetch_assoc($qryvalAltnsRotas) ) {
$alternates[] = $row_qryvalAltnsRotas['altn'];
}
echo json_encode( $alternates );
?>;
Because you have called mysql_fetch_assoc two times, remove this line
$row_qryvalAltnsRotas = mysql_fetch_assoc($qryvalAltnsRotas);
And use only this one
while( $row_qryvalAltnsRotas = mysql_fetch_assoc($qryvalAltnsRotas) )
I have tried to create a small 'bookmarking' feature for my website. Users are able to click on the ".bookmarkButton" which will execute the following script:
<!--Add To Bookmarks-->
$(".bookmarkButton").click(function() {
var pid=$(this).closest('div').attr('id');
$('#noBookmark').hide();
$.post('bookmarks/addBookmark.php', 'rid=' + pid, function (addBookmark) {
$("#bookmarkResults").add(addBookmark);
});
});
Here is the code for "addBookmark.php":
<?php
session_start();
if (isset($_SESSION['ridArray']) && count($_SESSION['ridArray'] > 0)){
addBookmark();
} else if (isset($_POST['rid']) && !isset($_SESSION['ridArray'])) {
$_SESSION['ridArray'] = array();
addBookmark();
}
function addBookmark() {
if (is_array($_SESSION['ridArray']) && isset($_SESSION['ridArray']) && isset( $_POST['rid']) ) {
array_push($_SESSION['ridArray'], $_POST['rid']); //push the id value from post to the session array
//$_SESSION['ridArrayClean'] = array_unique($_SESSION['ridArray']); //remove duplicates
print_r($_SESSION['ridArray']);
foreach($_SESSION['ridArray'] as $x) {
// Get all the data from the "example" table
$result = mysql_query("SELECT * FROM example WHERE id = $x")
or die(mysql_error());
$row = mysql_fetch_array( $result );
echo $row['productname'];
}}}
?>
The variable $_SESSION['ridArray'] holds the array with all the id's that have been accumulated.
My problem is that this script works only when one item is bookmarked. When there is more than one product bookmarked, I only get the product name that was last bookmarked and not every thing that I've bookmarked.
So for example instead of getting multiple product id's after clicking the bookmarkButton class like this: 0,1,2,3 in the array. I only get the one that was clicked last i.e. 6.
I've been looking into this for a while now and I can't seem to see what I'm doing wrong.
The script only echos the productnames, if you posted a "rid".
Also you could write the if like this:
if (isset($_SESSION['ridArray'], $_POST['rid']) && is_array($_SESSION['ridArray'])) {
Checking isset() first. Also you could additionally check for
... && count($_SESSION['ridArray'] > 0)
I do not think that your session starts automatically (is it possible to set its autostart in php.ini, but it does not by default), so
<?php
session_start();
Other thoughts:
SELECT * FROM example WHERE id = $x
Have you ever heard about SQL Injection?
ps: no need in secondary check (they are checked before) and from the first condition follows the second one
is_array($_SESSION['ridArray']) && isset($_SESSION['ridArray'])
I would write it as
<?php
session_start();
if (isset($_POST['rid'])) {
addBookmark(intval($_POST['rid']));
}
function addBookmark($rid) {
$_SESSION['ridArray'][] = $rid;
$_SESSION['ridArray'] = array_unique($_SESSION['ridArray']);
foreach($_SESSION['ridArray'] as $x) {
$result = mysql_query("SELECT * FROM example WHERE id = '$x'")
or die(mysql_error());
$row = mysql_fetch_array( $result );
echo $row['productname'];
}
}
?>