MySql search script writes an unkown error - php

This is my second post on stackoverflow, and i hope u will help me resolve this one too.
When i run this script it says "Undefined variable: search_name".i don't know what is problem.
Hope u are going to help.
Ty :D .
<?php
$con=mysqli_connect("localhost","root","","test");
if (mysqli_connect_errno())
{
echo "Error" .mysqli_connect_error();
}
if(isset($_POST['go']))
{
$search_name = mysqli_real_escape_string($con, $_POST['form_name']);
}
$select_name=mysqli_query($con,"SELECT * FROM test_mysql WHERE name='$search_name' ");
while($row=mysqli_fetch_array($select_name))
{
$ime=$row['name'];
$prezime=$row['lastname'];
$id_number=$row['id'];
echo $id_number." . ".$ime. " ".$prezime."<br>";
}
?>
<form action="" methom="post">
Name: <input type="text" name="form_name"/>
<input type="submit" value="send" name="go"/>
</form>

You need to move your query inside the isset() of your submit button, otherwise the code will be executed everytime the page loads causing the error.
if(isset($_POST['go']))
{
$search_name = mysqli_real_escape_string($con, $_POST['form_name']);
$select_name=mysqli_query($con,"SELECT * FROM test_mysql WHERE name='$search_name' ");
while($row=mysqli_fetch_array($select_name))
{
$ime=$row['name'];
$prezime=$row['lastname'];
$id_number=$row['id'];
echo $id_number." . ".$ime. " ".$prezime."<br>";
}
}
?>
<form action="" methom="post">
Name: <input type="text" name="form_name"/>
<input type="submit" value="send" name="go"/>

Simply, just make sure the form is submitted before building the query, you already do that but not to all the parts of the code
if(isset($_POST['go']))
{
$search_name = mysqli_real_escape_string($con, $_POST['form_name']);
$select_name=mysqli_query($con,"SELECT * FROM test_mysql WHERE name='$search_name' ");
while($row=mysqli_fetch_array($select_name))
{
$ime=$row['name'];
$prezime=$row['lastname'];
$id_number=$row['id'];
echo $id_number." . ".$ime. " ".$prezime."<br>";
}
}
This should solve it.

Related

Why can't I "INSERT INTO" my table through my php script?

I have two different directories on my wampserver, this code works on one, but not on the other, I don't understand why.
PHP
<?php
error_reporting(E_ALL & ~E_NOTICE);
session_start();
$msg = "";
if (!isset($_SESSION['username'])) {
header('Location: login.php');
die();
}
if(isset($_SESSION['username'])) {
if (isset($_POST['submit']))
{
$className = $_POST['className'];
$classColour = $_POST['classColour'];
include_once("connection.php");
$sql = "INSERT INTO class (className, classColour) VALUE ('$className', '$classColour')";
mysqli_query($dbConnection, $sql);
$msg = "New class '" . $className . "' added.";
} else {
$msg = "No class added yet.";
}
}
?>
HTML
<form method="post" action="add_class.php">
<input type="text" name="className" placeholder="Class" />
<input type="text" name="classColour" placeholder="Colour" />
<div><input type="submit" name="submit" value="Add" class="btn butn-orange"/></div>
</form>
This is in the file "add_class.php" and I've tried many different things, putting single quotes (`) around the table columns in the $sql but still, it won't work. I've tried adjusting the names in the table, which had underscores but now have camelCasing, still made no difference. This code works perfectly in another directory, can someone please tell me why this is happening and possibly propose a solution? Thank you in advance.
P.S My connection works because I inserted a new row via phpmyadmin and looped through the database printing every existing "className" and it worked, I just can't insert from the php script.
connection.php
<?php
$dbConnection = mysqli_connect("localhost","root", "", "main");
if(mysqli_connect_errno())
{
echo "Failed to connect" . mysqli_connect_error();
}
?>
When asked if you've had assigned the sessions, you replied I assigned this when the user logs in. Moving forward from that, let's assume the assigned session as one written below:
<?php
error_reporting(E_ALL & ~E_NOTICE);
session_start();
$_SESSION['username'] = "HawqasKaPujaari";
$msg = "";
// this fails, as session is already set.
if (!isset($_SESSION['username'])) {
header('Location: login.php');
die();
}
if(isset($_SESSION['username'])) {
if (isset($_POST['submit']))
{
$className = $_POST['className'];
$classColour = $_POST['classColour'];
include_once("connection.php");
$sql = "INSERT INTO class (className, classColour) VALUES ('$className', '$classColour')";
mysqli_query($dbConnection, $sql);
echo $msg = "New class '" . $className . "' added.";
} else {
$msg = "No class added yet.";
}
}
?>
<form method="post" action="">
<input type="text" name="className" placeholder="Class" />
<input type="text" name="classColour" placeholder="Colour" />
<div><input type="submit" name="submit" value="Add" class="btn butn-orange"/></div>
</form>
Note: The only changes I made were to change the action="" empty and changed VALUE to VALUES in your query.
connection.php:
<?php
$dbConnection = mysqli_connect("localhost","root", "", "main");
if(mysqli_connect_errno())
{
echo "Failed to connect" . mysqli_connect_error();
}
?>
As the above posted code seemed to be correct and was bugging me so I thought of testing it myself by creating the database/tables and it seemed to work properly without any errors. I have posted the relevant pictures below:
Note: Make sure you have the connection.php file in the same
directory as the add_class.php.

Query not updating not sure why

For some reason this script isn't updating the database properly according to the query. Does anybody have any idea why the script isn't updating? Please let me know!
<?php
session_start();
include '../connect.php';
if(!isset($_SESSION['id'])){
header("Location: ../index.php");
}
if(isset($_POST['submit'])){
$id=$_POST['id'];
$postid=$_POST['postid'];
$content=$_POST['content'];
$title=$_POST['title'];
echo "<pre>";
print_r($_POST);
if(!empty($content)){
$content = mysql_real_escape_string($content);
} else {
echo 'You need to write something in your comment!';
}
$upd=mysql_query("UPDATE replies SET reply_content='$content' WHERE reply_id='$postid'");
if(!$upd){
echo 'Error: '.mysql_error();
}
} else {
if (isset($_GET['id'])){
$postid = $_GET['id'];
$id=$_SESSION['id'];
$q = mysql_query("SELECT * FROM `replies` where `reply_id`='$postid'");
if(!$q){
echo 'Error: '.mysql_error();
}
$res = mysql_fetch_assoc($q);
$q2 = mysql_query("SELECT topic_subject FROM `topics` where `topic_id`='$postid'");
$res2 = mysql_fetch_assoc($q2);
if(!q2){
echo 'Error: '.mysql_error();
}
if ($res['reply_by'] == $id){
} else {
header("Location: ../pagenotfound.html");
}
}
?>
<form action="edit.php">
<input type="text" name="title" value="<?php echo $res2['topic_subject'] ?>" disabled="disabled" />
<br />
<textarea rows="20" name="content" cols="50"><?php echo $res['reply_content']?></textarea>
<input type="hidden" name="postid" value="<?php echo $postid ?>" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>
<?php
}
?>
If you need more info let me know!
Update: The issue is that when I click submit, it sends me to a page which still lists the form. I noticed this isuee when I tried to print_r($_POST) because it didn't actually print $_POST, I believe there is something wrong with either the form or where it checks if isset submit.
Try with:
if(!empty($content)){
$content = mysql_real_escape_string($content);
} else {
echo 'You need to write something in your comment!';
// if $content is mandatory, you should put a die("error") here
}
You should check your $_POST array with a simple
echo "<pre>";
print_r($_POST);
and ensure that POST has vars you are looking for (first of all: submit)
EDIT: put print_r($_POST) BEFORE using it just before:
if(isset($_POST['submit'])){
ERROR: you forgot to set form method type. Try with:
<form action="edit.php" method="post">
Without that, form will send parameters as $_GET.
Here's a simple php-form tutorial. http://php.net/manual/en/tutorial.forms.php

get result in same page and form

hello i have simple problem with my functions there is 2 codes :
i need when i put the right input answer echo $row['answer']; and sucess in next code.
it means i need when $_POST['answer'] = $row['answer']; echo my password
can someone help me with if cond.
this code is working perfect :
<?php
$username = $_POST['username'];
include('config.php');
$result = mysqli_query($con,"SELECT * FROM persons WHERE username='$username'");
while($row = mysqli_fetch_array($result)){
echo $row['username'];
echo "</br>";
echo "</br>";
echo "<p><b>Secret Question</b></p>";
echo $row['secret'];
$freeanswer = $row['answer'];
}
?>
code problem in same page :
</br>
</br>
<form action="" method="POST">
<p><b>Answer is :</b><p>
<input type="text" name="answer">
</br>
</br>
<input type="Submit" value="Submit">
</form>
</div>
<?php
$anme = $_POST['answer'];
if ($anme==$freeanswer) {
echo "sucess";
} else {
echo "wrong";
}
?>
Do you have problem sending the data?
If you want to post the form data to the same page you could use this:
<form action="<?php echo $_SERVER['REQUEST_URI'];?>" method="post">
And this code will catch whatever you posted. (Put it in the same page as the form)
<?php
if(isset($_POST['answer'])) {;
if($name==$freeanswer) {
echo "success";
} else {
echo "wrong";
}
} else {
// Just for testing
var_dump("No data sent yet");
}
?>
Where is the $freeanswer variable declared in the second code?
This if statement is failing cause there is no $freeanswer declared.
$anme = $_POST['answer'];
if ($anme==$freeanswer) { ..
I see you declared it in first code but I dont see it in the second code..
EDIT :
Actually I didn't see It's all the same code. But still the problem is $freeanswer cause It's not declared in public scope It's only in the scope of while loop
Try declaring / writing this line of code here :
$username = $_POST['username']; // Near this line
$freeanswer = ""; // Declare this here
You should put a name to submit button, and the check the existence of $_POST['name_of_button'];
This is a dirty example I wrote quickly so you can get the idea, I didn't test it
<?php
// if the button has not been sent show the form
if(!isset($_POST['submit'])) {
?>
<form action="/test.php" method="POST">
<p><b>Answer is :</b><p>
<input type="text" name="answer">
</br>
</br>
<input type="Submit" value="Submit" name="submit">
</form>
</div>
<?php
// otherwise means the form has been sent, show the password or wrong
} else {
include('config.php');
$result = mysqli_query($con,"SELECT * FROM persons WHERE username='$username'");
$row = mysqli_fetch_array($result);
if($row) {
if($row['answer'] == $_POST['answer']) {
echo 'your password is ' . $row['password'];
} else {
echo 'wrong!';
}
}
}

Retrieve data from database and display in text fields.

Please help me. I written a code but it is not working well.
I want to retrieve data from database and display text fields.
My Code is:
<DOCTYPE html>
<html>
<head><title>Practice</title></head>
<body align="center">
<?php
$con=mysqli_connect("localhost","root","","address_db");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
<form action="1.php" method="post">
Name <br><input type="text" name="name" value="<?php echo $_GET['n']; ?>"><br>
Address 1<br><input type="text" name="address_1" value=""><br>
Address 2<br><input type="text" name="address_2" value=""><br>
Address 3<br><input type="text" name="address_3" value=""><br><br><br>
<input type="submit" name="reset" value="Clear">
<input type="submit" name="submit" value="Submit">
<input type="submit" name="retrieve" value="Retrieve">
</form>
<?php
if (isset($_POST['submit']))
{
$name=$_POST['name'];
$address_1=$_POST['address_1'];
$address_2=$_POST['address_2'];
$address_3=$_POST['address_3'];
if(($name=='')||($address_1=="")||($address_2=="")||($address_3==""))
{
echo "<script>alert('Please fill all fields')</script>";
exit();
}
else
{
mysqli_query($con,"INSERT INTO address_tbl (name,address_1,address_2,address_3)
VALUES ('$name','$address_1','$address_2','$address_3')");
echo "<script>alert('Your record successfull inserted into database...')</script>";
exit();
}
}
if (isset($_POST['retrieve']))
{
$result = mysqli_query($con,"SELECT * FROM address_tbl");
while($row = mysqli_fetch_array($result))
{
$name=$row['name'];echo "<br>";echo "<br>";
$add1=$row['address_1'];echo "<br>";echo "<br>";
$add2=$row['address_2'];echo "<br>";echo "<br>";
$add3=$row['address_3'];echo "<br>";echo "<br>";
echo "<script type='text/javascript'>
window.open('1.php?n=$name','_self'); </script>";
}
}
?>
</body>
</html>
Please help me. give me any hint that I can solve my problem. Thanks
try this ,
mysqli_query($con,"INSERT INTO `1address_tbl` (`name`,`address_1`,`address_2`,`address_3`)
VALUES ('$name','$address_1','$address_2','$address_3')");
it should work fine now. it needs to include ( ` ) around the table names and column name to make sql work correctly. you left them out,
you replace this with yours.
First of all you should have your php in a seperate file called index.php with just php code then create a page called index.html.php in that page use a foreach loop to output data from the database its the most common and practical way of doing what your trying to do .

How to disable writing to database if i made duplicate entry, and show warning in alertbox?

I am a bit new with php, so I need help. On one page i have small form with firstname and lastname fields. On submit i send it to external .php script where i want to check if there is already person with same name in database. If there is already person with entered name in database, I want to cancel writing to database, and return to the html page. I have done this, but I want to display the JS messagebox "Person with this name already exists in db!", and if the writing to base was canceled, i want my input fields show last written values. I've been reading a lot of litertaure, and I'm lost. Thanks for help anyway :)
This is my form:
<form name="form" action="write.php" method="post" onSubmit="return Validate()">
Firstname: <input type="text" name="firstname">
Lastname: <input type="text" name="lastname">
<input type="submit">
</form>
My php code:
<?php
$con=mysqli_connect("localhost","root","","phptest");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if (isset($_POST['firstname'])) {
$firstname = $_POST['firstname'];
}
if (isset($_POST['lastname'])) {
$lastname = $_POST['lastname'];
}
$duplicate=mysqli_query($con,"SELECT * FROM persons WHERE FirstName='$firstname'");
if(mysqli_num_rows($duplicate)>0)
{
die('Name already exists' );//I want that this message shows in html file, as alert
}
else{
$sql="INSERT INTO Persons (FirstName, LastName)
VALUES('$firstname','$lastname')";
$result=mysqli_query($con,$sql);
if (!$result)
{
die('Error: ' . mysqli_error());
}
}
header( 'Location://localhost/ivanda.php' ) ;
mysqli_close($con);
?>
This line:
if(mysqli_num_rows($duplicate)>0)
{
die('Name already exists' );//I want that this message shows in html file, as alert
}
Change it to this this code:
if(mysqli_num_rows($duplicate)>0)
{
echo "<script>alert('Name already exist!!!'); </script>";
echo "<script>window.location.assign('ivanda.php'); </script>"; //add this line instead of header
}
-------------------------EDITED----------------------------------
Trys this:
$duplicate=mysqli_query($con,"SELECT * FROM Persons WHERE FirstName='$firstname' limit 1");
if(mysqli_num_rows($duplicate)>0)
{
$row = mysqli_fetch_assoc($duplicate);
echo "<script>alert('Name already exist!!!'); </script>";
echo "<script>window.location.assign('ivanda.php?firsName=".$row['FirstName']."&lastName=".$row['LastName']."'); </script>"; //add this line instead of header
}
else{
$sql="INSERT INTO Persons (FirstName, LastName)
VALUES('$firstname','$lastname')";
$result=mysqli_query($con,$sql);
if (!$result)
{
die('Error: ' . mysqli_error());
}
}
With this you are sending the var via GET on the url...then in your form you should have something like this:
<form name="form" action="write.php" method="post" onSubmit="return Validate()">
Firstname: <input type="text" name="firstname" value="<?php if(isset($_GET['firsName'])){echo $_GET['firsName'];} ?>">
Lastname: <input type="text" name="lastname" value="<?php if(isset($_GET['lastName'])) {echo $_GET['lastName'];} ?>">
<input type="submit">
</form>
PS: Go for mysqli o PDO, remember it...mysql extension is gonna be deprecated soon
Saludos.

Categories