I've tried things like setting a $var to the MySQL information (such as name or password), then pulling it with PHP, but I cannot figure the PHP out to do so. I use the server connect code as well. I have checked ASP.net out, but don't find any information on altering HTML text to equal SQL information. How might I go about accomplishing this?
One example: The account balance on my website is displayed in the bottom right corner, but I need to pull the balance from a column of my table from my database. What code would I use to set that paragraph element to the server value of account_balance?
My PHP/SQL for Registration:
<?php
$con=mysql_connect(DB_HOST,DB_USER,DB_PASSWORD) or die("Failed to connect to MySQL: " . mysql_error());
$db=mysql_select_db(DB_NAME,$con) or die("Failed to connect to MySQL: " . mysql_error());
$email = $_POST['email'];
$emailConfirm = $_POST['confirmemail'];
$password = $_POST['password'];
$passwordConfirm = $_POST['confirmpassword'];
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$countryCode = $_POST['countrycode'];
$phoneNumber = $_POST['phone'];
$address = $_POST['address'];
$zipCode = $_POST['zipcode'];
$city = $_POST['city'];
$state = $_POST['state'];
$country = $_POST['country'];
$dateOfBirth = $_POST['birthdate'];
$registerDate = "CURDATE()";
$registerTime = "CURTIME()";
$paymentMethod = $_POST['moneymethod'];
if($email == $emailConfirm && $password == $passwordConfirm){
if(!empty($email) && !empty($_POST['confirmemail']) && !empty($password) && !empty($_POST['confirmpassword']) && !empty($fname) && !empty($lname) && !empty($countryCode) && !empty($phoneNumber) && !empty($address) && !empty($zipCode) && !empty($city) && !empty($state) && !empty($country) && !empty($paymentMethod)){
$query = "INSERT INTO user_information (email,password,f_name,l_name,country_code,phone_number,address,city,state,zip_code,country,money_option,join_date,join_time) VALUES ('$email','$password','$fname','$lname','$countryCode','$phoneNumber','$address','$city','$state','$zipCode','$country','$paymentMethod','$registerDate','$registerTime')";
$data = mysql_query ($query)or die(mysql_error());
if($data){
header( 'Location: http://www.madmater.com/register/success.php' );
}else{
echo "Unknown Error!";
}
}else{
echo 'Please fill out all required fields before completing your registration!';
}
}else{
echo 'Your passwords or emails do not match!';
}
?>
I have only tried a simple PHP command, as it is the only thing I could think of, being new to MySQL.
$fname = $_POST['fname']; //From form
echo "<script type="text/javascript">document.getElementById("fname-holder").innerHTML($fname);</script>";
Even a hint of where to start would help, and thank you in advanced.
Since I don't know which row your account balance is called, I've used account_balance as an example in order to get you started.
Here is a basic method to retrieve information from your database:
$fname = stripslashes($_POST['fname']);
$fname = mysql_real_escape_string($_POST['fname']);
// or if DB connnection is required
// $fname = mysql_real_escape_string($_POST['fname'], $db);
$query = "SELECT * FROM user_information WHERE f_name = '$fname'";
while($row = mysql_fetch_array($query)){
$user = $row['f_name'];
$balance = $row['account_balance'];
echo "Username: " . $user;
echo "<br>";
echo "Balance: " . $balance;
}
or mysql_fetch_assoc() depending on what method you wish to use.
For more information on MySQL's SELECT, visit:
http://dev.mysql.com/doc/refman/5.0/en/select.html
You can also try:
$row = mysql_fetch_array($query);
foreach($row as $r) {
echo $r . "<br>";
}
or:
$row = mysql_fetch_assoc($query);
foreach($row as $r) {
echo $r . "<br>";
}
Footnotes:
I have to state that your present code is open to SQL injection. Use mysqli with prepared statements, or PDO with prepared statements, they're much safer.
There is no sql code in this example. Besides the error i found in this code of PHP for ' is not used.
$fName = $_POST['fname'] //This is from my register form
echo "<script type='text/javascript'>document.getElementById('fname-field').innerHTML(".$fname.");</script>";
and try to give some insert/update code also.
Use form submit your values,
In that form in action give register.php
echo "<pre>";
print_r($_post);
echo"</pre>;
use that you got value
then $name= $_post['name']
$query = "INSERT INTO "Tablename" set name= '".$name."',addeddate=now();
This way you can write.
Related
I am updating MySQL row using the following code. could any one tell me how i can error check the update query and only print Success if the update query was successful without any error? and print failed if update query was not successful!
<?php
//start the session
session_start();
// include db configuration
include('include/db_connect.php');
// user's information
$member_id = $_SESSION['id'];
$member_name = $_SESSION['name'];
$contact_id = $_GET['id'];
// $get_contact = "SELECT * FROM `contacts` where contacts_id = '$contact_id'";
$get_contact = mysqli_query($conn, "SELECT * FROM `contacts` where contacts_id = '$contact_id'");
$row = mysqli_fetch_array($get_contact);
if(isset($_POST['submit'])){
$contact_id = $_POST['contact_id'];
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$cphone = $_POST['cphone'];
$city = $_POST['city'];
$update = "UPDATE `contacts` SET `first_name`='$fname',`last_name`='$lname',`cellphone_number`='$cphone',`city`='$city' WHERE contacts_id = ". $contact_id;
if (mysqli_query($conn, $update)) {
echo "
<script>
var msg = confirm('Contact Updated');
if(msg == true || msg == false){
location.href='update_contact.php?id=$contact_id';
}
</script>
";
} else {
echo "Error: " . $update . "<br>" . mysqli_error($conn);
}
}
?>
My question is this: I'm doing my best to find whats the error and i couldn't what it is. It is for my elective project.
first of all please learn how to use procedure based query to be safe from SQL injection( I am not here to give tutorials on procedure and SQL injection, it is just warning against malicious code) and now your code solution. There was a problem in the way you were concatenating a variable with a string in your query. I have fixed that part for you.
if you still get any error then share what error you are getting and what is the error message.
<?php
//start the session
session_start();
// include db configuration
include('include/db_connect.php');
// user's information
$member_id = $_SESSION['id'];
$member_name = $_SESSION['name'];
$contact_id = $_GET['id'];
$get_contact = mysqli_query($conn, "SELECT * FROM `contacts` where contacts_id = '".$contact_id."'");
$row = mysqli_fetch_array($get_contact);
if(isset($_POST['submit'])){
$contact_id = $_POST['contact_id'];
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$cphone = $_POST['cphone'];
$city = $_POST['city'];
$update = "UPDATE `contacts` SET `first_name`='".$fname."',`last_name`='".$lname."',`cellphone_number`='".$cphone."',`city`='".$city."' WHERE contacts_id = '".$contact_id."'";
if (mysqli_query($conn, $update)) {
echo "
<script>
var msg = confirm('Contact Updated');
if(msg == true || msg == false){
location.href='update_contact.php?id=$contact_id';
}
</script>
";
} else {
echo "Error: " . $update . "<br>" . mysqli_error($conn);
}
}
?>
use this function:
function alertBox($alert_msg, $redirect_link)
{
$alert = '<head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /></head>';
$alert .= '<script type="text/javascript">alert("'.$alert_msg.'");';
if(!empty($redirect_link)):
$alert .='window.location="'.$redirect_link.'";';
endif;
$alert .='</script>;';
return $alert;
}
// and for calling..
if((mysqli_query($con,$sql))
{
echo alertBox("sucessfull","example.php");
}
I am trying to make a post-ad form add data to a database. The page keeps reloading and asking to fill in all the details. I cannot seem to find the error and i have done a lot of searching on google and youtube, all to no avail. Please help!!!
<?php
session_start();
include'db.php';
$name = $_POST['name'];
$email = $_POST['email'];
$phoneNumber = $_POST['mobile-num'];
$photos = $_POST['fileselect'];
$town = $_POST['location'];
$category = $_POST['category'];
$adTitle = $_POST['title'];
$adDescription = $_POST['description'];
if(isset($_SESSION['email']))
{
if($email != "" && $name != "" && $phoneNumber != "" && $photos != "" && $town != "" && $category != "" && $adTitle !="" && $adDescription != "")
{
$name = stripslashes($name);
$email = stripslashes($email);
$phoneNumber = stripslashes($phoneNumber);
$photos = stripslashes($photos);
$town = stripslashes($town);
$adTitle = stripslashes($adTitle);
$category = stripslashes($category);
$adDescription = stripslashes($adDescription);
$name = mysqli_real_escape_string($connection,$name);
$email = mysqli_real_escape_string($connection,$email);
$phoneNumber = mysqli_real_escape_string($connection,$phoneNumber);
$photos = mysqli_real_escape_string($connection,$photos);
$town = mysqli_real_escape_string($connection,$town);
$adTitle = mysqli_real_escape_string($connection,$adTitle);
$category = mysqli_real_escape_string($connection,$category);
$adDescription = mysqli_real_escape_string($connection,$adDescription);
$imagePath = "images/".basename($_FILES['fileselect']['MAX_FILE_SIZE']);
$photo = $_FILES['fileselect']['MAX_FILE_SIZE'];
$date = date("j F Y");
if(filter_var($email,FILTER_VALIDATE_EMAIL))
{
mysqli_query($connection, "SELECT email,ad-title,ad-category,ad-description,Photos,Name,Mobile-Num,Town,date from ads");
$insertQuery = mysqli_query($connection, "INSERT INTO ads(email,ad-title,ad-category,ad-description,Photos,Name,Mobile-Num,Town,date)
VALUES('$email','$adTitle','$category','$adDescription','$photo','$name','$phoneNumber','$town','$date')");
header("Location: /profile.php");
}
else
$_SESSION['errorMessage'] = "Please check email pattern";
header("Location: /post-ad.php");
}
else
$_SESSION['errorMessage'] = "Please input all the required details";
header("Location: /post-ad.php");
}
else
header("Location: /login.php");
?>
That's the PHP code.
Since I am not very good with Stackoverflow, I am having issues formatting the html form code i wanted to post here. I will attach an image instead. Html form code for the post-ad form
Not sure why you are running the SELECT, as you seem to do nothing with it and no parameters. But the INSERT should be...
$insertQuery = mysqli_query($connection, "INSERT INTO ads(email,`ad-title`,`ad-category`,`ad-description`,`Photos`,`Name`,`Mobile-Num`,`Town`,`date`)
VALUES('$email','$adTitle','$category','$adDescription','$photo','$name','$phoneNumber','$town','$date')");
When you have column names with hyphens in them it should be enclosed in back-ticks, either that of I would recommend (if not tooo late ) to remove the hyphens and use an underscore instead.
You should also check for errors when running any SQL and do some sort of processing with them.
Thanks Guys for the help. Sorry for putting you all through the stress. I went through my database structure and found a column with the wrong type that was preventing the sql insert query. My apologies....
I am programming an App and I have a problem now.
When I register a new student with the app a Query runs on my php Script and insert the new student in my database.
What I want to do now is, when I am registering him, I want my php Script to run a multiple query so that all the other tables should be filled with NULL and the query should get the ID from the new created student to link it with the other tables(foreign key).
I tried it with mysqli_multiple_query and LAST_INSERT_ID() but both didn't work.
How would it be possible to get that id in return from my insert?
Here is my php script.
<?PHP
if ($_SERVER['REQUEST_METHOD']=='POST') {
$Name = $_POST['Name'];
$Surname = $_POST['Surname'];
$Street = $_POST['Street'];
$Hometown = $_POST['Hometown'];
if ($Name == '' || $Surname == '' || $Street== '' || $Hometown == '') {
echo 'please fill all values';
} else {
require_once('dbConnect.php');
$sql = "INSERT INTO T_Student(Name,Surname,Street,Hometown) VALUES('$Name','$Surname','$Street','$Hometown')";
$sql .= "INSERT INTO T_University(ID, Teacher, Subject , Classroom, F_ID_Student) VALUES ("","","","","",LAST_INSERT_ID())";
if(mysqli_multi_query($con,$sql)){
echo 'successfully registered';
} else {
echo 'oops! Please try again!';
}
}
mysqli_close($con);
}
echo "Data Inserted";
?>
I hope someone can help me.
Don't concatenate the two queries. Execute the first, save the last id into a variable like
$id = mysqli_insert_id();
, then execute the second query referencing the variable among the values.
Be aware that if those $_POST variables come from a user submitted form it would be useful to do some validation on them before saving them into database. Maybe this answer would be a nice read ;)
I have modify your code. Try and see if it works for you.
<?php
if ($_SERVER['REQUEST_METHOD']=='POST') {
$Name = $_POST['Name'];
$Surname = $_POST['Surname'];
$Street = $_POST['Street'];
$Hometown = $_POST['Hometown'];
if ($Name == '' || $Surname == '' || $Street== '' || $Hometown == '') {
echo 'please fill all values';
} else {
require_once('dbConnect.php');
$sql = "INSERT INTO T_Student(Name,Surname,Street,Hometown)VALUES('$Name','$Surname','$Street','$Hometown')";
mysqli_query($con, $sql);
$id = mysqli_insert_id($con);
if ($id) {
$sql = "INSERT INTO T_University(ID, Teacher, Subject , Classroom, F_ID_Student) VALUES (NULL, NULL, NULL, NULL, NULL, $id)";
mysqli_query($con, $sql);
}
}
mysqli_close($con);
}
echo "Data Inserted";
?>
I've been following a login system tutorial. You can find it here. There are 2 parts of coding C# and PHP. The C# part is working fine but my PHP part returning error. Here is my PHP code:
<?php
$servername = getenv('IP');
$username = getenv('C9_USER');
$passwordp = "";
$database = "game_database";
$dbport = 3306;
// Create connection
mysql_connect($servername, $username, $passwordp, $dbport)or die("Cant Connect to server");
mysql_select_db($database) or die("Cant connect to database");
// Check connection
$Email = $_REQUEST["Email"];
$Password= $_REQUEST["Password"];
if (!$Email || !$Password){
echo"Email or password must be used";
}
else{
$SQL = "SELECT * FROM 'users' WHERE Email = '" . $Email ."'";
$result_id = #mysql_query($SQL) or die("Database Error");
$Total = mysql_num_rows($result_id);
if ($Total){
$datas = #mysql_fetch_array($result_id);
if (strcmp($Password, $datas["Password"])){
$sql2 = "SELECT Characters FROM users WHERE Email = '" . $Email ."'";
$result_id2 = #mysql_query($sql2) or die("Database Error!!!");
while ($row = mysql_fetch_array($result_id2)){
echo $row ["Characters"];
echo ":";
echo "Success";
}
}
else{
echo "WrongPassword";
}
}else {
echo "NameDoesNotExist";
}
}
?>
It seems the error comes from $result_id but I'm not sure?
You are true, the error is from $result_id, because your SQL statement has problem and there are extra stuff to fix.
You have put users table in two single quotes, it is wrong.
Your code is:
$SQL = "SELECT * FROM 'users' WHERE Email = '" . $Email ."'";
It should be with out quotes:
$SQL = "SELECT * FROM users WHERE Email = '" . $Email ."'";
You have wrote:
if ($Total){
It should check how many users record found, typically it should find only 1 record and return 1, therefore change it to:
if ($Total == 1){
Note1:
But when this is said, it does not mean the code is perfect, you should further develop your code to fulfill nowadays requirement. I would suggest you think of password hashing, use mysqli or PDO in sted of mysql and input sensitization. I would suggest you look at this link it describes some of the things I mentioned.
Note2:
I was able to write you a total solution with mysqli/PDO etc, but I wanted only to point the errors I have catch so far in your code so you can learn from your mistakes and develop your self.
And in general read about security principles, check this page.
Link1: http://www.wikihow.com/Create-a-Secure-Login-Script-in-PHP-and-MySQL
Link2: https://www.owasp.org/index.php/Category:OWASP_Top_Ten_Project
This is another simple way where you can create user log in, it is
more secure than the one you have at the moment. And you should
protect your code from sql injections.
<?php
if (isset($_POST['email'], $_POST['password']) === true )
{
require 'connection.php';
$email = mysqli_real_escape_string($connection,$_POST['email']);
$password = mysqli_real_escape_string($connection,$_POST['password']);
$sql = "SELECT * FROM users WHERE email= '$email'";
$result = mysqli_query($connection,$sql);
if (mysqli_num_rows($result))
{
if( $email == $row['email'] && $password == $row['password'])
{ //use session to check if user is logged in
if (!isset($_SESSION['loggedin']))
{
//you can set session of user's log in details
//you can redirect to user profile
}
else
//already log in, redirect to user profile
}
else
echo "Incorrect Email or Password.";
}
else
echo "Incorrect Username or Password.";
mysqli_close($connection);
}
else
{
echo "Oops, something went wrong!";
?>
I have written a PHP script that I use for authentication with e-mail and password since e-mail is identified as unique.
I want to echo "true" as well as echo :: fname (First Name). how can I write it? Following is my PHP code.
include "db_config.php";
$email = $_POST['email'];
$password = $_POST['password'];
$sql = "select fname,e_mail,password from user where e_mail = '$email' and pwd = '$password' ";
$result = mysql_query($sql);
if (mysql_num_rows($result) > 0){
echo "true";
}
else{
echo "Login Failed";
}
If you can suggest me some better way to write this code, please let me know.
Consider the comments about mysql_* and mysql_real_escape_string, but after you get your result, you echo it like this, adapted from the manual:
$result = mysql_query($sql);
if (!$result) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
$row = mysql_fetch_assoc($result);
echo "true" . $row['fname'];
if (mysql_num_rows($result) > 0)
{
echo mysql_result($result, 0);
}
-- or --
The code from Sankalp's or GDP's answers. (mysql_fetch_array)
mysql_result is not good if you want to display many results, it's good for just a few of them.
BTW, I'd like to point you to some omissions in your code:
you should check if every $_POST or $_GET variables are set by using isset or empty.
your code is so insecure! You should escape every variable before using it in a query. Use mysql_real_escape_string() for that. I also suggest you to use strip_tags() along with escaping.
Example of checking if variables are set:
Using isset():
if(isset($_POST['email'])) $email = $_POST['email'];
if(isset($_POST['password'])) $password = $_POST['password'];
Using empty():
if(!empty($_POST['email'])) $email = $_POST['email'];
if(!empty($_POST['password'])) $password = $_POST['password'];
$row = mysql_fetch_array($result, MYSQL_NUM)
echo $row[0]; //fname
echo $row[1]; //email
or you can use MYSQL_ASSOC to get a named array and access values as
echo $row['fname'];