Why data failed to save to MySQL from URL parameter value? - php

I cannot figure out why the parameter from the value are not saving on the MySQL database. My connection string is working (config.php). But on MySQL database, it is 000-00-00 or 0.000000 The data are not saving. What do you think is the problem here?
This is my URL parameter: http://crbphil-001-site1.1tempurl.com/adddata.php?
addday=2017/10/04&addhour=01:31:00&addlati=14.779623&addlongti=120.993705
adddata.php
<?php
//Connect to MySQL
include("config.php");
//Prepare Query
$query = "INSERT INTO track (tr_date, tr_time, latitude, longitude) VALUES ('".urlencode($_GET["addday"])."','".urlencode($_GET["addhour"])."','".urlencode($_GET["addlati"])."','".urlencode($_GET["addlongti"])."')";
//Execute Query
mysqli_query($connect, $query);
?>
config.php
<?php
$username = "a2a8e2_itrack"; //mysql username
$password = "******"; //mysql password
$servername="mysql****.hostbuddy.com";
$dbname = "db_a2a8e2_itrack";
$connect = mysqli_connect($servername, $username, $password, $dbname);
$selected = mysqli_select_db($connect, $dbname);
?>

You are using urlencode which is changing the format of the data.
For example, you are passing addday=2017/10/04 BUT
urlencode($_GET["addday"] gives 2017%2F10%2F04
Simply remove urlencode and use just $_GET.
So your insert query becomes this :
$query = "INSERT INTO track (tr_date, tr_time, latitude, longitude)
VALUES ('".$_GET["addday"]."', '".$_GET["addhour"]."', '".$_GET["addlati"]."', '".$_GET["addlongti"]."')";

Related

how to include a php variable as part of a table name?

I have a site where I needed to use separate table names for each of my clients because the data has to be updated all the time with a manual import.
example:
kansas_users
newyork_users
I have set a global variable as $client which will create the state name on all pages so if I echo "$client"; then I will see "kansas" for example on any page.
I would like to include this variable as part of my SQL query if possible to make it easier to code:
SELECT "nick, firstname, lastname, cell
FROM database.$client_members
where active =1 and id = $user->id";
Is this possible or even safe to do?
Yes it possible you can do some thing like below
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$client = 'kansas';
$table_name = "database." . $conn->real_escape_string($client) . "_members";
$query = sprintf("SELECT nick, firstname, lastname, cell
FROM %s WHERE active = 1 and id = ?", $table_name);
// prepare and bind
$stmt = $conn->prepare($query);
$stmt->bind_param("i", $user->id);
But i think you should seriously consider normalizing your database to avoid such issues

PHPMyAdmin Cannot use PHP to Insert data into MySQL

I'm using MAMP Server to host a MySQL database to store some information about user accounts.
When I try to insert an entry using the code given by PHPMyAdmin, it won't insert it. Could somebody please tell me what's wrong with my code?
<?php
$username = "username";
$password = "*******";
$hostname = "localhost:8889";
$inputUsername = $_POST["username"];
$inputPassword = $_POST["password"];
$confirmPassword = $_POST["confirmPassword"];
if ($inputPassword != $confirmPassword) {
die("Your two password entries are not the same!");
}
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
$sql = mysql_select_db("billet",$dbhandle)
or die("Could not select database");
$sql = mysql_query("INSERT INTO `billet` (`username`, `password' VALUES ('$inputUsername', '$inputPassword')");
echo "Inserted values! <a href='index.html'>Go</a>";
mysql_close($dbhandle);
?>
You need to query the database to insert the data that you want, currently you are just connecting to the database and then closing.
You will need to do something like this (depending on your MySQL table) :
$result = mysql_query("INSERT INTO `billet` (`username`, `password`) VALUES ('$inputUsername', '$inputPassword')");
You should also think about switching to PDO as mysql_ functions are deprecated.

Can't connect to database in php

I have a database running on my server with phpmyadmin but I can't connect with it. Here is an example:
$user_name = "xxxxx";
$password = "xxxxx";
$database = "xxxxx";
$host = "db.xxxx.nl";
$db_handle = mysql_connect($host, $user_name, $password);
$db_found = mysql_select_db($database);
But this doesn't seem to work. If I try to insert some values into a table it still stays empty.
$sql = "INSERT INTO tbl_forum
(
title,
name,
content,
lastname,
post_image
)
VALUES
(
'{$_POST['contactsubject']}',
'{$_POST['contactname']}',
'{$_POST['contactmessage']}',
'{$_POST['contactlastname']}',
'{$_FILES["contactBrowse"]["name"]}'
)";
Am I doing something wrong?
I'm going to completely rewrite your code. As you are clearly new to databases within PHP, there is absolutely no reason not to use the new mysqli API.
Your connection should look something like this;
$mysqli = new mysqli($host,$user_name,$password,$database);
if ($mysqli->connect_errno) echo "Failed to connect to MySQL: " . $mysqli->connect_error;
This will create a new database object called $mysqli (or you can call it what you like, such as $db).
You can then prepare your SQL statement and execute it. In the code below, we have 5 parameters that are represented in the SQL as ?, and then we bind the variables to those 5 parameters. The first argument in bind_param tells the API the 5 parameters are 5 strings (hence s x5). For integers, use i;
if($query = $mysqli->prepare("INSERT INTO tbl_forum (title,name,content,lastname,post_image) VALUES (?,?,?,?,?)")) {
$query->bind_param('sssss',$_POST['contactsubject'],$_POST['contactname'],$_POST['contactmessage'],$_POST['contactlastname'],$_FILES["contactBrowse"]["name"]);
$query->execute();
}
else {
echo "Could not prepare SQL: " . $mysqli->error;
}
Assuming all your connection information is correct, this will insert your information into the database as required.
Hope this helps.
I think the last value '{$_FILES["contactBrowse"]["name"]}' has some problem. Try this and get the sql after preparing(echo $sql;) to debug by your self.
$file_name = $_FILES["contactBrowse"]["name"];
$sql = "INSERT INTO tbl_forum
(
title,
name,
content,
lastname,
post_image
)
VALUES
(
'{$_POST['contactsubject']}',
'{$_POST['contactname']}',
'{$_POST['contactmessage']}',
'{$_POST['contactlastname']}',
'{$file_name}'
)";

migrating mysql to mysqli in ajax environment

First i would like to say thank you for letting me ask questions again. I know my previous question was a bit low level of knowledge. Today, I would like to ask if the principle of converting mysql to mysqli in ajax is same with html. Suppose this is my Connect.php
<?php
$host = "localhost";
$dbusername = "root";
$dbpassword = "765632";
$dbname = "student";
$link_id = mysqli_connect($host,$dbusername,$dbpassword,$dbname) or die("Error " . mysqli_error($link_id));
?>
and my ajax.php is
<?php
//Connect to MySQL Server
include 'Connect.php';
mysql_connect($host, $dbusername, $dbpassword);
//Select Database
mysql_select_db($dbname) or die(mysql_error());
// Escape User Input to help prevent SQL Injection
$first_name = mysql_real_escape_string(trim($_GET['first_name']));
// Retrieve data from Query
$query = "SELECT student_id, LRN, first_name, last_name, grade, section FROM student_information WHERE first_name LIKE '%{$first_name}%'";
$result = mysql_query($query) or die(mysql_error());
//Generate the output
$searchResults = '';
if(!mysql_num_rows($result))
What are the changes should i made to convert it to mysqli without changing its logical scheme.
Did you mean this?
$link_id = mysqli_connect($host, $dbusername, $dbpassword);
//Select Database
mysqli_select_db($link_id, $dbname) or die(mysqli_error($link_id));
// Escape User Input to help prevent SQL Injection
$first_name = mysqli_real_escape_string($link_id, trim($_GET['first_name']));
// Retrieve data from Query
$query = "SELECT student_id, LRN, first_name, last_name, grade, section FROM student_information WHERE first_name LIKE '%{$first_name}%'";
$result = mysqli_query($link_id, $query) or die(mysqli_error($link_id));
//Generate the output
$searchResults = '';
if(!mysqli_num_rows($result))

PHP Select fields from database where username equals X

im having problems in PHP with selecting Infomation from a database where username is equal to $myusername
I can get it to echo the username using sessions from the login page to the logged in page.
But I want to be able to select things like 'bio' and 'email' from that database and put them into variables called $bio and $email so i can echo them.
This is what the database looks like:
Any ideas?:/
You should connect to your database and then fetch the row like this:
// DATABASE INFORMATION
$server = 'localhost';
$database = 'DATABASE';
$dbuser = 'DATABASE_USERNAME';
$dbpassword = 'DATABASE_PASSWORD';
//CONNECT TO DATABASE
$connect = mysql_connect("$server", "$dbuser", "$dbpassword")
OR die(mysql_error());
mysql_select_db("$database", $connect);
//ALWAYS ESCAPE STRINGS IF YOU HAVE RECEIVED THEM FROM USERS
$safe_username = mysql_real_escape_string($X);
//FIND AND GET THE ROW
$getit = mysql_query("SELECT * FROM table_name WHERE username='$safe_username'", $connect);
$row = mysql_fetch_array($getit);
//YOUR NEEDED VALUES
$bio = $row['bio'];
$email = $row['email'];
Note 1:
Dont Use Plain Text for Passwords, Always hash the passwords with a salt
Note 2:
I used MYSQL_QUERY for your code because i don't know PDO or Mysqli, Escaping in MYSQL is good enought but Consider Using PDO or Mysqli , as i don't know them i can't write the code with them for you
Simplistic PDO examples.
Create a connection to the database.
$link = new PDO("mysql:host=$db_server;dbname=$db_name", $db_user, $db_pw, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
$link->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
Use the $link variable when creating (preparing) and executing your SQL scripts.
$stmt = $link->prepare('insert into `history` (`user_id`) values(:userId)');
$stmt->execute(array(':userId' => $userId));
Code below will read data. Note that this code is only expecting one record (with 2 data elements) to be returned, so I'm storing whatever is returned into a single variable (per data element), $webId and $deviceId.
$stmt = $link->prepare('select `web_id`, `device_id` from `history` where `user_id` = :userId');
$stmt->execute(array(':userId' => $userId));
while($row = $stmt->fetch()) {
$webId = $row["web_id"];
$deviceId = $row["device_id"];
}
From the picture I can see you are using phpMyAdmin - a tool used to handle MySQL databases. You first must make a connection to the MySql server and then select a database to work with. This is shown how below:
<?php
$username = "your_name"; //Change to your server's username
$password = "your_password"; //Change to your server's password
$database = "your_database" //Change to your database name
$hostname = "localhost"; // Change to the location of your server (this will prolly be the same for you I believe tho
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
$selected = mysql_select_db($database, $dbhandle)
or die("Could not select examples");
?>
Then you can write something like this:
<?php
$bio = mysql_query("SELECT bio FROM *your_database_table_name* WHERE username='bob' AND id=1");
?>
and
<?php
$email = mysql_query("SELECT email FROM *your_database_table_name* WHERE username='bob' AND id=1");
?>
Where *your_database_table_name* is the table in the database you selected which you are trying to query.
When I was answering your question, I was referencing this site: http://webcheatsheet.com/PHP/connect_mysql_database.php. So it might help to check it out as well.

Categories