PHP, MySQL Insert Into table in localhost - php

I'm pretty new to MySQL and PHP, and I had a little problem with Inserting into table.
I have build 'setup.php' that have all MySQL codes but I didn't know how to included correctly to 'index.php'.
I tried to separate the code as the following, but still didn't work. I don't know what's the problem here, is it the code itself? or the way i included it? Please help me fix it.
index.php, The code is right after body element.
if (isset($_POST['name']) &&
isset($_POST['email']) &&
isset($_POST['place']) &&
isset($_POST['level'])) {
include "setup.php";
$name = sanitizeString($_POST['name']);
$email = sanitizeString($_POST['email']);
$place = sanitizeString($_POST['place']);
$level = sanitizeString($_POST['level']);
$query = "INSERT INTO customers VALUES('$name', '$email', '$place', '$level')";
queryMysql($query);
}
setup.php
<?php
$dbhost = 'localhost';
$dbname = 'applicants';
$dbuser = 'root';
$dbpass = 'root';
mysql_connect($dbhost, $dbuser, $dbpass) or die(mysql_error());
mysql_select_db($dbname) or die(mysql_error());
function createTable($name, $query) {
if (tableExists($name)) {
echo "Table $name already exists";
}
else {
queryMysql("CREATE TABLE $name($query)");
}
}
function tableExists($name) {
$result = queryMysql("SHOW TABLES LIKE $name");
return mysql_num_rows($result);
}
function queryMysql($query) {
$result = mysql_query($query);
return $result;
}
createTable('customers',
'name VARCHAR(16),
email VARCHAR(16),
place VARCHAR(16),
level VARCHAR(16)');

Using PDO is a better approach:
function validatePost($post) {
return (isset($post['name']) &&
isset($post['email']) &&
isset($post['place']) &&
isset($post['level']));
}
function createTable(PDO $pdo, $name, $query) {
if (tableExists($pdo, $name)) {
throw new Exception("Table already exists");
}
$pdo->query("CREATE TABLE $name($query)");
}
function tableExists(PDO $pdo, $name) {
$result = $pdo->query("SHOW TABLES LIKE $name");
return count($result->fetchAll());
}
$dbhost = 'localhost';
$dbname = 'applicants';
$dbuser = 'root';
$dbpass = 'root';
validatePost($_POST);
try {
$pdo = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
createTable($pdo, "customers",
"name VARCHAR(16),
email VARCHAR(16),
place VARCHAR(16),
level VARCHAR(16)");
$stmt = $pdo->prepare("INSERT INTO `customers` (`name`, `email`, `place`, `level`) VALUES(:name, :email, :place, :level)");
$stmt->bindParam(":name", $_POST["name"]);
$stmt->bindParam(":email", $_POST["email"]);
$stmt->bindParam(":place", $_POST["place"]);
$stmt->bindParam(":level", $_POST["level"]);
$stmt->execute();
}
catch (PDOException $e) {
echo "There was an error regarding the Database: " . $e->getMessage();
die();
}
catch (Exception $e) {
echo "Error! " . $e->getMessage();
}
You have a PDO object which acts as the connection, it is then passed around the functions in order to operate.
Points
PDO supports prepared statements, which removes the need to sanitize (the prepared statement does it for you!)
When inserting, it's considered a good practice to expicitely declare which column gets what, I've assumed the names of your columns, but you should change them if they don't match.
Don't echo, throw Exceptions. Throwing an exception allows you to deal with problems and errors in your code much more efficiently and easily. You throw an exception and catch it where it may occur. An uncaught (catched) exception will terminate the script.

In index.php, the query should be
mysql_query($query)
not queryMysql.
Plus, make sure you are inserting every field in the database. If you have auto increment field or field which you aren't using, use this syntax
INSERT INTO products (column 1, column 2) VALUES (value1, value2)
p.s. Change your all queryMysql to mysql_query(). I believe there's no function like queryMysql (i have stopped using this mysql_* functions long ago so i could be wrong but about mysql_query() i am sure that it'l work).

Related

Inserting ID from primary col to another table

I want to insert 2 tables columns ids to another table
I got the query but there is the annoying error.
I tried to solve this problem for hours none worked :(
This code:
$query = "INSERT INTO
groups(
group_school_id,
group_teacher_id,
group_name,
group_note,
group_system,
group_students_count
)
VALUES(
$group_shcool_id,
$group_teacher_id,
'$group_name',
'$group_note',
'$group_system',
'$group_students_count'
)";
this old:
<?php
$db['db_host'] = "localhost";
$db['db_user'] = "admin";
$db['db_pass'] = "1998";
$db['db_name'] = "ahlquran";
foreach ($db as $key => $value) {
define(strtoupper($key), $value);
}
$con = mysqli_connect(DB_HOST,DB_USER,DB_PASS,DB_NAME);
mysqli_query($con, "SET NAMES 'utf8'");
}
?>
this new:
<?php
// if you are using php just don't forget to add php tags though
$db['db_host'] = "localhost";
$db['db_user'] = "admin";
$db['db_pass'] = "1998";
$db['db_name'] = "ahlquran";
foreach ($db as $key => $value) {
define(strtoupper($key), $value);
}
//using try catch statements
try{
$conn = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME, DB_USER, DB_PASS);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Successfully Connected";
}
catch(PDOException $e){
echo "Connection Failed" .$e->getMessage();
}
?>
its connects successfully but all my code use the old one, how to change to convert it? I dont know what pdo I like to learn it, it seems more pro type, but is there solution for this site only using mysqli?
sorry for the long post this is my 1st one, dont know how to explain enough
Thanks
give this error :
QUERY FAILED .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 ' , 'test', '', 'test' at line 11
I thought it will work fine like this but I think the problem with the query syntax.
Just an advice try to use PDO prepared statements example below:
$query = "INSERT INTO groups(group_school_id,
group_teacher_id,
group_name,
group_note,
group_system,
group_students_count)
VALUES (:gsid,:gtid,:gname,:gnote,:gsystem,:gstudcount)";
//assuming $conn is your object variable name for database connection
$stmnt = $conn->prepare($query);
$stmnt->execute(array(':gsid'=>$group_school_id,
':gtid'=>$group_teacher_id,
':gname'=>$group_name,
':gnote'=>$group_note,
':gsystem'=>$group_system,
':gstudcount'=>$group_students_count));
//to check if you have inserted data into your table
$rows = $stmnt->rowCount();
echo "Inserted ".$rows." row";
the :gsid are placeholders for your variables, also make sure that each variable passed are inline with column datatypes in your database
//if you are using php just don't forget to add php tags though
$dbhost = "localhost";
$dbname = "whatevername";
$dbuser = "root";
$dbpass = "";
//using try catch statements
try{
$conn = new PDO('mysql:host='.$dbhost.';dbname='.$dbname, $dbuser, $dbpass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Successfully Connected";
}
catch(PDOException $e){
echo "Connection Failed" .$e->getMessage();
}

Updating data in DataBase with PHP

I have a simple script that should Update variable in a column where user login equals some login.
<?PHP
$login = $_POST['login'];
$column= $_POST['column'];
$number = $_POST['number'];
$link = mysqli_connect("localhost", "id3008526_root", "12345", "id3008526_test");
$ins = mysqli_query($link, "UPDATE test_table SET '$column' = '$number' WHERE log = '$login'");
if ($ins)
die ("TRUE");
else
die ("FALSE");
?>
but it doesn't work. It gives me - FALSE. One of my columns name is w1 and if I replace '$column' in the code with w1 it works fine. Any suggestions?
Simply remove quotes: '$column' = should be $column =
Your code is open for SQL Injection, use prepared statements.
change this "UPDATE test_table SET '$column' = '$number' WHERE log = '$login'"
to this "UPDATE test_table SET '".$column."' = ".$number." WHERE log = '".$login."'"
It's possible that your error is to do with the $column being set as a string with single quotation marks? Because it returns false, it suggests that you have a MySQL error of some sort.
To find out what the error message is, on your else block, rather than dying with a "FALSE" message, try use mysqli_error($link) - this should give you your error message
If removing the quotes surrounding the $column doesn't work, you could try the PDO method. Here's the snippet:
function insertUser($column, $number, $login) {
try
{
$connect = getConnection(); //db connection
$sql = "UPDATE test_table SET $column = '$number' WHERE log = '$login'";
$connect->exec($sql);
$connect = null;
} catch (Exception $ex) {
echo "EXCEPTION : Insert failed : " . $ex->getMessage();
}
}
function getConnection() {
$servername = "localhost";
$dbname = "my_db";
$username = "root";
$password = "12345";
try {
$connection = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (Exception $ex) {
echo "EXCEPTION: Connection failed : " . $ex->getMessage();
}
return $connection;
}
Regarding $number, I'm not sure the datatype for the $number whether quotes or not is needed so experiment with or without quotes to see which one works.
And the getConnection() function is in separate PHP file where it will be included in any PHP files that calls for database connection.

I am trying to add some data in database using PHP, but it does not work

This is my PHP code starting and used connection type is PDO.
//connection with server
$servername = "localhost";
$username = "root";
$password = "";
try {
$conn = new PDO("mysql:host=$servername;dbname=gujaratoil", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
if(isset($_POST['submit']))
{
//at the beginning null value is set
$name = $emailaddress="";
$sql = "INSERT INTO
registration(name,emailaddress)VALUES('$_POST[name]','$_POST[emailaddre
ss]')";
}
?>
I have tried all the solutions available; what should I do to solve this issue? I am using a PDO connection.
When using PDO you should use prepared statements rather than directly embedding variables in the SQL.
The reason, I believe, given the code above why the insert was failing was / is due to the lack of quotes around field names within $_POST[] ~ ie $_POST[name] which is likely to be causing undeclared constant errors
$name=$_POST['name'];
$email=$_POSt['emailaddress'];
$sql='insert into `registration` ( `name`, `emailaddress` ) values ( :name, :email )';
$stmt=$conn->prepare( $sql );
if( $stmt ){
$stmt->bindParam(':name',$name);
$stmt->bindParam(':email',$email);
$stmt->execute();
}

PHP bindParam not working - blindValue is not the solution

I can't figure this out. I've googled it and a lot of answers refer to blindValue as the solution but I've also tried that with no luck.
The problem is that the SELECT statement is returning zero records but it should return one record. If I hard code the values into the SQL statement it works but passing them in as parameters isn't. Can some one please help me out with this? Thanks.
<?php
function checklogin($email, $password){
try
{
// Connection
$conn;
include_once('connect.php');
// Build Query
$sql = 'SELECT pkUserID, Email, Password, fkUserGroupID FROM tbluser WHERE Email = :email AND Password = :password';
// $sql = 'SELECT pkUserID, Email, Password, fkUserGroupID FROM tbluser WHERE Email = "a" AND Password = "a"';
// Prepare the SQL statement.
$stmt = $conn->prepare($sql);
// Add the value to the SQL statement
$stmt->bindParam(':email', $email, PDO::PARAM_STR);
$stmt->bindParam(':password', $password, PDO::PARAM_STR);
// Execute SQL
$stmt->execute();
// Get the data in the result object
$result = $stmt->fetchAll(); // $result is NULL always...
// echo $stmt->rowCount(); // rowCount is always ZERO....
// Check that we have some data
if ($result != null)
{
// Start session
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
// Search the results
foreach($result as $row){
// Set global environment variables with the key fields required
$_SESSION['UserID'] = $row['pkUserID'];
$_SESSION['Email'] = $row['Email'];
}
echo 'yippee';
// Return empty string
return '';
}
else {
// Failed login
return 'Login unsuccessful!';
}
$conn = null;
}
catch (PDOexception $e)
{
return 'Login failed: ' . $e->getMessage();
}
}
?>
the connect code is;
<?php
$servername = 'localhost';
$username = 'admin';
$password = 'password';
try {
// Change this line to connect to different database
// Also enable the extension in the php.ini for new database engine.
$conn = new PDO('mysql:host=localhost;dbname=database', $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// echo 'Connected successfully';
}
catch(PDOException $e)
{
echo 'Connection failed: ' . $e->getMessage();
}
?>
I'm connecting to mySQL. Thanks for the help,
Jim
It was a simple but stupid error.
I had a variable called $password also in the connect.php file which was overwriting the $password that I was passing to the checklogin.
Jim

PHP PDO prepared insert - does not insert data and show no errors [duplicate]

This question already has answers here:
Why does this PDO statement silently fail?
(2 answers)
Closed 2 years ago.
This problem is driving me crazy, i tried everything. Is does not give me any error, but it does not insert anything to the database either. Database connection is good, and there should be no typos. Please take a look, and see if you can find the problem:
$err = array();
if (isset($_POST['submit'])) {
$ip = gethostbyname($_SERVER['REMOTE_ADDR']);
$date = "2012-02-02 02:02:02"; //Example
$uploader_name = $_POST['uploader_name'];
// Validation happens here...
if (empty($err)) {
$host = "host";
$dbname = "db";
$user = "user";
$pass = "pass";
try {
$dbh = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
$sql = "INSERT INTO `table` (`ip`, `date`, `uploader_name`)
VALUES (:ip, :date, :uploader_name)";
$stmt = $dbh->prepare($sql);
# the data we want to insert
$params = array(
':ip' => $ip,
':date' => $date,
':uploader_name' => $uploader_name
);
$stmt->execute($params);
$dbh = null;
} catch(PDOException $pe) {
die('SQL Error');
}
if (empty($err)) {
$err[] = "Success!";
}
}
}
Also, Im sure it gets to the insert part, because i get the 'Success' message.
Use this code to execute your statement. If there is a non-fatal error, it will display it.
$stmt->execute($params) or die(print_r($stmt->errorInfo(), true));
Almost certainly your db user does not have permissions to execute the statement you're asking against the table you're trying to execute against.
Are you using auto-commit? If not you may need to wrap your query in a transaction.
try
{
$dbh->beginTransaction();
// your code.
$dbh->commit();
}
catch(PDOException $pe)
{
$dbh->rollback();
die($pe->getMessage());
}
http://php.net/manual/en/pdo.transactions.php

Categories