Inserting ID from primary col to another table - php

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();
}

Related

unable to update SQL table with php program

I have installed XAMPP and ensured that all the servers are running. I'm completely new to PHP and SQL
I configured a local database called test and a table called sensor.
I have added a user called arduino with a password.
pls ignore the comments
<?php
// Prepare variables for database connection
$dbusername = "arduino";
$dbpassword = "xxx";
$server = "localhost";
// Connect to your database
$dbconnect = new PDO('mysql:host=localhost;dbname=test;charset=utf8mb4', 'arduino', 'test');
// Prepare the SQL statement
$sql = "INSERT INTO test.sensor (value) VALUES ('".$_GET["value"]."')";
// Execute SQL statement
// mysql_query($sql);
?>
I want to use this set up to fetch data from arduino. Before connecting this set up to arduino, I wanted to ensure that this would be able to fetch data by passing http://localhost/write_data.php?value=100 to the browser. I was expecting that this would update the table with id, timestamp and value (of 100). It did not.
I had trouble with $dbconnect = mysql_pconnect($server, $dbusername, $dbpassword); and hence replaced that with $db = new PDO('mysql:host=localhost;dbname=test;charset=utf8mb4', 'arduino', 'test');
I also had trouble with mysql_query($sql);. So I have commented it out for now.
How can I get this to work? Where can I find easy to follow documentation for MySql replacements?
Updated Code based on answers
<?php
$dbusername = "arduino";
$dbpassword = "test";
$server = "localhost";
$dbconnect = new PDO('mysql:host=localhost;dbname=test;charset=utf8mb4', 'arduino', 'test');
$stmt = $dbconnect->prepare('insert into sensor(value) values(:val)');
$stmt->bindParam(':val', $_GET["value"], PDO::PARAM_INT);
$stmt->execute();
print "procedure returned $return_value\n";
?>
Brother checkout this example.. you have to bind get parameter in your query
Example:-
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT * FROM `$table` WHERE `$fieldname`=:id";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':id', $id);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
print_r($result);
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
You are not executing the SQL statement in your code. Try executing the below implementation :
$db = new PDO('mysql:host=localhost;dbname=rfid_db;charset=utf8mb4', 'username', 'password');
//$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); //optional
//$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); //optional
$stmt = $db->prepare('insert into sensor(value) values(:val)');
$stmt->bindParam(':val', $_GET["value"], PDO::PARAM_INT);
$stmt->execute();
Also for detailed study on PDO try referencing the documentation here http://php.net/manual/en/pdo.prepared-statements.php

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();
}

Separate connection from PDO

I am new to PDO. I try to understand.
What is the best way to separate the connection from the rest with PDO?
For instance. I have this code that works well:
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "podcast";
try {
$conn = new PDO("mysql:host=$servername; dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully <br>";
$sql = "SELECT podcast, text
FROM bookmarks
WHERE data = :data";
$statement = $conn->prepare($sql);
$data = 1;
$statement->bindValue(':data', $data);
$statement->execute();
echo $statement->rowCount() . " records SELECTED successfully <br>";
$rows = $statement->fetchAll();
foreach($rows as $row){
echo $row['podcast'] . '<br>';
echo $row['text'] . '<br>';
}
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
It could be useful to have the connection in a separate file. I tried that and it works well but I am not sure if it is the best way to do it. Is it ok to have the try-catch only with the connection?
index.php:
include("includes/connetion.php")
$sql = "SELECT podcast, text
FROM bookmarks
WHERE data = :data";
$statement = $conn->prepare($sql);
$data = 1;
$statement->bindValue(':data', $data);
$statement->execute();
echo $statement->rowCount() . " records SELECTED successfully <br>";
$rows = $statement->fetchAll();
foreach($rows as $row){
echo $row['podcast'] . '<br>';
echo $row['text'] . '<br>';
}
$conn = null;
connection.php:
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "podcast";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// $conn = new PDO("sqlite:/Applications/MAMP/db/sqlite/podcast", $username, $password); //Lite
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully <br>";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?>
I tried that and it works well but I am not sure if it is the best way to do it.
As long as your code is a usual spaghetti as shown above, it's all right with include.
Is it ok to have the try-catch only with the connection?
quite contrary, there shouldn't be a try catch with the connection as well:
"Catch an exception only if you have a handling scenario other than just reporting it. Otherwise just let it bubble up to a site-wide handler (note that you don't have to write one, there is a basic built-in handler in PHP, which is quite good)."
If you are trying to catch possible exception you have to do it everywhere you communicate with database. So you have to wrap try-catch also around code which ask database for some data.
Another step is to separate concepts of getting data from database representing them (sending them to output as you do it). You can check some MVC concept - how to do it.

PHP, MySQL Insert Into table in localhost

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).

Categories