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.
Related
I'm making a "Shopping Webpage" just to test SQL Injection (I'm trying to mock the webpage shown in Computerphile's "SQL Injection" video). Searching for the data isn't a problem, but the default result (when I refresh the page) is an item inside my db instead of nothing. Can you help me? Also only one item comes up when I have two items that match that search query.
Everything is new for me on php. I've seen a lot of Youtube tutorials and tried making new website codes just to check that the tutorial I took was right. But nothing really worked for me.
<?php
$conn = mysqli_connect("localhost", "root", "") or die("Could not
connect");
mysqli_select_db($conn, "search_products") or die("Could not find the
database");
$output = '';
$count = 0;
if (isset($_POST['searchq']))
{
$search_query = $_POST['searchq'];
$query = mysqli_query($conn, "SELECT * FROM products WHERE name LIKE
'%$search_query%'")
or die("Could not search for the query");
$count = mysqli_num_rows($query);
if ($count == 0)
{
$output = 'No Results';
}
else
{
while ($row = mysqli_fetch_array($query)) {
$name = $row['name'];
$price = $row['price'];
$stock = $row['instock'];
$output = '<div> '.$name.' '.$price.' '.$stock.' </div>';
}
}
}
?>
<--This is my php code -->
You are getting only one item because of the below line
$output = '<div> '.$name.' '.$price.' '.$stock.' </div>';
The above line overrides the previous value. So replace it with below:
$output .= '<div> '.$name.' '.$price.' '.$stock.' </div>'; (observe the dot after variable name).
The above line will concatenate each of the item. Hope this helps.
Change the following to see if helps
if (isset($_POST['searchq'])) to if (isset($_POST['searchq']) && !empty($_POST['searchq']))
$output should have ".=" instead of "=", you are simply replacing the new output with the old one. You should concatinate to get all results.
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
This question already exists:
php pdo search column array
Closed 8 years ago.
table name - animationmaster
column - animationdate ,type= varchar
column - animationno ,type= varchar
Data present in each column are like below..
animationno = 300,301
animationdate = 300 - 23-03-2015,301- 23-04-2015
When user search 300 then it display output 300-23-03-2015 from animationdate
When user search 301 then it display output 301-23-04-2015 from animationdate.
I have no idea is this possible..or not...and if yes...i really no guesses how to achieve this...thanks for any help...to find solution
plz help to get solution for this..array search
<?php
$q = $_GET['q'];
$city = $database->getRows("SELECT animationdate FROM animationmaster WHERE animationno = :animationno ", array(':animationno '=>"$q"));
$info = array();
foreach($city as $row)
{
$generat = $row['animationdate'];
$info[] = array('date' =>$generat);
}
echo json_encode($info);
?>
Try this for a database SELECT query based on user input using PDO:
<?php
$database= new PDO( "connection string goes here" );
$q = $_GET['q'];
$query=$database->prepare("SELECT animationdate FROM animationmaster WHERE animationno = :animationno");
$query->bindParam(':animationno', $q);
$query->execute();
$result = $query -> fetch();
echo json_encode($result);
?>
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
i am trying to display data based on wether data in a field is new. instead of showing only the data that is new it is showing all data. can someone point out my error. many thanks
<?php
include("../../js/JSON.php");
$json = new Services_JSON();
// Connect to MySQL database
mysql_connect('localhost', 'root', '');
mysql_select_db(sample);
$page = 1; // The current page
$sortname = 'id'; // Sort column
$sortorder = 'asc'; // Sort order
$qtype = ''; // Search column
$query = ''; // Search string
$new = 1;
// Get posted data
if (isset($_POST['page'])) {
$page = mysql_real_escape_string($_POST['page']);
}
if (isset($_POST['sortname'])) {
$sortname = mysql_real_escape_string($_POST['sortname']);
}
if (isset($_POST['sortorder'])) {
$sortorder = mysql_real_escape_string($_POST['sortorder']);
}
if (isset($_POST['qtype'])) {
$qtype = mysql_real_escape_string($_POST['qtype']);
}
if (isset($_POST['query'])) {
$query = mysql_real_escape_string($_POST['query']);
}
if (isset($_POST['rp'])) {
$rp = mysql_real_escape_string($_POST['rp']);
}
// Setup sort and search SQL using posted data
$sortSql = "order by $sortname $sortorder";
$searchSql = ($qtype != '' && $query != '') ? "where ".$qtype." LIKE '%".$query."%' AND new = 1" : '';
// Get total count of records
$sql = "select count(*)
from act
$searchSql";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
$total = $row[0];
// Setup paging SQL
$pageStart = ($page -1)*$rp;
$limitSql = "limit $pageStart, $rp";
// Return JSON data
$data = array();
$data['page'] = $page;
$data['total'] = $total;
$data['rows'] = array();
$sql = "select *
from act
$searchSql
$sortSql
$limitSql";
$results = mysql_query($sql);
while ($row = mysql_fetch_assoc($results)) {
$data['rows'][] = array(
'id' => $row['id'],
'cell' => array($row['id'], $row['slot'], $row['service'], $row['activity'], $row['department'], $row['company'], $row['address'], $row['user'], $row['item'], $row['filebox'], date('d/m/Y',strtotime($row['date'])), $row['quantity'], $row['type'], $row['new'])
);
}
echo $json->encode($data);
?>
You should debug SQL by looking at the SQL query, not at the PHP code that produces the SQL query. If you echo $sql and look at it, you'll probably see any syntax errors much more easily.
You can also copy & paste that SQL and try to execute it in the MySQL command tool, and see what happens, whether it gives the result you want, you can profile it or use EXPLAIN, etc.
You're using mysql_real_escape_string() for integers, column names, and SQL keywords (ASC, DESC). That escape function is for escaping only string literals or date literals. It's useless for escaping unquoted integers, column names, SQL keywords, or any other SQL syntax.
For integers, use (int) to typecast inputs to an integer.
For column names or SQL keywords, use a whitelist map -- see example in my presentation http://www.slideshare.net/billkarwin/sql-injection-myths-and-fallacies
You're not testing for error statuses returned by any of your functions. Most functions in ext/mysql return false if some error occurs. You should check for that after every call to a mysql function, and report errors if they occur.
You're selecting a database using a constant name sample instead of a quoted string "sample". This might be intentional on your part, I'm just noting it.
Also, this is not related to your errors, but you should really upgrade to PHP 5. PHP 4 has been end-of-lifed for over two years now.
after looking at the code again and all the suggestions i think i should be using an AND clause and not WHERE. for example the code
$searchSql = ($qtype != '' && $query != '') ? "where ".$qtype." LIKE '%".$query."%' AND new = 1" : '';
this is the WHERE clause? which basically translates to:
$sql = "select *
from act
$searchSql
$sortSql
$limitSql"; <- original code
$sql = "select *
from act
WHERE company LIKE '%demo%' AND new = 1
$sortSql
$limitSql";<-updated code
am i on the right track?