SQL insert is not working - mysql

Please can someone help? The code below seems to work and gives no errors, but when I check the database, it hasn't added anything. Tearing my hair out!
<?php
$bcode = $_GET['barcode'];
$businessid = $_GET['businessid'];
$servername = "---------";
$username = "-------";
$password = "-------";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO 'db741921215'.'Scans' (Barcode, Success, Business) VALUES ('".$barcode."', 'Y', '".$businessid."')";
$con->close();
} ?>
The columns in table 'Scans' is as below:
Help is very, very much appreciated!!!

I see a couple things - use backticks "`" around your table name definitions, not single quotes. Also, save yourself some eye strain and use the fact that PHP interpolates variables just fine within doublequoted strings.
$sql = "INSERT INTO `db741921215`.`Scans`
(Barcode, Success, Business)
VALUES
('$barcode', 'Y', '$businessid')";
Also - you never actual execute the query, do you?
$conn->query($sql);

You seem to be missing the step where you execute the sql statement
I can see where you define it but I don't see where it's executed. i.e.
$conn->query($sql);
Also, you seem to be missing a letter when closing the connection: $con->close() should be $conn->close();

Related

Using PDO_MYSQL DSN and Adding Attributes to the Array

I'm trying to create a secure, SQL-injection proof connection to a database using PDO. I've know certain character sets are vulnerable, but that UTF-8 is not one of them. I also know that I should turn PDO's prepared statement emulation mode off. Below is the code that I've put together for the connection. My question is twofold.
Can someone please take a look at my code below to make sure that I'm doing everything correctly? I've tested it, and it works. But is there something else I could add to make it more secure or am I doing it right?
I'm not 100% positive that my syntax for what's inside the array is correct, though I don't get any errors when I do an insert, so I'm inclined to believe that it is. However, is there a way to test or confirm that those attributes are actually being set? Or can someone tell by looking that the syntax is correct and those attributes are definitely being set?
Thanks for any help in advance. My full code for the database connection and an insert using a prepared statement is below.
function addItem($category, $item, $price) {
$dsn = 'mysql:host=localhost;dbname=myDatabase;charset=utf8';
$username = "myUsername";
$password = "myPassword";
$options = array(
PDO::ATTR_EMULATE_PREPARES => false,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
try {
$link = new PDO($dsn, $username, $password, $options);
$query = $link->prepare("INSERT INTO items (category, item, price)
VALUES (:category, :item, :price)");
$query->bindParam(':category', $category);
$query->bindParam(':item', $item);
$query->bindParam(':price', $price);
$query->execute();
echo "New item added successfully";
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
$link = null;
}

INSERT INTO MYSQL - Can´t insert data

After a couple of week´s trying to insert data in variables from form in MYSQL database, i´m asking here. I found a lot of example codes of INSERT INTO and also my provider checked my skript. He said I have a problem in my $sql=.
I tryed a lot of, but i can´t see any data in phpMyAdmin after click submit, but i receive the mail, that works fine.
Maybe anybody can see an issue in my script.
<?php
if(isset($_POST["sendcopy"])){
mail($mailToCC, $subject, $textCC, $from);
}
if(isset($_POST["submit"])){
$host_name = "database.myprovider";
$database = "db_name";
$user_name = "user_name";
$password = "*****************";
$connect = mysqli_connect($host_name, $user_name, $password, $database);
if (mysqli_connect_errno())
{
echo "KEINE VERBINDUNG MÖGLICH! " . mysqli_connect_error();
}
else
{
echo "ERFOLGREICHE VERBINDUNG ZUR DATENBANK!";}
$sql= 'INSERT INTO "offen"("id", "vorname", "nachname", "email", "telefon", "geburtsjahr", "postleitzahl", "datum", "stunde", "minute", "personen", "bereich", "nachricht")
VALUES ($id, $vorname, $nachname, $email, $tel, $geburtsjahr, $plz, $datum, $stunde, $minute, $personen, $bereich, $nachricht)';
mysql_close($connect);
}
include ("reservtrue.php");
exit;
?>
The "submit" comes from a <form> below.
<form method="post" action="mailer.php" onsubmit="return chkFormular()" name="Formular" id="formTemplate">
<table id="reservtable">
.
.
.
.
<input type="submit" name="submit" value="Reservieren" id="submit">
</td>
</tr>
</table>
</form>
I hope it´s no problem to use german words as variables, here in stackoverflow.
Thank´s for help.
EDIT
Thank you for you´r suggestions. I still can´t insert data from form to MYSQL. I changed my Code a bit. And if I paste the code into phpMyAdmin - SQL, it work´s! But not if I load my script to server and test my form in web.
This is my new Code:
<?php
error_reporting(E_ALL ^ E_NOTICE);
if(isset($_POST["submit"])){
$vorname = $_POST["Vorname"];
$nachname = $_POST["Nachname"];
$email = $_POST["Mailadresse"];
$tel = $_POST["Telefonnummer"];
$geburtsjahr = $_POST["Geburtsjahr"];
$plz = $_POST["PLZ"];
$datum = $_POST["Datum"];
$stunde = $_POST["Stunde"];
$minute = $_POST["Minute"];
$personen = $_POST["Personen"];
$bereich = $_POST["Bereich"];
$nachricht = $_POST["Nachricht"];
$host_name = "database.myprovider";
$database = "db_name";
$user_name = "user_name";
$password = "*****************";
$connect = mysqli_connect($host_name, $user_name, $password, $database);
if (mysqli_connect_errno())
{
echo "KEINE VERBINDUNG MÖGLICH! " . mysqli_connect_error();
}
else
{
echo "ERFOLGREICHE VERBINDUNG ZUR DATENBANK!";}
$insert = ("INSERT INTO offen(vorname, nachname, email, telefon, geburtsjahr, postleitzahl, datum, stunde, minute, personen, bereich, nachricht)
VALUES ('".$id."', '".$vorname."', '".$nachname."', '".$email."', '".$tel."', '".$geburtsjahr."', '".$plz."', '".$datum."', '".$stunde."', '".$minute."', '".$personen."', '".$bereich2."', '".$nachricht."')");
mysqli_query($insert, $sql);
}
include ("reservtrue.php");
exit;
?>
Problem solved
Problem is solved with following code:
$insert = "INSERT INTO `offene`
(
`id`, `vorname`, `nachname`, `email`, `telefon`, `geburtsjahr`, `postleitzahl`, `datum`, `stunde`, `minute`, `personen`, `bereich`, `nachricht`
)
VALUES
(
NULL, '$vorname', '$nachname', '$email', '$tel', '$geburtsjahr', '$plz', '$datum', '$stunde', '$minute', '$personen', '$bereich', '$nachricht');";
mysqli_query($connect, $insert);
Thank you guy´s for information, inspriation and tips! I learnd a lot in the last 2 days.
Where is your mysql_query($sql); ? Add this after your $sql. Your $sql query require mysql_query to run it. If you added that and it still doesn't work, I suggest your go to phpmyadmin's sql tab. Paste your query in with some random VALUES. That's how I check if my query is working or not.
echo "ERFOLGREICHE VERBINDUNG ZUR DATENBANK!";}
$sql= 'INSERT INTO offen (id, vorname, nachname, email, telefon, geburtsjahr, postleitzahl, datum, stunde, minute, personen, bereich, nachricht)
VALUES ('$id', '$vorname', '$nachname', '$email', '$tel', '$geburtsjahr', '$plz', '$datum', '$stunde', '$minute', '$personen', '$bereich', '$nachricht')';
mysqli_query($connect,$sql); //this line was missing from your code.
mysqli_close($connect); //updated to make it MySQLi
The mysqli_query($connect,$sql) actually does the work of applying the SQL you define in the $sql query.
NOTE
You have both MySQLi and MySQL functions in your script, you must stick with just one function, ALL your SQL functions must be MySQL i .
I would recommend that you change your SQL query to use single quotes and backticks. The table name offen and the column names do not need to be in quotes. The variables you insert do need to be in quotes, as I have illustrated.
You do not (usually) need to have mysqli_close because the SQL connection automatically closes once the PHP reaches the end of the page.
The variable names don't need quotes but the parametes do. Also you are missing the code to execute the SQL statement.
echo "ERFOLGREICHE VERBINDUNG ZUR DATENBANK!";}
$sql= "INSERT INTO offen(id, vorname, nachname, email, telefon, geburtsjahr, postleitzahl, datum, stunde, minute, personen, bereich, nachricht)
VALUES ($id, '$vorname', '$nachname', '$email', '$tel', '$geburtsjahr', '$plz', '$datum', '$stunde', '$minute', '$personen', '$bereich', '$nachricht')";
if ($connect->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $connect->error;
}
mysql_close($connect);
}
It appears you have some understandable confusion about quoting of the variables in $insert. You likely have a problem with how you are handling your datatypes.
Here are a few things to look out for
You have too many quotes around your variables. Wrap the query in "" but save the '' for individual variables (where necessary, seen below). For instance, just wrap the variable once like so: .'$vorname'.' if the variable you are inputting is a string. If it is an integer (INT variable type), leave the quotes off, e.g.$number`. In other words, input strings as strings, and INT as int.
If the variable you wish to input is set as auto-increment in your database (i.e. it is the primary key), you probably don't want to be inputting it at all. For example, in your case $id appears to be one. If this is true, you have the syntax backward. Just input it as NULL or leave it off the insert, like so: insert into tablename (id, vorname) values (NULL, '$vorname')
You need to also sanitize your ALL of your variables if you to prevent SQL Injection (very possible with your code). You can do this with mysqli_real_escape_string()
OR instead of going through all of that, you could use prepared statements, which would both handle that information in a cleaner way, but also would protect your code against SQL injection.
Here's how to do this using mysqli:
Connect as an object:
$connect = new mysqli($host_name, $user_name, $password, $database);
And then feed your query into the object and bind the parameters. In this section, "s" is a string, "i" is an integer.
$insert = $connect->prepare("INSERT INTO offen(id, vorname, nachname, email)
VALUES (NULL, ?,?,?");
$insert->bind_param("sss", $vorname, $nachname, $email);
$insert->execute();
$insert->close();
If you name your variables correctly, this should work.

Admin panel - Creating an edit users button

I've created an admin panel on my website so when the admin logs in he can edit users. I'm trying to get it to create a table that displays a list of all the users on the database, however, when I run it I get the error:
No database selected
Here is the code in my editusers.php:
<?php
include 'adminpage.php';
include 'connection.php';
$sql = "SELECT * FROM Users";
$result = mysql_query($sql)or die(mysql_error());
echo "<table>";
echo "<tr><th>UserID</th><th>First Name</th><th>Last Name</th><th>Email</th><th>D-O-B</th></tr>Username</th><th>Password</th><th>";
while($row = mysql_fetch_array($result)){
$userid = $row['UserID'];
$firstname = $row['FirstName'];
$lastname = $row['LastName'];
$email = $row['Email'];
$dob = $row['DateofBirth'];
$username = $row['Username'];
$password = $row['Password'];
// Now for each looped row
echo "<tr><td style='width: 200px;'>".$userid."</td><td style='width: 200px;'>".$firstname."</td><td>".$scale."</td><td>".$lastname."</td><td>".$email."</td></tr>".$dob."</td></tr>".$username."</td></tr>".$password."</td></tr>";
} // End our while loop
echo "</table>"
?>
First of all it looks like you are using mysql which isn't a wise move. This is because Mysql is actually deprecated and was improved to mysqli. Your problem may be to do with your database connection. You also haven't set a database. Like I said you can set an active database in your connection script. It should or could look something like this.
<?php
$conn = mysqli_connect("localhost", "root", "password", "database");
// Evaluate the connection
if (mysqli_connect_errno()) {
echo mysqli_connect_error();
exit();
}
?>
After that, your sql query is correct by selecting all from you table 'users' but in order to proceed I recommend creating a query where you use mysqli_query an select the $sql and $conn as parameters. In all honesty it is much advised to stop and continue once you have adapted to mysqli. Alternatively you can use PDO which in some cases can be seen as better to use rather than mysqli but the choice is yours. I personally would get to grips with mysqli and then look at some answers on Stack Overflow to decide whether you should use PDO or not. Visit the PHP manual here. Enter all the mysql functions you know and it will show you how to use the new mysqli version of the functions. Don't think that it is as simple as just adding and 'i' to the end of a mysql function. That's what I initially thought but there is alot to do with extra parameters etc. Hope this helps :-)

mysql query run only for numbers

$username = $_POST['username'];
$password = $_POST['password'];
$passworda = $_POST['passworda'];
$email = $_POST['email'];
if ($password == $passworda){
echo 'this is the user name to be chacked:' .$username .'<br>';
$query = "SELECT username FROM mishta where username=$username";
$queryrun = mysql_query($query);
echo $queryrun .'<br>';
echo mysql_num_rows($queryrun) .'<br>';
if (mysql_num_rows($queryrun)!=1){
mysql_query("INSERT INTO mishta(id, username, password, email) VALUES ('', '$username','$password','$email')");
}
else{
echo 'user already exist';
}
Hello there,
I'm trying to make a simple registration form, I get useername from html form and I want to make sure it doesn't already exist in my database.
the thing is that whenever I run the username as a number (1,2,3...) it runs smoothly.
but, when I try to write anything with letter, like Bob or Dora I get the following error:
Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in...
Yet the information is still being stored my my data base, means it got false on the last if statement, and it will continue to get false (It will just insert duplicates if I try again).
Any help would be appreciated.
You forgot the quotes around the username:
$query = "SELECT username FROM mishta where username='$username'"
Quotes are used as string delimiter. Numbers are not string and it works if you use a number.

Need help connecting to my Mysql database on local server

I'm quite new to databases and have no idea where I have gone wrong. Please help me find out why I can't connect to my database.
I'm getting an error with Dreamweaver - Dynamicaly-related files cannot be discovered because there is no site definition for this document
My Site root is located in htdocs.
the main file I'm trying to run is "dataquery.php" - htdocs/LetsPlays/dataquery.php
<?php
include 'includes/databaseform.php';
$query = "SELECT * FROM userchanel";
$result = mysql_query($query);
while($person = mysql_fetch_array($result));
{
echo $person['chanelurl'];
}
?>
Dataquery is connected to "databaseform.php" - htdocs/LetsPLays/includes/databaseform.php
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass ='';
$db = 'mysql_tut';
$conn = mysql_connect($dbhost,$dbuser,$dbpas);
mysql_select_db($userchanel);
?>
So I'm trying to connect to userchanel table through user tbl
screenshot: http://imageshack.us/f/23/usertbl.png/
Files run through wordpress are set up to run on 127.0.0.1
Please help me.
Sorry for the noobishness! I have no idea what I'm missing!
When I run the html file all I get is a blank page!
Replace the line
$conn = mysql_connect($dbhost,$dbuser,$dbpas);
with
$conn = mysql_connect($dbhost,$dbuser,$dbpass);
notice the double 's' on $dbpass, also if I may you should not rely on deprecated features when writing new code, use PDO instead, also don't login to db as root, create a user, don't be lazy, with that your database connection code should like:
<?php
$db = new PDO('mysql:dbname=databasename', 'username', 'password',
array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
the init command is not actually necessary I just included it cause I always use it, while the querying could be done as
<?php
include 'includes/databaseform.php';
$query = $db->prepare("SELECT * FROM userchanel");
$query->execute();
while(($person = $query->fetch(PDO::FETCH_ASSOC)) !== false);
{
echo $person['chanelurl'];
}
If you're only using one column you should fetch only that as below:
<?php
include 'includes/databaseform.php';
$query = $db->prepare("SELECT chanelurl FROM userchanel");
$query->execute();
while(($channelurl = $query->fetch(PDO::COLUMN)) !== false);
{
echo $channelurl;
}
I didn't include closing braces for php code as they are not necessary also do some error checking var_dump($db->errorInfo()); and var_dump($query->errorInfo()); - didn't include this in the code as I only use them in checking any issues with my code, good luck!
instead of htdocs/LetsPlays/dataquery.php
try localhost/dataquery.php
I recommend you to make and additional file for database connection and include it anywhere you need. Because when you need to push project live you need to change in every file incase file is includeed you need to change just at one place and it effects every where connection for localhost is
<?php
// Replace the variable values below
// with your specific database information.
$host = "localhost";
$user = "root";
$pass = "";
$db = "yourdatabase";
// This part sets up the connection to the
// database (so you don't need to reopen the connection
// again on the same page).
$ms = mysql_pconnect($host, $user, $pass);
if ( !$ms )
{
echo "Error connecting to database.\n";
}
// Then you need to make sure the database you want
// is selected.
mysql_select_db($db);
?>
Save all the above code in one file save it as dbConfig.php and include it any where
like
include ("dbConfig.php");
Now in that file you are connected to db you can interact with database.