How to give validation with statement of value on database table - php

i've problem while i make an insert function using php. i dont know how to give a validation while inserting data to database. my insert function using of the other data table from the database (copying data from other table to another).
somebody know how to give a validation with that data. not from a textbox value or input value from the form. but validation from the data in the database.
please help me out my trouble. im very appreciated when you give me an example.
this is my code for insert data (copying data from the other table to another).
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "", "silo");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Attempt insert query execution
$sql="Insert into termocouple
Select * from temp1";
if(mysqli_query($link, $sql)){
echo "Records inserted successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Close connection
mysqli_close($link);
?>

Related

Pushing Attachment Path to DB table

I've updated my project to it's almost final form and made a small change. The suggestion of #Raghbendra Nayak worked before the change and now, I'm trying to incorporate it to my new form. After 'submit' it pushes the item to the folder still and the link to the DB, however the link is on a separate row and not on the same row where the data name-description written is found.
Update: Got it working guys. Thanks!
You can simply follow the below code to insert data in database why you are using mysqli_connect to run the insert query.
Updated:
Change your if condition:
if(move_uploaded_file($file['tmp_name'],$upload_directory.$path)){
mysqli_connect("localhost", "root", "", "order") or die ("Connecting to DB failed");
mysqli_connect("INSERT INTO item VALUES ('', '$path')");
}
To
if(move_uploaded_file($_FILES['filename']['tmp_name'],$upload_directory.$path)){
$conn = mysqli_connect("localhost", "root", "", "order") or die ("Connecting to DB failed");
// If you want to save image name you can get like below:
$filename = $_FILES["filename"]["name"];
$path = $path."/".$filename;
$sql = "INSERT INTO item (path) VALUES ('$path')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
You have to add your image name also. Hope it will work for you, let me know it anything required.

PHP/MySQL query not working with no error

I have written that seems to not be working, but MySQL does not return any error. It is supposed to get data from database1.table to update database2.table.column
<?php
$dbh1 = mysql_connect('localhost', 'tendesig_zink', 'password') or die("Unable to connect to MySQL");
$dbh2 = mysql_connect('localhost', 'tendesig_zink', 'password', true) or die("Unable to connect to MySQL");
mysql_select_db('tendesig_zink_dev', $dbh1);
mysql_select_db('tendesig_zink_production', $dbh2);
$query = " UPDATE
tendesig_zink_dev.euid0_hikashop_product,
tendeig_zink_production.euid0_hikashop_product
SET
tendesig_zink_dev.euid0_hikashop_product.product_quantity = tendesig_zink_production.euid0_hikashop_product.product_quantity
WHERE
tendesig_zink_dev.euid0_hikashop_product.product_id = tendesig_zink_production.euid0_hikashop_product.product_id";
if (mysql_query($query, $dbh1 ))
{
echo "Record inserted";
}
else
{
echo "Error inserting record: " . mysql_error();
}
?>
The manual page for mysql_error() mentions this about the optional parameter you're omitting:
link_identifier
The MySQL connection. If the link identifier is not
specified, the last link opened by mysql_connect() is assumed. If no
such link is found, it will try to create one as if mysql_connect()
was called with no arguments. If no connection is found or
established, an E_WARNING level error is generated.
So it's reading errors from $dbh2, which is the last connection you've opened. However, you never run any query on $dbh2:
mysql_query($query, $dbh1 )
Thus you get no errors because you are reading errors from the wrong connection.
The solution is to be explicit:
mysql_error($dbh1)
As about what you're trying to accomplish, while you can open as many connections as you want, those connections won't merge as you seem to expect: they're independent sessions to all effects.
All your tables are on the same server and you connect with the same users, there's absolutely no need to even use two connections anyway.
You can't just issue a cross-database update statement from PHP like that!
You will need to execute a query to read data from the source db (execute that on the source database connection: $dbh2 in your example) and then separately write and execute a query to insert/update the target database (execute the insert/update query on the target database connection: $dbh1 in your example).
Essentially, you'll end up with a loop that reads data from the source, and executes the update query on each iteration, for each value you're reading from the source.
I appreciate everyone's help/banter, here is what finally worked for me.
<?php
$dba = mysqli_connect('localhost', 'tendesig_zink', 'pswd', 'tendesig_zink_production') or die("Unable to connect to MySQL");
$query = " UPDATE
tendesig_zink_dev.euid0_hikashop_product, tendesig_zink_production.euid0_hikashop_product
SET
tendesig_zink_dev.euid0_hikashop_product.product_quantity = tendesig_zink_production.euid0_hikashop_product.product_quantity
WHERE
tendesig_zink_dev.euid0_hikashop_product.product_id = tendesig_zink_production.euid0_hikashop_product.product_id";
if (mysqli_query($dba, $query))
{
echo "Records inserted";
}
else
{
echo "Error inserting records: " . mysqli_error($dba);
}
?>

Database cannot create a record when a text value is entered ($_POST)

Perhaps I'm making some obvious beginner mistake, but I just cannot seem to figure out why this happens.
Strangely enough, the code only seems to work properly if I enter a number into the "inputbox". I check this in the myphpadmin panel, and it shows a new record has been created. However, if I attempt to input a string as intended for my purposes (example: "hello") no new record appears in the database...
In short, the database only updates if I put a number into the "inputbox" but not when I enter a string.
Any ideas why this may be happening? It's driving me crazy. If it helps, the data type of the "Company" field is VARCHAR and the collation is set to latin1_swedish_ci
The PHP code is as follows:
<?php
//Retrieve data from 'inputbox' textbox
if (isset($_POST['submitbutton']))
{
$comprating = $_POST['inputbox'];
//Create connection
$con = mysqli_connect("localhost","root","","test_db");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//Insert data into 'Ratings' table
mysqli_query($con,"INSERT INTO Ratings (Company,Score)
VALUES ($comprating,1)");
mysqli_close($con);
}
?>
The HTML code is:
<form method="post">
<input type="text" name="inputbox">
<input type="submit" name="submitbutton">
</form>
Cheers
Try this query,
mysqli_query($con,"INSERT INTO Ratings (Company,Score)
VALUES ('$comprating',1)");`
^ ^
Note the single quotes that reserves the string value and don't forget to sanitize the input before inserting them to database.
Sample standard escaping:
$comprating = mysqli_real_escape_string($comprating) before executing a query that uses $comprating
Hi here is the objected oriented method and also its secure because data binding is used in mysqli. I recommend to use this.
if (isset($_POST['submitbutton'])) {
$comprating = $_POST['inputbox'];
$mysqli = new mysqli("localhost", "root", "", "test_db");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$stmt = $mysqli->prepare("INSERT INTO Ratings (Company,Score) VALUES (?, ?)");
$stmt->bind_param($comprating, 1);
/* execute prepared statement */
$stmt->execute();
printf("%d Row inserted.\n", $stmt->affected_rows);
/* close statement and connection */
$mysqli->close();
}
feel free to ask any questions if you have..

Error:NO database is selected

I tried it connection to database connection to database is successful but when i try to match user information with database it gives me a error NO database is selected
i tried it connecting to database using different method but nothing worked
<?php
//CREATING CONNECTION TO DATABASE
$con= new mysqli("localhost", "****", "***", "*****");
$con->select_db("lel_server_user_db_secured");
if(mysqli_connect_errno())
{
echo "Problem With connection to database Please contact administrator regarding this error";
}
/* RETURNS NAME OF DEFAULT DATABASE
if ($result = $con->query("SELECT DATABASE()")) {
$row = $result->fetch_row();
printf("Default database is %s.\n", $row[0]);
$result->close();
}
*/
/*
$host="localhost";
$db_user="sky.xpert";
$db_pass="havefun344";
$database="lel_server_user_db_secured";
mysqli_connect($host,$db_user,$db_pass,$database) or die ("Failed to connect");
mysqli_select_db($database) ;
*/
session_start();
//GATHERING DATA FROM USER FORM
$email=$_POST["login"];
$pass=$_POST["pwd"];
//COMMANDING WHERE TO FIND MATCH FOR LGOIN INFORMATION
$veryfy="SELECT * FROM users WHERE Email='$email' Password='$pass'";
$query=mysql_query($veryfy) or die ( mysql_error() );
$match=0;
$match=mysql_num_rows($query);
//IF MATCH FOUND THEN SETTING SESSION AND REDIRECTING IT TO LOGGED PAGE
if($match==1)
{
$_SESSION['loggedin'] = "true";
header ("Location: logged.php"); //REDIRECTING USER TO ITS HOMEPAGE
}
else //IF MATCH NOT FOUND THEN REDIRECTING IT BACK TO LOGIN PAGE
{
$_SESSION['loggedin'] = "false";
header ("Location: index.php");
}
//PERSONAL COMMENTS OR DETIALED COMMENTS
//PROBLEM WITH THIS SCRIPT GIVING OUTPUT ON LOGIN "NO DATABASE SELECTED"
//REFRENCE from http://www.dreamincode.net/forums/topic/52783-basic-login-script-with-php/
?>
You are initializing a connection to your database with mysqli. Then you try to do queries with mysql. Obviously, there is no connection with the database made through that library, and therefore it fails with an error. Change mysql_query to mysqli_query.
General note
Your current code is vulnerable to sql injection attacks, because you do not sanitize the input from the user before putting it in a query. Consider using prepared queries.
The database lel_server_user_db_secured may be not exist.
Content to your mysql:
mysql -hlocalhost -uusername -p
then input your password. After login, type command:
show databases;
check if lel_server_user_db_secured is in the result.
update1*
change the code below:
$veryfy="SELECT * FROM users WHERE Email='$email' Password='$pass'";
$query=mysql_query($veryfy) or die ( mysql_error() );
$match=0;
$match=mysql_num_rows($query);
to:
$veryfy="SELECT * FROM users WHERE Email='$email' Password='$pass'";
$result = mysqli_query($con, $veryfy) or die ( mysqli_connect_errno() );
$match=0;
$match=mysqli_num_rows($result);
var_dump($match);
In the first half of your program you have used mysqli and in the latter half mysql. Either use mysqli or mysql. I would recommend using mysqli in your entire program so that you are not vulnerable to SQL injection
you can simply do it by
$mysqli = new mysqli("localhost", "user", "password", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
there is no need to do $con->select_db("lel_server_user_db_secured"); again
and using mysqli isnt mean your code is safe ... your code is still vulnerable to SQL injection Use prepared statement instead or atleast mysqli_real_escape_string
You need to escape all request properly
and its possible that your database isnt exist so check that its exist first
AND you are mixing tow different API
you can not use MySQLi functions with MySQL_* function

Basic MySQL help? - submitting data

I've been getting better at PHP - but I have NO idea what I'm doing when it comes to MySQL.
I have a code
<IMG>
I need to grab the "for", "affi" and "reff" and input them into a database
//Start the DB Call
$mysqli = mysqli_init();
//Log in to the DB
if (!$mysqli) {
die('mysqli_init failed');
}
if (!$mysqli->options(MYSQLI_INIT_COMMAND, 'SET AUTOCOMMIT = 0')) {
die('Setting MYSQLI_INIT_COMMAND failed');
}
if (!$mysqli->options(MYSQLI_OPT_CONNECT_TIMEOUT, 5)) {
die('Setting MYSQLI_OPT_CONNECT_TIMEOUT failed');
}
if (!$mysqli->real_connect('localhost', 'USERNAME', 'PASSWORD', 'DATABASE')) {
die('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
That's what I'm using to create a connection. It works. I've also got a table created, call it "table", with rows for "for", "affi", and "reff".
So my question is... someone gets directed to http://www.example.com/test.php?for=abcde&affi=12345&reff=foo
Now that I've got a DB connection open - how do I SEND that data to the DB before redirecting them to their destination site? They click - pass across this page - get redirected to destination.
BONUS KARMA - I also need a separate PHP file that I can create that PULLS from that data base. If you could point me at some instructions or show me a simple "how to pull this rows values from this table" I would be greatly appreciative :)
If I understand correctly, you'll want to use $_GET to get the URL parameters.
Then you want to run an insert query on the db with the values you got, which should be something like:
INSERT INTO table VALUES(x, y, z)
Then you need to change the page using a location header.
For the bonus question you just need the code you have now with a select query like:
SELECT * FROM table WHERE 1;
and then fetch the query results.
If this does not answer your questions please provide some clarifications.
Mysqli is the deprecated function and now PDO is recommended to connect to database. You could do following.
<?php
$conn = new PDO('dblib:host=your_hostname;dbname=your_db;charset=UTF-8', $user, $pass);
$sql = "SELECT * FROM users WHERE username = '$username'";
$result = $conn->query($sql);
?>
Read more here.

Categories