mysqli_insert_id() not working? - php

I'm getting quite angry over this, I don't know how can this simple situation be so complicated and not work.
Basically:
$lastInsertId = mysqli_insert_id($query);
echo $lastInsertId;
returns NULL
my $query runs fine, inserts perfectly. Anyone knows why I'm not getting the last insert id?

What is $query? You have to pass the mysqli link as parameter ($link = mysqli_connect(...)). Maybe your $query is the result of mysqli_query or something else.
mixed mysqli::mysqli_insert_id ( mysqli $link )
Manual: http://php.net/mysqli_insert_id

//you follow the folow the bellow code
<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_query($con,"INSERT INTO Persons (FirstName,LastName,Age)
VALUES ('Glenn','Quagmire',33)");
// Print auto-generated id//
//NOTE: $con link should be in ()
echo "New record has id: " . mysqli_insert_id($con);
mysqli_close($con);
?>

Related

Tutorial issues using INSERT INTO without adding a row to database for certain entries

I am following the last part of the following video tutorial "How to create a database website with PHP and mySQL 07 - Add in input form" :
https://www.youtube.com/watch?v=MGIG00d1Xzc&list=PLhPyEFL5u-i0zEaDF0IPLYvm8zOKnz70r&index=7
At the end here is my code, for the inserting portion to the database for the new_jokes.php script (everything up to this point of the series I have gotten to work fine so far)
Basically I am getting the seemingly classic "INSERT INTO" not working although all my syntax looks correct. Am I missing something obvious here? I get no errors, just the row isn't added.
<?php
include "db_connect.php";
$new_joke_question = $_GET["newjoke"];
$new_joke_answer = $_GET["newanswer"];
// Search the database for the word chicken
echo "<h2>Trying to add a new joke and answer: $new_joke_question
$new_joke_answer </h2>";
$sql = "INSERT INTO Jokes_table (JokeID, Joke_question, Joke_answer) VALUES
(NULL, '$new_joke_question', '$new_joke_answer' )";
$result = $mysqli->query($sql);
include "search_all_jokes.php";
?>
Return to the main page
Here is the db_connect.php code as requested:
<?php
// four variables to connect the database
$host = "localhost";
$username = "root";
$user_pass = "usbw";
$database = "test";
// create a database connection instance
$mysqli = new mysqli($host, $username, $user_pass, $database);
?>
Here is search_all_jokes.php (which has minor error checking):
// if there are any values in the table, select them one at a time
if ($mysqli->connect_errno) {
echo "Connection to MySQL failed: (" . $mysqli->connect_errno . ") " .
$mysqli->connect_error;
}
echo $mysqli->host_info . "<br>";
$sql = "SELECT JokeID, Joke_question, Joke_answer FROM Jokes_table";
$result = $mysqli->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "JokeID: " . $row["JokeID"]. " - Joke_question: " .
$row["Joke_question"]. " " . $row["Joke_answer"]. "<br>";
}
} else {
echo "0 results";
}
?>
Also here is the table structure screenshot viewed in myPHPAdmin:
I added error capturing into new_jokes.php inspired by this Stack Overflow post:
INSERT INTO SYNTAX ERROR
And get the following error:
Error: 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 't jump.' )' at line 1localhost via TCP/IP
Thank you everyone for helping out with this! Syntax can really throw a wrench in everything. I also will read up on prepared statements since that also could have prevented the issue. The ultimate help to this I found the solution to by adding the function referenced here for MySQLi real_escape_string to clean the single quote I had within the answer I was submitting to my joke table:
(Can a kangaroo jump higher than the empire state building? Of course, the empire state building can't jump.)
As shown in the documentation #miken32 linked as a comment here it is says: "But if $val1 or $val2 contains single quotes, that will make your SQL be wrong. So you need to escape it before it is used in sql; that is what mysql_real_escape_string is for. (Although a prepared statement is better.)"
But now the code for this part 7 of the tutorial on you tube I found works and adds it into a row on the database table, then displaying the full new table on the next webpage. I spent a good while shooting in the dark on while the answer ended up being fairly simple. Again special thanks to #miken32 for pointing me the right direction.
Here is my completed code that ended up working to at least achieve the goal of the tutorial:
<?php
include "db_connect.php";
$new_joke_question = $_GET["newjoke"];
$new_joke_answer = $_GET["newanswer"];
$new_joke_question = $mysqli->real_escape_string($new_joke_question);
$new_joke_answer = $mysqli->real_escape_string($new_joke_answer);
// Search the database for the word chicken
echo "<h2>Trying to add a new joke and answer: $new_joke_question $new_joke_answer
</h2>";
if ($mysqli->connect_errno) {
echo "Connection to MySQL failed: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
echo $mysqli->host_info . "<br>";
$sql = "INSERT INTO Jokes_table (JokeID, Joke_question, Joke_answer) VALUES (' ',
'$new_joke_question', '$new_joke_answer' )";
$result = $mysqli->query($sql);
if ($mysqli->query($sql) === TRUE) {
echo 'users entry saved successfully';
}
else {
echo 'Error: '. $mysqli->error .'<br>';
}
include "search_all_jokes.php";
?>
Return to the main page

PHP mysqli_query won't execute

I'm trying to write my first basic PHP RESTful API - I managed to get it working on my local machine using MAMP. But when I uploaded to hosting server, it doesn't want to work.
Code below - I've added some ECHO's in there to make sure things are working along the way. It seems like we're all good up until the $result=mysqli_query.
<?php
//header('Content-type:application/json');
// Connect to db
$con = mysqli_connect("HOSTNAME","USER","PASSWORD","DATABASE");
echo "Database: ";
// Check connection
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
echo "Connected successfully";
echo "<br><br>";
// Get value from url
$bid = $_GET['bid'];
echo "BID: ";
echo $bid;
echo "<br><br>";
// Define Query
$sql = "SELECT id, bandname, members, bio, songlist FROM bands WHERE id='$bid'";
echo "SQL Query: ";
echo $sql;
echo "<br><br>";
// Run Query
$result = mysqli_query($con, $sql);
echo "Result: ";
print_r($result);
echo "<br><br>";
// Put Query result into array
$result_array = mysqli_fetch_array($result, MYSQLI_ASSOC);
echo "Result Array: ";
print_r($result_array);
echo "<br><br>";
// Encode array as JSON and output
echo "JSON: ";
echo json_encode($result_array);
?>
The url I'm entering is http://bandsly.com/api.php?bid=1 and this is the output I'm getting in the browser...
Database: Connected successfully
BID: 1
SQL Query: SELECT id, bandname, members, bio, songlist FROM bands WHERE id='1'
Result:
Result Array:
JSON: null
When I manually run the query SELECT id, bandname, members, bio, songlist FROM bands WHERE id='1' in the database (PHPmyadmin), it works fine and I get 1 row returned with the correct values.
The manual db query result:
(http://i.stack.imgur.com/d3ZPJ.png)
Any help would be most appreciated!!
*****EDIT*****
OK, i think i found the issue... My "successfully Connected" wasn't written correctly, and always came back looking good. It looks like after fixing that, i have db connection issues.
I'm going to go look up the db connection settings and try and fix that.
Thanks all for your help!
Your code seems to be ok on my localsystem http://www.awesomescreenshot.com/image/494275/c6c255cd6924d07196076b32489489de. There should be a connection problem . so you can do some try to check connection like
check the details in
// Connect to db
$con = mysqli_connect("HOSTNAME","USER","PASSWORD","DATABASE");
and then you can try to ping database
/* check connection */
if ($con->connect_errno) {
printf("Connect failed: %s\n", $con->connect_error);
exit();
}
/* check if server is alive */
if ($con->ping()) {
printf ("Our connection is ok!\n");
} else {
printf ("Error: %s\n", $con->error);
}
Your all code is correct, I have tested in my local just change your
HOSTNAME like "localhost", USER like "root", PASSWORD like "your password", DATABASE like "YOUR DATABASE NAME".
$con = mysqli_connect("HOSTNAME","USER","PASSWORD","DATABASE");
please, visit http://php.net/manual/en/function.mysqli-connect.php

mysql php displays results but not inserting into database

I stripped down query for only one insert
<?php
session_start();
include 'cstring.php';
$title="";
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else {
$title=$_POST['title'];
$query=mysqli_query($con,"insert into blogpages(blogpagetitle) values('".$title."')");
if($query){
$bloga="sucessfully added a new blog";
echo $bloga;
}
else {
echo mysqli_error($con); // if using mysqli do not use mysql in between
}
}
mysqli_close($con);
?>
is there something wong in this code that it doesnt insert into mysql
table structure
1.bpid int(50)--------------null-no default-none autoincrement
2.blogpagetitle------------varchar(255) utf16_general_ci
3.datemade-------------timestamp current time stamp
4.blogpagedescription---------text utf16_general_ci
5.blogbody----------------longtext utf16_general_ci
6.blogpageextended------------ text utf16_general_ci
TIP
Sanitize variables, Use mysqli_real_escape_string()
When you are not able to debug your code, echo every possible stuff and die the rest code.
For example here, echo if there is error in DB connection, echo the query to see if it is correct, echo the result of query execution, echo if there is some error!
You should be using echo mysqli_error($con) to get the error message rather than mysql_error().

So i'm trying to have it check to see if the steamid64 all ready exists before inserting but it just inserts any way?

So i'm trying to have it check to see if the steamid64 all ready exists before inserting but it just inserts any way?
i'm not good with PHP here.
<?php
$con=mysqli_connect("localhost","user","pass","Gmod");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$SteamID64 = mysqli_real_escape_string($con, $_POST['SteamID64']);
$enable = mysqli_real_escape_string($con, $_POST['enable']);
$sql="SELECT * FROM Loading (SteamID64, enable) WHERE SteamID64='$SteamID64'";
if(mysql_num_rows($sql)>=1) {
echo'<center>The music is already disabled!</center>';
}
else {
$sql="INSERT INTO Loading (SteamID64, enable)
VALUES ('$SteamID64', '$enable')";
}
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
echo "<center>The music will not play when you connect.</center>";
mysqli_close($con);
?>
i got this off some forums and w3schools.com
and edited it.
Ok so i did this but its still just inserting the data?
<?php
mysqli_report(MYSQLI_REPORT_STRICT);
$con=mysqli_connect("localhost","root","server","Gmod");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$SteamID64 = mysqli_real_escape_string($con, $_POST['SteamID64']);
$enable = mysqli_real_escape_string($con, $_POST['enable']);
mysqli_query($con,"SELECT * FROM Loading WHERE SteamID64='$SteamID64'");
if(mysqli_num_rows(mysqli_query)>=1) {
echo'<center>The music is already disabled!</center>';
}
else {
mysqli_query($con,"INSERT INTO Loading (SteamID64, enable)
VALUES ('$SteamID64', '$enable')");
}
echo "<center>The music will not play when you connect.</center>";
mysqli_close($con);
?>
Apart from the fact that you cannot mix mysql_* and mysqli_* functions like that (pick one, mysqli_* and stick to that), you have an error in your sql:
SELECT * FROM Loading (SteamID64, enable) WHERE SteamID64='$SteamID64'
^^^^^^^^^^^^^^^^^^^ this should not be here
You need to change that to:
SELECT * FROM Loading WHERE SteamID64='$SteamID64'
You can have mysqli throw exceptions so that it tells you exactly what went wrong when it goes wrong. Just add this to the top of your script:
mysqli_report(MYSQLI_REPORT_STRICT);
Another problem you have, is that the execution of your second query should be inside the else part of the previous condition.
And as #FabrícioMatté already mentioned, you actually need to execute your query using mysqli_query(), just setting the string does not do anything.

Return the id of the last MySQL insert in PHP

I'm trying to grab the id of the last inserted auto-increment row and cannot successfully grab it.
error_reporting(E_ALL);
ini_set('display_errors', 1);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$title = mysqli_real_escape_string($conxn,$_POST['blog_title']);
$entry = mysqli_real_escape_string($conxn,$_POST['blog_entry']);
$sourceName = mysqli_real_escape_string($conxn,$_POST['blog_source_name']);
$sourceLink = mysqli_real_escape_string($conxn,$_POST['blog_source_link']);
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO blog (blog_title, blog_entry, blog_source, blog_link)
VALUES ('$title','$entry','$sourceName','$sourceLink')";
$lastID = $mysqli->insert_id;
if (!mysqli_query($conxn,$sql)) {
die('Error: ' . mysqli_error($conxn));
}
When I echo $lastID a "0" is returned after every submit.
You need to place the $mysqli->insert_id() after the actual mysqli_query(). See below.
if (!mysqli_query($conxn,$sql)) {
die('Error: ' . mysqli_error($conxn));
}
$lastID = $mysqli->insert_id;
That said, there are other issues with your code. First & foremost, you are mixing up the Object oriented style of calling mysqli_* with the procedural style. For example the OOP method of $mysqli->real_escape_string equates to the procedural method of mysqli_real_escape_string.
So this:
$lastID = $mysqli->insert_id;
Should be this:
$lastID = mysqli_insert_id($conxn);
So without seeing the rest of your code, unclear how to handle. Know the difference & experiment. But here are my suggestions in good faith based on the code you have presented.
For example, your references to $_POST values do not have single quotes, so I added that. Also, since you are using double quotes—which handle string substitution—you can condense your INSERT variable setting by getting rid of the . concatenation.
$title = mysqli_real_escape_string($conxn, $_POST['blog_title']);
$entry = mysqli_real_escape_string($conxn, $_POST['blog_entry']);
$sourceName = mysqli_real_escape_string($conxn, $_POST['blog_source_name']);
$sourceLink = mysqli_real_escape_string($conxn, $_POST['blog_source_link']);
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO blog (blog_title, blog_entry, blog_source, blog_link)
VALUES ('$title','$entry','$sourceName','$sourceLink')";
if (!mysqli_query($conxn,$sql)) {
die('Error: ' . mysqli_error($conxn));
}
$lastID = mysqli_insert_id($conxn);
That done, this code chunklet can be cleaned up even more, and this is how I would handle it. I have made an array of the $_POST values you are grabbing so you don’t have to repeat code. Also added comments to make it clearer what is happening. And I have used the procedural format for all commands here. If OOP is what you want, then you need to change all of the commands to match OOP format.
// Set all of the `$_POST` values into an array.
$post_items = array('blog_title','blog_entry','blog_source_name', 'blog_source_link');
// Roll through those values with a `foreach` loop.
foreach ($post_items as $post_item) {
$$post_item = mysqli_real_escape_string($conxn, $_POST[$post_item]);
}
// MySQL connection error check.
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Set the SQL values.
$sql = "INSERT INTO blog (blog_title, blog_entry, blog_source, blog_link)
VALUES ('$blog_title','$blog_entry','$blog_source_name','$blog_source_link')";
// Run the query.
if (!$mysqli_query($conxn, $sql)) {
die('Error: ' . mysqli_error($conxn));
}
// Get the last insert ID via object oriented method.
// $lastID = $mysqli->insert_id;
// Get the last insert ID via procedural method.
$lastID = mysqli_insert_id($conxn);

Categories