PHP mysqli INSERT does nothing - php

I looked at a dozen questions and nothing helps. Some give contradictory advice.
I have a simple INSERT INTO query with PHP mysqli. The query and the connection are both ok, and the query actually executes on an older version of xampp. But when I switched to a newer one - nothing! No errors, but, no new data, either.
<?php
$connection = mysqli_connect("localhost", "standard_user", "standard", "liquidity");
if (!$connection) {
die("Error: ".mysqli_connect_errno());
}
$table = "clan";
$username = "someusername";
$ime = "My name";
$query = "INSERT INTO ";
$query.=$table;
$query.=" (username, ime) ";
$query.="VALUES ('".$username."','".$ime."');";
//$query = "INSERT INTO clan (username, ime) VALUES ('someusername', 'My name')";
mysqli_query($connection, $query);
if ($query) {
echo("Success: ".$ime);
} else {
echo("There has been an error. Try again.");
}
mysqli_close($connection);
?>
This is the query it echoed when I tried it: INSERT INTO clan (username, ime) VALUES ('someusername','My name');
Since every time I reload it prints "Success: My name", I guess it somehow executes. But, no data is saved. I can't figure it out. Any help?
[SOLUTION] The clan table had a foreign key (username) to another table which had no entries, so there was nothing wrong with the query, but a silly overlook actually. Thanks to Deivison Francisco's answer, it was easy to determine the cause of the problem by simply reading an error.

Please use the return value of mysqli_query() to determine the result.
Also think about using prepared statements to mitigate SQL Injections.
$result = mysqli_query($connection, $query);
if ($result) {
echo("Success: ".$ime);
} else {
echo("There has been an error. Try again. Error message: ".mysqli_error($connection));
}

Alter for:
$query = "INSERT INTO clan (username, ime) VALUES ('someusername', 'My name')";
$return = mysqli_query($connection, $query);
if ($return) {
echo("Success: ".$ime);
} else {
echo("There has been an error. Try again.");
}
mysqli_close($connection);

Related

Data which is succesfully added in database, doesnt show in database

im adding data in databese with php and received "succesful" but when i look into the database the data which is i have just added doesnt show. Here my codes
<?php
require ('db.php');
#$name = $_POST['name'];
#$surname = $_POST['surname'];
#$number = $_POST['number'];
#$mail = $_POST['mail'];
#$note = $_POST['note'];
$sql = "INSERT INTO customersinfo (name,surname,number,email,notes) VALUES ($name,$surname,$number,$mail,$note)";
$con->query($sql);
if ($sql)
{
echo "Succesful";
}
else
{
echo "error";
}
?>
this is also my db.php codes ;
<?php
$con = mysqli_connect("localhost","root","","customers");
if (mysqli_connect_errno()) {
printf(" Connection error :( %s\n", mysqli_connect_error());
exit();
}
?>
i also have one more question. When i try to add data in databese with mysqli_query() function, it doesnt work. for example;
mysqli_query($con, "INSERT INTO customersinfo (name,surname,number,email,notes) VALUES($name,$surname,$number,$email,$note)");
because of this , i had to use this code,its working now but i have no idea why mysqli_query() function is doesnt work
$sql = "INSERT INTO customersinfo (name,surname,number,email,notes) VALUES ($name,$surname,$number,$mail,$note)";
$con->query($sql);
if you help me it would be great, thank you.
Put single quote(') in values like this
$sql = "INSERT INTO customersinfo (name,surname,number,email,notes) VALUES ('$name','$surname','$number','$mail','$note')";
You are checking just $sql variable which doesn't provide sql resul, it's just a query.
Try
$result = $con->query($sql);
if($result)
{
echo "Succesful";
}else{
echo "error";
}
More proper way:
$sql = "INSERT INTO `customersinfo`
(`name`,`surname`,`number`,`email`,`notes`) VALUES
('{$name}','{$surname}','{$number}','{$mail}','{$note}')";
$result=$con->query($sql);
if (!$result) {
// Query has failed
}
You checked $sql in if condition which is not right because $sql is always true so that u get the result successful but actually value is not getting inserted in database.
take the result in some variable and used that in if condition.
after that you will get what actual error in your code.

Attempting to insert new row into database using PDO

Ok, so I've been trying to do this for days, and I've been reading all sorts of tutorials, but I seem to be missing something, because I still can't get it. I'm working on learning about web forms and inserting the form input into the respective database. I'm able to take the info from the form and echo it on the result page, so I know that all works. but I can't seem to get the form input to go into my database. I know the connection works, so there must be something wrong with my syntax.
PHP
//DB Configs
$username = null;
$password = null;
try {
$db = new PDO("mysql:host=localhost;dbname=Testing3", $username, $password);
//Set the PDO error mode to exception (what does this mean?)
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//Prepare SQL and bind parameters
$sql = $db->prepare("INSERT INTO `NFK_SPECIES` (`Name`)
VALUES (:name)");
//Insert a Row
$species = $_POST['Species'];
$sql->execute(array(':name'=>$species));
}
catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
$result = $db->query('SELECT * from `NFK_Species` ORDER BY `Id` DESC');
//Query
/*
$input = $db->query("INSERT INTO `NFK_Species` (`Id`, `Name`) VALUES (Null, `$species`)");
$result = $db->query('SELECT * from `NFK_Species` ORDER BY `Id` DESC');*/
//Kill Connection
$db = Null;
}
HTML/PHP (web page)
<h1>Inserting a New Species into Database:</h1>
<h3>Results</h3>
<?php
if ($sql->execute()){
echo "Data input was successful";
while ($rows = $result->fetch()){
echo $rows['Name']; echo ", ";
}
} else {
echo "Data input failed."; echo mysql_error();
}
?>
This is only my current attempt at doing this. I prefer the attempt I had before, with the bindParam and simple execute(), so if I could get that to work instead, I'd appreciate it. The following example also has the Id column for this table. This is an auto-increment column, which I read doesn't need to be included, so I excluded it from my recent attempt. Is that correct?
Past PHP
//Prepare SQL and bind parameters
$sql = $db->prepare("INSERT INTO `NFK_SPECIES` (`Id`, `Name`)
VALUES (Null, :name)");
$sql->bindParam(':name', $species);
//Insert a Row
$species = $_POST['Species'];
$sql->execute();
I've been reading a bunch of tutorials (or trying to), including attempting to decipher the php.net tutorials, but they all seem to be written for people who already have a good handle on this and experience with what's going on, and I'm very new to all of this.
Alright, I was able to figure out my problem, and then successfully insert a row using my code.
Debugging:
So the code posted above was breaking my code, meaning my page wouldn't load. I figured that meant that there was a syntax error somewhere, but I couldn't find it, and no one else had located it yet. Also, that meant that my Error Alerts weren't working to let me know what the problem was. If you look at my original PHP sample, you'll see down at the very bottom there is a single "}" just hanging out and serving no purpose, but more importantly, it's breaking the code (stupid, hyper-sensitive php code). So I got rid of that, and then my Error messages started working. It said I couldn't connect to my database. So I look over my database login syntax, which looked fine, and then you'll notice in my 1st php sample that somehow I'd managed to set my $username and $password to NULL. Clearly that isn't correct. So I fixed that, and next time I refreshed my page, I'd successfully entered a row in my database! (yay)
Note:
In my original php sample, I'd included the Id Column, which is auto-incremented, for the row insertion, with a value of NULL. This worked, and it inserted the row. Then I experimented with leaving it out altogether, and it still worked. So the updated working code below doesn't include the Species Id.
Working code:
<body>
<h1>Inserting a New Species into Database:</h1>
<h3>Results</h3>
<?php
//DB Configs
$username = root;
$password = root;
try {
//Connect to Database
$db = new PDO("mysql:host=localhost;dbname=Testing3", $username, $password);
//Enable PDO Error Alerts
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//Prepare SQL statement and bind parameters
$sql = $db->prepare("INSERT INTO `NFK_SPECIES` (`Name`) VALUES (:name)");
$sql->bindParam(':name', $species);
//Insert a Row
$species = $_POST['Species'];
$sql->execute();
// Echo Successful attempt
echo "<p class='works'><b>" . $species . "</b> successfully added to database.</p></br></br>";
}
catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
// Gather updated table data
$result = $db->query('SELECT * from `NFK_Species` ORDER BY `Id` DESC');
//Kill Connection
$db = Null;
while ($rows=$result->fetch()){
echo $rows['Id']; echo " - "; echo $rows['Name']; echo "</br>";
}
?>
<body>

MySQL Query not submitting via PHP but submitting as a raw query

I have a page which allows a user to create an entry and insert it into the database via submitting a form through PHP.
I have had the page working in the past, and it worked perfectly, but now for some reason it has stopped working. Basically, I submit the form, and there are no error messages, but my entry does not appear in the database.
Here is my PHP:
<?php // add_entry.php
session_start();
include_once 'creds.php';
$con=mysqli_connect("$db_hostname","$db_username","$db_password","$db_database");
if (isset($_POST['group'])){
$lab = $_SESSION['labname'];
$author = $_SESSION['username'];
$name = $_POST['entryName'];
$group = $_POST['group'];
$protocol = $_POST['protocol'];
$permission = $_POST['permission'];
$array = $_POST['protocolValues'];
// $filearray = $_POST['fileArray']; Don't forget to add '$filearray', to your query after ARRAY.
$project = $_POST['project'];
$query = "INSERT INTO data (protocol, name, lab, author, uniquearray, usergroup, project, permissionflag) VALUES ('$protocol', '$name', '$lab', '$author', '$array', '$group', 'project', '$permission')";
mysqli_query($con, $query);
mysqli_close($con);
}else{
echo "FAILURE. GROUP WAS NOT SET.";
}
?>
Any ideas as to why this may be happening?
Thanks in advance!
In addition to the accepted answer which I applaud, this 'project' in your VALUES()
is missing the $ sign - therefore, it's not being passed as a variable but as a simple string.
so change it to '$project'
otherwise, the value entered in DB will be project and not the intended POST value from your form.
You're also not checking for errors, which is crucial during the development stages of a project.
Add error reporting to the top of your file(s)
error_reporting(E_ALL);
ini_set('display_errors', 1);
which will signal any errors found in your code.
try to add
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
after $con=mysqli_connect(...);
and replace this
mysqli_query($con, $query);
with this
if (!mysqli_query($con, $query)) {
printf("Errormessage: %s\n", mysqli_error($con));
}
you will be able to debug the problem (if related to the query)

Cannot get information generated from google maps into MySQL

I am trying to insert values for longitude, latitude and descriptions of locations generated from google maps (the ID value is to be generated within PhpMyAdmin. When I run the following code I always get the "error" message. If I "echo $sql;" before //insert values into database then I get the intended output so I guess it must be a problem with transferring to the database.
I'm using phpMyAdmin from within MAMP so am not sure if that is causing any issues of whether I'm missing something obvious in the code? I'm fairly new to PHP so may have missed something obvious! Any help would be much appreciated.
<?php
$con=mysqli_connect("localhost", "root", "root", "googlemaps") or die("could not connent to db");
error_reporting(0);
for($i=0;$i<count($_POST['value']);$i=$i+3)
{
$sql .= "(NULL, '".$_POST['value'][$i]."', '".$_POST['value'][$i+1]."', '".$_POST['value'][$i+2]."'),";
}
//remove last comma
$sql = substr($sql,0,-1);
//insert values into database
$query = "INSERT INTO 'googlemaps'.'values' ('id', 'lat', 'lng', 'des') VALUES " .$sql;
$status = mysqli_query($con, $query);
if($status)
echo "inserted";
else
echo "error";
?>

mysql insert PHP statement keeps throwing error

Does anybody know why the following PHP code keeps throwing errors: I have been unable to log any proper error other than the if statement $result not going through and giving me the Echo 'Error' statement. Is there something wrong with my insertion?
$new_tbl_name = 'Password_Reset';
$sql = "INSERT INTO $new_tbl_name (Email, Key) VALUES ('$email','$resetHash')";
$result = mysql_query($sql);
if ($result) {
}
else {
echo 'Error';
}
key is a reserved word, you'll have to escape it:
INSERT INTO $new_tbl_name (Email, `Key`) VALUES
^ ^
As a general suggestion, simply saying "error" is utterly useless for debugging purposes. Have mysql TELL you what's wrong:
if (!$result) {
die(mysql_error());
}
so you have a clue as to what's wrong, instead of just poking around in the dark.

Categories