I'm trying to insert some data into a mysql table but the process doesnt go through and I get nothing printed for the error. I don't think I'm outputting the errors correctly. Looking at php.net it seems like I'm doing the error handling properly but maybe I'm missing something.
Here is the code
$db = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
$sqlInsert = $db->query("INSERT INTO transactions(`user_id`, `courses`, `invoice`, `start_date`, `end_date`, `mc_gross`, `email`) VALUES ('".$user_id."','".$trim."','".$invoice."','".$start_date."','".$end_date."', '".$email."')");
if($sqlInsert)
{
echo "Inserted successfully";
}
else
{
printf("Error: ", $db->error);
}
The values for the variables are as follows
$custom = $_SESSION['custom'];
$user_id = $_POST['userID'];
$pwd = $_POST['password'];
$email = $_POST['email'];
$start_date = date('Y-m-d');
$end_date = date (('Y-m-d'), strtotime('+120 days'));
$invoice = date('Ymd'). mt_rand(1252,10000);
$invoice_check = $db->query("SELECT `invoice` FROM `transactions` WHERE `invoice` = $invoice");
while ($rows = $invoice_check->fetch_assoc())
{
$invoice = date('Ymd'). mt_rand(1252,10000);
}
$mc_gross = $_SESSION['subtotal'];
$trim = rtrim($custom, ",");
the var_dump for $trim is string(17) "bio_01,calculus_01" and the other variables just echo out normally as you'd expect.
Any ideas?
EDIT Updated the code with $db instead of $sqlInsert. Still no output for an error.
Change:
printf("Error: ", $sqlInsert->error);
to:
printf("Error: %s", $db->error);
You can't read the error property of false, because it's not an object. And you're missing the %s in the printf format string to substitute the argument.
Related
it's my first time working with php and after 2h of searching for my problem i came to the conclusion that i cant find and fix it.
I hope you guys can help me!
<?php
require "./config/_sqlconnect.php";
$temp = $_POST;
$vname = "Peter";
$nname = "Hans";
$straße ="XY";
$strnr ="8";
$plz = "9031";
$ort = "würzburg";
$land ="deutschland";
$tel ="1334134";
$email ="asdas#aasd.com";
$datum ="21.03.1942";
$anrede ="herr";
$connection = mysql_connect($dbhost, $dbuser, $dbpass, $dbname) or die
("Verbindungsversuch fehlgeschlagen");
mysql_select_db($dbname, $connection) or die('DB FAIL');
$sql = "INSERT INTO tadresse (vname,nname,straße,strnr,plz,ort,land,tel,email,datum,anrede) VALUES($temp)";
$eintrag = "INSERT INTO tadresse (vname,nname,straße,strnr,plz,ort,land,tel,email,datum,anrede) VALUES ('$vname','$nname','$straße','$strnr','$plz','$ort','$land','$tel','$email','$datum','$anrede')";
$eintragen = mysql_query($eintrag);
if($eintragen == true)
{
echo 'RICHTIG';
}
else
{
echo 'FEHLER';
}?>
the Result:
Notice: Array to string conversion in C:\xampp\htdocs\aufgabe\text.php on line 23
FEHLER
As the error suggest you are passing an array, but there is needed of a string. Your $temp is an array because it's the same as $_POST. So if you are sure that you want to pass there the $temp you have to change like this:
$sql = "INSERT INTO tadresse (vname,nname,straße,strnr,plz,ort,land,tel,email,datum,anrede) VALUES('" . implode("','", $temp) . "')";
But I see that you also have all the variables also so you can pass one by one here in VALUES like this:
$sql = "INSERT INTO tadresse (vname,nname,straße,strnr,plz,ort,land,tel,email,datum,anrede) VALUES('$vname', '$nname', '$straße', ....)";
And my suggestion is to use only English characters so to change $straße to something else
The first example will add data to mysql database without any issue. The second block of code - where I try to use variables wont. Can someone please explain where I am going wrong?
<?php
$query = "INSERT INTO subjects (menu_name,position,visible) VALUES ('Edit me',4,1)";
$result = mysqli_query($connection, $query);
Problem CODE:
<?php
$menu_name = "TEST";
$position = 5;
$visible = 1;
$query = "INSERT INTO subjects (menu_name,position,visible)
VALUES ('{menu_name}',{position}, {visible})";
$result = mysqli_query($connection, $query);
*Answer updated with MySQLi prepare statement, thanks #h2ooooooo
<?php
//Open a new connection to the MySQL server
$db = new mysqli('host','username','password','database_name');
//Output connection errors
if ($db->connect_error) {
die('Error : ('. $db->connect_errno .') '. $db->connect_error);
}
$sql = "INSERT INTO subjects (menu_name, position, visible) VALUES (?, ?, ?)";
if (!$stmt = $db->prepare($sql)) {
echo 'Database prepare error';
exit;
}
$stmt->bind_param('sss', $menu_name, $position, $visible);
if (!$stmt->execute()) {
echo 'Database execute error';
exit;
}
$stmt->close();
I'd say for you to take a look in the many tutorials thorugh net, like these:
http://markonphp.com/simple-insert-mysqli/ and
http://www.sanwebe.com/2013/03/basic-php-mysqli-usage
$query = "INSERT INTO subjects (menu_name,position,visible) VALUES
('".$menu_name."','".$position."', '".$visible."')";
try this
my mysql table accepts NULL values on many fields, I'm updating records and my desktop app is creating a http string as follows and sending to a php script.
www.webpage/script.php?firstval=48.345345&secondval=234&thirdval=&fourthval=simon
on the db thirdval is already NULL
but the parameters in the http string may or may not hold values
do I need to :
A)pass the parameter in the http string as
b)pass the parameter in the httpstring as
c)cater for the null value in the php script(
d)not include the parameter in the http string at all
or something else
my phpscript is like so :
?php
DEFINE ('DBUSER', 'generic01');
DEFINE ('DBPW', 'genpass');
DEFINE ('DBHOST', 'mysql4.xxxxxxxxx.com');
DEFINE ('DBNAME', '_Places');
$dbc = mysqli_connect(DBHOST,DBUSER,DBPW);
if (!$dbc) {
die("Database connection failed: " . mysqli_error($dbc));
exit();
}
$dbs = mysqli_select_db($dbc, DBNAME);
if (!$dbs) {
die(" Database selection bit failed: " . mysqli_error($dbc));
exit();
}
$lat = mysqli_real_escape_string($dbc, $_GET['lat']);
$lng = mysqli_real_escape_string($dbc,$_GET['lng']);
$prox = mysqli_real_escape_string($dbc,$_GET['prox']);
$description = mysqli_real_escape_string($dbc,$_GET['description']);
$id = mysqli_real_escape_string($dbc,$_GET['id']);
$direction = mysqli_real_escape_string($dbc,$_GET['direction']);
$avoiddays = mysqli_real_escape_string($dbc,$_GET['avoiddays']);
$validfrom = mysqli_real_escape_string($dbc,$_GET['validfrom']);
$validto = mysqli_real_escape_string($dbc,$_GET['validto']);
$gefid = mysqli_real_escape_string($dbc,$_GET['gefid']);
$expiry = mysqli_real_escape_string($dbc,$_GET['expiry']);
$query = "UPDATE places SET rt_lat = '$lat',rt_lng= '$lng',rt_prox = '$prox', rt_description = '$description', rt_direction = '$direction',rt_avoiddays = '$avoiddays',rt_validto = '$validto',rt_validfrom = '$validfrom',rt_gefid = '$gefid',rt_expiry='$expiry' WHERE rt_id = '$id'";
$result = mysqli_query($dbc, $query) or trigger_error("Query MySQL Error: " . mysqli_error($dbc));
mysqli_close($dbc);
?>
All help appreciated,
You do not need to include it in the http request, but you have to catch that, otherwise you get an E_NOTICE error.
For all fields that can be null:
if (isset($_GET['gefid'])) {
$gefid = mysqli_real_escape_string($dbc,$_GET['gefid']);
} else {
$gefid = null;
}
PHP has no knowledge of SQL nulls. If you want a blank/not-set $_GET value to become a null in the DB, then you have to take special steps:
if(isset($_GET['lat']) || ($_GET['lat'] == '')) {
$lat = 'NULL'; // a plain PHP string with the word "null" in it
} else {
$lat = "'" . mysqli_real_escape_string($dbc, $_GET['lat']) . "'"; // note the extra quotes
}
$sql = "INSERT ... VALUES ($lat, ....)"
If you do it any other way, e.g (just as an example, yes it's sql-injection vulnerable):
$sql = "INSERT ... VALUES ('$_GET[lat]', ...)";
Then for an empty $_GET['lat'] your query would actually be
INSERT ... VALUES ('', ...)
and you'd be inserting an empty string, NOT an sql null.
mysql_connect('localhost', 'root', '')
or die(mysql_error());
mysql_select_db('shuttle_service_system')
or die(mysql_error());
$insert="INSERT INTO inactive (ID_No, User_Password, First_Name, Last_Name, Email, Contact_Number)
VALUES('". $ID_No ."','". $UserPassword ."','". $FirstName ."','". $LastName ."','". $Email ."','". $ContactNumber ."')";
$result=mysql_query($insert);
$sql="DELETE FROM users WHERE ID_No = '$ID_No'";
$result2=mysql_query($sql);
if($result && $result2){
echo"Successful!";
} else {
echo "  Error";
}
Hi guys I have been stuck in delete function of MySQL, I have tried searching the net but when I ran my code it always goes to the else part which means there is an error, the insert is already okay but the delete is not.
PHP variables are allowed in double quotes. Hence try this,
$sql="DELETE FROM users WHERE ID_No = $ID_No";
Your first query was not properly escaped. Rewrite like
$insert="INSERT INTO inactive (`ID_No`, `User_Password`, `First_Name`, `Last_Name`, `Email`, `Contact_Number`)
VALUES('$ID_No','$UserPassword','$FirstName','$LastName','$Email','$ContactNumber')";
This (mysql_*) extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. Switching to PreparedStatements is even more better to ward off SQL Injection attacks !
First, use PDO.
Make your connection Database like this:
function connectToDB(){
$host='localhost';
try {
$user = 'username';
$pass = 'password';
$bdd = 'databaseName';
$dns = 'mysql:host='.$host.';dbname='.$bdd.'';
$options = array(
PDO::ATTR_PERSISTENT => true,
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8",
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
return $connexion = new PDO($dns, $user, $pass, $options);
}catch ( Exception $e ) {
echo "Fail to connect: ", $e->getMessage();
die();
}
}
To delete something, here is an example:
function deleteUserWithId($ID_No){
$connexion = connectToDB();
try{
$connexion->exec('DELETE FROM users WHERE ID_No = '.$ID_No);
}catch(Exception $e){
echo "Error: ".$e->getMessage();
}
}
To insert something:
function addInactiveUser($UserPassword,$FirstName ,$LastName ,$Email,$ContactNumber){
$connexion = connectToDB();
$insert = $connexion->prepare('INSERT INTO inactive VALUES(:ID_No,
:User_Password,
:First_Name,
:Last_Name,
:Email,
:Contact_Number
)');
try {
// executing the request
$success = $insert->execute(array(
'ID_No'=>'',
'User_Password'=>$UserPassword,
'First_Name'=>$FirstName ,
'Last_Name'=>$LastName ,
'Email'=>$Email,
'Contact_Number'=>$ContactNumber
));
if($success)
// OK
else
// KO
}
catch (Exception $e){
echo "Error: ".$e->getMessage();
}
}
To make a select:
// If you want to display X user per pages for example
function getAllInactiveUsers($page, $numberInactiveUserPerPage){
$connexion = connectToDB();
$firstInactiveUser = ($page - 1) * $numberInactiveUserPerPage;
$selectAllInactiveUsers = $connexion->prepare('SELECT * FROM inactive ORDER BY ID_No DESC LIMIT '.$firstInactiveUser.','.$numberInactiveUserPerPage);
return $selectAllInactiveUsers ;
}
To get the results of this methods, just do something like this:
$inactiveUsers= getAllInactiveUsers(1,15); // for page 1, display 15 users
$inactiveUsers->execute();
while($row = $inactiveUsers->fetch(PDO::FETCH_OBJ)){
$id = $row->ID_No;
$first_name = $row->First_Name;
// etc...
}
Hope that's help :)
I am not sure if this helps you, but as an alternative you could delete the last entry in the table:
$delQ = mysql_query("SELECT * FROM ph ORDER BY id DESC LIMIT 1" );
while(( $ar = mysql_fetch_array($delQ)) !== false){
mysql_query("DELETE FROM ph WHERE id= $ar[id]");
}
So I am having a difficult time getting a variable using a mysql search command and then using it in the same script in an insert command. What am I doing wrong?
<?php
$usto= $_GET["usto"];
$itena= "item";
$sql = 'SELECT sname FROM login';
$hostname_Database = "blocked";
$database_Database = "blocked";
$username_Database = "blocked";
$password_Database = "blocked";
$mysqli = new mysqli($hostname_Database, $username_Database, $password_Database, $database_Database);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$result = $mysqli->query($sql);
if ($result) {
$row = $result->fetch_assoc();
$sql = "INSERT INTO pon(mis, take)
VALUES({$row['snake']}, '" . $usto . "')"; //Here, I am trying to use the result from the previous select statement for the variable
$result = $mysqli->query($sql);
if ($result) {
...etc.
}
}
?>
You are vulnerable to SQL injection attacks. Read up about those and fix your code FIRST.
After that, realize that ->query() calls return a result HANDLE, not the actual field(s) you'd requested in your query. You have to FETCH a row of data first:
$result = $mysqli->query($sql);
$row = $result->fetch_assoc();
$sql = ".... VALUES ({$row['name_of_field']} ...)";
Note that this is STILL vulnerable to SQL injection.. it's purely to illustrate the query/fetch/insert process.