I don't enter or enter any random info in search, result shows, "No Results Found" And I am okay with that but when I enter anything related to MySQL table shows error,
"**Fatal error: Call to undefined function mysql_fetch_assocc() in /home/opticfhb/public_html/vacationsbychoice.com/search_result.php on line 10".
I know page is able to connect to db.
Form:
<form name="form_search" method="post" action="search_result.php">
<input name="search" id="search" type="text" value="Type the name of City, State or Place you are visiting.." onFocus="if (value == 'Type the name of City, State or Place you are visiting..') {value=''}" onBlur="if (value== '') {value='Type the name of City, State or Place you are visiting..'}" />
<input id="from" type="date" value="Check In" onFocus="if (value == 'Check In') {value=''}" onBlur="if (value== '') {value='Check In'}" />
<input id="to" type="date" value="Check Out" onFocus="if (value == 'Check Out') {value=''}" onBlur="if (value== '') {value='Check Out'}" />
<input name="submit" type="submit" value="Search" />
</form>
PHP:
if(!isset($_POST['search'])) {
header("Location:index.php");
}
$search_sql="SELECT * FROM world_wise WHERE stat_province LIKE '%".$_POST['search']."%' or city LIKE '%".$_POST['search']."%'";
$search_query=mysql_query($search_sql);
if (mysql_num_rows($search_query)!=0) {
$search_rs=mysql_fetch_assocc($search_query);
}
?>
Result:
<h2>Search Result</h2>
<?php if (mysql_num_rows($search_query)!=0) {
do { ?>
<p><?php echo $search_rs['name']; ?></p>
<?php } while ($search_rs=mysql_fetch_assocc($search_query));
} else {
echo "No Results Found";
}
?>
Simple; change both instances of mysql_fetch_assocc to mysql_fetch_assoc (a typo)
There are 2x c's instead of one at the end of the function's name.
Use error reporting at the top of your files when in production mode.
error_reporting(E_ALL); ini_set('display_errors', 1);
Footnotes:
Your present code is open to SQL injection. Use prepared statements, or PDO.
mysql_* functions deprecation notice:
http://www.php.net/manual/en/intro.mysql.php
This extension is deprecated as of PHP 5.5.0, and is not recommended for writing new code as it will be removed in the future. Instead, either the mysqli or PDO_MySQL extension should be used. See also the MySQL API Overview for further help while choosing a MySQL API.
These functions allow you to access MySQL database servers. More information about MySQL can be found at » http://www.mysql.com/.
Documentation for MySQL can be found at » http://dev.mysql.com/doc/.
As you can see you are using wrong mysql function mysql_fetch_assocc, its mysql_fetch_assoc
if(!isset($_POST['search'])) {
header("Location:index.php");
}
$search_sql="SELECT * FROM world_wise WHERE stat_province LIKE '%".$_POST['search']."%' or city LIKE '%".$_POST['search']."%'";
$search_query=mysql_query($search_sql);
if (mysql_num_rows($search_query)!=0) {
$search_rs=mysql_fetch_assoc($search_query);
}
?>
If you are not sure about the functions you are using , try to put debug mode on , in short make error_reporting ON always to display errors
I think it's a simple typo: mysql_fetch_assoc(), not mysql_fetch_assocc().
Related
I am learning PHP MYSql and faced an error while writing a marks submission program. When i run the program in chrome, the table is coming ok but neither the values are inserting in the MySQL table nor the redirection to different webpage taking place. You will understand it more clearly in the code and screen given below
<html>
<body>
<?php
error_reporting(E_ALL ^ E_DEPRECATED);
$connection = mysql_connect("localhost","root","");
if($connection == false)
{
echo("<h3>Unable MySQL</h3>");
die();
}
$db = mysql_select_db("IGNOU",$connection);
if($db == false)
die("<h3>Unable to connect to DB</h3>");
if(isset($_POST['submit']))
{
$rcptno=mysql_real_escape_string($_POST['rcptno']);
$subdt=mysql_real_escape_string($_POST['subdt']);
$amarks=mysql_real_escape_string($_POST['amarks']);
$Vvmarks=mysql_real_escape_string($_POST['Vvmarks']);
$chk_dt=mysql_real_escape_string($_POST['chk_dt']);
$roll_no=mysql_real_escape_string($_POST['roll_no']);
$sbcode=mysql_real_escape_string($_POST['sbcode']);
$ecode=mysql_real_escape_string($_POST['ecode']);
$query1=mysql_query("insert into assignment values('$rcptno','$subdt','$amarks','$Vvmarks','$chk_dt',
'$roll_no','$sbcode','$ecode')");
echo "insert into assignment values('$rcptno','$subdt','$amarks','$Vvmarks','$chk_dt','$roll_no'
,'$sbcode','$ecode')";
if($query1)
{
header("location:studentmaster.php");
}
}
?>
<fieldset style="width:400px;">
<form method="post" action="">
Reciept No.: <input type="number" name="rcptno" min="1">
<br>
Submission Date.: <input type="date" name="subdt">
<br>
Assignment Marks: <input type="number" name="amarks" max = "100">
<br>
Viva Marks: <input type="number" name="Vvmarks" max="100">
<br>
Checking Date.: <input type="date" name="chk_dt">
<br>
Roll No.: <input type="text" name="roll_no">
<br>
Subject Code.:
<input type="text" name="sbcode">
<br>
Evaluator Code:
<input type="text" name="ecode">
<br>
<input type="submit" name="submit">
</form>
</fieldset>
</body>
</html>
Screen
[This is the screen in which i have not yet clicked submit button]
[Now i have Clicked Submit button but it only displays a line...no insertion...no redirection]
Kindly help in overcoming this problem....
You're seeing the output because your using this line.
echo "insert into assignment values('$rcptno','$subdt','$amarks','$Vvmarks','$chk_dt','$roll_no'
,'$sbcode','$ecode')";
Also you need to make sure that you have successfully inserted or not.
For this you should use these lines of code.
if ($query1) {
header('Location: studentmaster.php');
} else {
echo 'No redirect means query failed';
var_dump(mysql_error($connection));
}
Because you're learning you can skip mysql_* functions and move to mysqli, PDO
Just replace the insert query with this
insert into assignment(`col1`,`col2`,`col3`,`col4`,`col5`, `col6`,`col7`,`col8`) values('$rcptno','$subdt','$amarks','$Vvmarks','$chk_dt', '$roll_no','$sbcode','$ecode')
replace col1, col2, col3... with your mysql table columns
I am working on a school project and can't get registration page done right. It just doesn't insert the data in table.
Here is a screenshot for database and table
I have added the HTML, and after going through all your answers I think I am using outdated videos and study material to learn (PHP, HTML, CSS, Website Security).
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Register</title>
</head>
<body>
<div class="form">
<h2>Registeration</h2>
<form action="" method="post">
Name<input type="text" name="name" placeholder="First & Last name" required><br><br>
Username<input type="text" name="username" placeholder="Username"required><br><br>
Password<input type="password" name="password" placeholder="Keep it Strong"required><br><br>
Confirm Password<input type="password" name="confirm-pass" placeholder="Re-Enter Password"required><br><br>
Email<input type="email" name="email" placeholder="Email"required><br><br>
Phone No.<input type="text" name="phone-no" placeholder="Phone No"required><br><br>
Gender<input type="text" name="gender" placeholder="Male or Female"required><br><br>
State<input type="text" name="state" placeholder="State"required><br><br>
<button type="submit" name="home">Home</button>
<button type="submit" name="sub">Submit</button>
<button type="submit" name="reset">Reset</button>
</form>
</div>
</body>
</html>
<?php
$con=mysqli_connect('localhost','root','123456789','eedb');
if ($con)
{
if (isset($_POST['sub']))
{
$n= $_POST['name'];
$un=$_POST['username'];
$p=$_POST['password'];
$cp=$_POST['confirm-pass'];
$e=$_POST['email'];
$pn=$_POST['phone-no'];
$g=$_POST['gender'];
$s=$_POST['state'];
mysqli_query($con,"SELECT * FROM `register`");
$insert= mysqli_query($con,"INSERT INTO `register`(`name`, `username`, `password`, `confirm-pass`, `email`, `phone-no`, `gender`, `state`) VALUES ('$n','$un','$p','$cp','$e','$pn','$g','$s')");
if ($insert)
{
echo "<center>Data Successfully Submitted</center>";
}
else
{
echo "<center>Data Not Submitted</center>";
}
}
}
else
{
echo "<center>Oh!no there is an error.<br><br>But don't worry we have an army of trained chimpanzies to deal with it.<br><br> <image src='images/chimps.jpg'><br><br>Come Back Soon</center>";
}
if (isset($_POST['home']))
{
header("location:index.php");
}
if (isset($_POST['reset']))
{
header("location:register.php");
}
?>
Since you didn't post your HTML form, I am posting the following answer, which is what your HTML form should (basically) look like, which btw only contains the one example element.
You will need to fill in the rest and follow the same convention.
<form method="post" action="handler.php">
First name:
<input type="text" name="name">
<br>
<input type="submit" name="sub" value="Submit">
</form>
Then escape your values, should there contain any characters that MySQL may complain about, such as apostrophes.
I.e.: Doug's Bar & Grill.
Then:
$n= mysqli_real_escape_string($con, $_POST['name']);
Something you should use or a prepared statement since your code is presently open to an SQL injection.
Ref: How can I prevent SQL injection in PHP?
And do the same for all your other POST arrays.
The name attribute is required for POST arrays when using pure PHP and a post method for the HTML form.
Sidenote: Your entire code is dependant on the following conditional statement
if (isset($_POST['sub'])){...}. So make sure that that form element bears the same name attribute for it.
Check for errors also.
Since this does not help you:
echo "<center>Data Not Submitted</center>";
References:
http://php.net/manual/en/mysqli.error.php
http://php.net/manual/en/function.error-reporting.php
It's unclear as to what you're trying to do with this line:
mysqli_query($con,"SELECT * FROM `register` ");
If the goal is to check if a row exists, then consult one of my answers on Stack:
check if row exists with mysql
Passwords
I also noticed that you may be storing passwords in plain text. This is not recommended.
Use one of the following:
PHP 5.5's password_hash() function.
Compatibility pack (if PHP < 5.5) https://github.com/ircmaxell/password_compat/
Important sidenote about column length:
If and when you do decide to use password_hash() or the compatibility pack (if PHP < 5.5) https://github.com/ircmaxell/password_compat/, it is important to note that if your present password column's length is anything lower than 60, it will need to be changed to that (or higher). The manual suggests a length of 255.
You will need to ALTER your column's length and start over with a new hash in order for it to take effect. Otherwise, MySQL will fail silently.
Other links of interest:
CRYPT_BLOWFISH
crypt()
bcrypt()
scrypt()
On OPENWALL
PBKDF2
PBKDF2 on PHP.net
PBKDF2 For PHP
HTML stickler:
The <center> tag is deprecated and has been removed from Web standards.
For more information, visit the following:
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/center
you can try this
$insert= mysqli_query($con,"INSERT INTO `register`(`name`, `username`, `password`, `confirm-pass`, `email`, `phone-no`, `gender`, `state`)VALUES ('$n','$un','$p','$cp','$e','$pn','$g','$s')");
you can try to use notepad++ or any other editor (e.g netbeans )that will make the open and closed brackets more obvious .
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
My code doesn't work, nor it gives me any errors, so the code is right, but still doesn't work.
The code aims to look up for the entered data of a HTML form and, if the entered values are not stored on the database, creating them(the new user).
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
define('SECURE', true);
require_once('_connecting.php');
include "_head.php";
if(isset($_POST["send"]))
{
$username = $_POST["user_name"];
$mail=$_POST["user_email"];
$passwort = $_POST["user_password"];
$passwort2 = $_POST["user_password2"];
if(strlen($passwort)<6||$passwort!=$passwort2)
{
echo "Eingabefehler. Bitte alle Felder korekt ausfüllen. Zurück";
}
else
{
$check = ("SELECT Count(*) FROM user WHERE user_email ='$mail'");
$mysqli->query($check);
if ($check > 1) {
echo "Schon vorhanden";
exit();
} else {
$send="INSERT INTO user (user_name, user_email,user_password) VALUES ('$username','$passwort','$mail')";
$mysqli->query($send);
}
}}
?>
<h1>
Registriere dich jetzt, um alle Funktionen des Forums in vollem Umfang genießen zu können.
</h1>
<h1 id="yellowh1">
Du wirst es nicht bereuen - Es warten viele spannende Dinge auf dich.
</h1>
<form action="signup.php" method="post">
<br><br>
<input type="text" name="user_name" value="" required="required" placeholder="Nutzername" maxlength="255" />
<br>
<br>
<input type="email" name="user_email" value="<?php echo !empty($_POST['user_email']) ? $_POST['user_email'] : ''; ?>" required="required" placeholder="E-Mail-Adresse" maxlength="255" />
<br><br>
<input type="password" name="user_password" required="required" placeholder="Passwort" maxlength="50" />
<input type="password" name="user_password2" required="required" placeholder="Passwort erneut eingeben" maxlength="50" />
<br><br>
<input type="submit" value="Abschicken" name="send">
</form>
<?php include "_footer.php";?>
There are a few problems here.
$mail=$_POSST["user_email"];
Firstly, there is a typo in there and you must remove one of the S's. It's a superglobal.
Having error reporting would have signaled:
Notice: Undefined variable: _POSST in...
As I stated in comments, your query depends on it. WHERE user_email ='$mail' and you're not checking for errors anywhere.
VALUES ('$username','$passwort','$mail') that will also fail because of the typo in $_POSST.
Then you have value="<?php echo $user_email; ?>" for the name="user_email" input, which will also throw the following notice in the input field itself, as soon as you hit the submit button:
Notice: Undefined variable: user_email in...
Therefore, you need to use a ternary operator:
value="<?php echo !empty($_POST['user_email']) ? $_POST['user_email'] : ''; ?>"
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Error reporting should only be done in staging, and never production.
Footnotes:
Your present code is open to SQL injection. Use prepared statements, or PDO with prepared statements, they're much safer.
I noticed you may be storing passwords in plain text. If this is the case, it is highly discouraged.
I recommend you use CRYPT_BLOWFISH or PHP 5.5's password_hash() function. For PHP < 5.5 use the password_hash() compatibility pack.
References:
http://php.net/manual/en/language.operators.comparison.php
http://php.net/manual/en/function.error-reporting.php
http://php.net/manual/en/language.variables.superglobals.php
http://php.net/manual/en/mysqli.error.php
Final notes:
Since the MySQL API to connect with is unknown (to me), make sure that you are in fact using mysqli_ to connect with, and not another one that is different. Different MySQL APIs do not intermix with each other.
Use the same API from connection to query.
https://php.net/mysqlinfo.api.choosing
As stated in comments and kudos to "Don't Panic":
$mysqli->query->execute seems kind of strange. – Don't Panic
This method of querying $mysqli->query->execute(...) is used for prepared statements. http://php.net/manual/en/mysqli.prepare.php
Those need to be modified as just $mysqli->query(...)
As per the manual http://php.net/manual/en/mysqli.query.php
After browsing google for a few hours, I managed to splice together some code up, and it looks like it's working for the most part. Unfortunately, I'm getting an SQL error when I submit my form.
What I'm trying to do: When someone fills out the form on my website, a specific function is applied based on which radio button is pressed in the form. I want to store the data in a database, but I also want to store the IP address of the individual submitting.
All I request of this wonderful community is an explanation of why this isn't functioning as I thought it should, and a quick lesson on how to prevent this from happening again.
Here is the code for my form:
<html>
<head>
<link rel="stylesheet" type="text/css" href="/style.css">
<title>
Learning Made Easy
</title>
</head>
<body>
<?php include_once 'googleanalytics.php'; ?>
<a href="http://terrythetutor.com">
<div class="banner"> </div>
</a>
<?php include 'menu.php'; ?>
<div class="content">
</br>
</br>
</br>
<form action="../scripts/switch.php" method="post">
Title:
</br><input type="text" name="Title">
</br>
</br>
</br>
Summary of the video (including questions used in the video):
</br><textarea name="Summary" COLS=60 ROWS=10></textarea>
</br>
</br>
</br>
URL of the video (Yes, this means you need to upload it to an external website.):
</br><input type="text" name="URL">
</br>
</br>
Which course does your video pertain to?</br>
<input type="radio" name="course" value="intermediate"> Intermediate and below</br>
<input type="radio" name="course" value="college"> College Algebra</br>
<input type="radio" name="course" value="precalculus"> PreCalculus</br>
<input type="radio" name="course" value="trigonometry"> Trigonometry</br>
<input type="radio" name="course" value="calculus I"> Calculus I</br>
<input type="radio" name="course" value="calculus II"> Calculus II</br>
<input type="radio" name="course" value="calculus III"> Calculus III</br>
<input type="radio" name="course" value="differential equations"> Differential Equations</br>
</br>
The function triggered is used to pick the correct function based on the radio button selected. For the sake of space I won't include it, and will skip right to the code that it redirects to. This is where (I suspect) my error is, and I'm unfortunately not well versed enough to solve this error alone.
Code of the function AFTER switch.php (this is where I define the IP variable):
<?php
// Create connection
$con=mysqli_connect("********","*****","*****","****");
$IP = $_Server['REMOTE_ADDR'];
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO Intermediate Algebra ('Title', 'URL', 'IP', 'Summary')
VALUES
('$_POST[Title]','$_POST[URL]','[$IP]','$_POST[Summary]'";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "Your video has been successfully submitted. Thank you for your contribution to TerryTheTutor.com";
header('Location:http://terrythetutor.com');
?>
</br>
<input type="submit" value="Submit, foo!">
</form>
</br>
</br>
</br>
<p>
Please understand that you will not be able to change the title, summary, or URL of your video after submission.
</p>
</div>
<div class="footer">
<?php include 'footer.php'; ?>
</div>
</body>
</html>
I believe that the error has originated with the $IP variable. I've tried to add quotes, scanned the code countless times and still am unsure of what the error is.
Here is what the error I'm getting when I submit looks like:
Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Algebra ('Title', 'URL', 'IP', 'Summary') VALUES ('Title Test','Url test','[]',' at line 1
As a courtesy, if someone could show me how to properly "sanitize" this data input, that would be wonderful.
Thank you, guys!
table names and column names are identifiers. they are not string literals so they should not be wrap with single quote. So you need to remove it eg
INSERT INTO `Intermediate Algebra` (Title, URL, IP, Summary) VALUES(....)
If it happens that the names contains spaces or a reserved keyword, it should be wrap with backticks. eg
INSERT INTO `Intermediate Algebra` (`Title`, `URL`, `IP`, `Summary`) VALUES(...)
Additional Info
MySQL Reserved Keywords List
As a sidenote, the query is vulnerable with SQL Injection if the value(s) of the variables came from the outside. Please take a look at the article below to learn how to prevent from it. By using PreparedStatements you can get rid of using single quotes around values.
How to prevent SQL injection in PHP?
You can try this, this will help you to run your script successfully without any error.
$sql="INSERT INTO `Intermediate Algebra` (`Title`, `URL`, `IP`, `Summary`)
VALUES ('".$_POST[Title]."','".$_POST[URL]."','".$IP."','".$_POST[Summary]."')";
You have more than one error here:
PHP variable names are case sensitive. This means you have an error in this line of code:
$IP = $_Server['REMOTE_ADDR'];
Thus, $IP is always empty.
Instead, this should be:
$IP = $_SERVER['REMOTE_ADDR'];
In your SQL statement, table names with spaces need to be backquoted. It's also a very good idea to do the same with your field names, to avoid conflicts with MySQL keywords:
$sql="INSERT INTO `Intermediate Algebra` (`Title`, `URL`, `IP`, `Summary`) VALUES(...)";
Finally, your SQL statement is vulnerable to SQL injection and needs to be completely rewritten and replaced with a prepared statement.
You need to close bracket ),
('$_POST[Title]','$_POST[URL]','$IP','$_POST[Summary]')";
SQL:
$Title = mysqli_real_escape_string($con, $_POST['Title']);
$URL = mysqli_real_escape_string($con, $_POST['URL']);
$IP = $_SERVER['REMOTE_ADDR'];
$IP = mysqli_real_escape_string($con, $IP);
$Summary = mysqli_real_escape_string($con, $_POST['Summary']);
$sql="INSERT INTO Intermediate Algebra ('Title', 'URL', 'IP', 'Summary')
VALUES
('$Title','$URL','$IP','$Summary')";
I'm creating a php-post form, containing: Who, What, Where, Contact and date_created.
I've made a database with these rows.
Here's my HTML Form code:
<form id="contactform" action="post.php">
<p class="contact"><label for="who">Who</label></p>
<input id="who" name="who" placeholder="Who are you? (First & Second name)" required="" tabindex="1" type="text">
<p class="contact"><label for="email">What</label></p>
<input id="what" name="what" placeholder="What do you want?" required="" type="text">
<p class="contact"><label for="username">Where</label></p>
<input id="where" name="where" placeholder="Country, City, Street..." required="" tabindex="2" type="text">
<p class="contact"><label for="password">Contact</label></p>
<input type="text" id="contact" name="contact" placeholder="Phone number or email"required="">
<br><br>
<input class="buttom" name="submit" id="submit" tabindex="5" value="Submit" type="submit">
And here's the php post.php code:
<?php
// Grab our POSTed form values
// Note that whatever is enclosed by $_POST[""] matches the form input elements
$who = $_POST["who"];
$what = $_POST["what"];
$where = $_POST["where"];
$contact = $_POST["contact"];
// Connect to our DB with mysql_connect(<server>, <username>, <password>)
$sql_connection = mysql_connect("server_name", "admin", "password");
mysql_select_db("database_name", $sql_connection);
$sql = "INSERT INTO content (
who,
what,
where,
contact,
date_created
)
VALUES (
'$who',
'$what',
'$where',
'$contact',
NOW()
)";
mysql_query($sql, $sql_connection);
mysql_close($sql_connection);
?>
When I try to post something, nothing is happening. The screen is just white, the database is empty and the url is like this:
http://my-website.com/post.php?who=Firstname+Secondname&what=Some+sentences+here-and&where=America&contact=some#website.com&submit=Submit%21
Just as HamZa DzCyberDeV said, you didn't specify which method you're using in <form> tag.
For situations when you're POSTing something in your database, just as you are now - use method="post" and for forms when you're searching for something, use method="get".
In case of using post method, your URL will change to only my-website.com/post.php and in case of using get method, your URL will change to something like my-website.com/post.php?... (where your things which you're getting are going) - just how you got URL after submitting.
The screen is just white because post.php (where you're going after clicking on submit button) doesn't contain anything to send to output, which you can easily do with echo.
For instance, you can make a new html page which will be written down with echo:
echo '
<html
<body>
This is my website!
</body>
</html>
';
Also, what you could do is to use include() php script which has already formed HTML, or you can check out here for some other redirect methods:
http://php.about.com/od/learnphp/ht/phpredirection.htm
Just remember that PHP is language which server is processing and only HTML tags (with CSS and JS) are sent to other browser to be read.
For more about POST and GET method you can read here:
http://php.net/manual/en/reserved.variables.post.php
http://php.net/manual/en/reserved.variables.get.php
why don't you try this to get an error or a clue to what is going wrong, enclose your code in try and catch blocks:
try {
// your code
} catch ( Exception $e ) {
echo $e->getMessage();
}