thats my second day working with PHP and MySQL.
I've got a problem. Im trying to create a new data in my db, but the only thing im getting is a 0 in the first field.(nummer)
<?php
$con=mysqli_connect("127.0.0.1","root","","aufgabe");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$nummer = mysqli_real_escape_string($con, $_POST['nummer']);
$vorname = mysqli_real_escape_string($con, $_POST['vorname']);
$sql="INSERT INTO kontakte (nummer,vorname)
VALUES ('$nummer','$vorname')";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
?>
Would you help me with that pls? I have now idea why nummer results in 0 and vorname in nothing.
I know that there is less security in my script, but it's only for school purposes.
Check if isset($_POST['nummer']) && isset($_POST['vorname']) == true then var_dump both there variables to see what content to they have.
Related
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
I'm fairly new to stack overflow. i am creating a site were you type text in to 2 text boxes and it sends it to a database. i need it then to tell me what the id of that was save it as a session and then upload it to another database. sounds confusing. but I'm stuck of one part. its viewing the result thats from just that user. i have tried just showing the the last id of the last uploaded but it can be very unreliable if multiple people are trying to upload data and know there exact session. I'm also having trouble linking the session with the id. below is the code for the forum saving to the database. I'm pretty confident with sending the id of that users inputed data to another database. I'm just stuck on finding that users inputed texts id and creating a session holding the id number
<?php
header("Location:myscorenum.php");
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "score";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
session_start();
if (isset($_SESSION['username'])){
$username = $_SESSION['username'];
echo "working";
}else{
//3.2 When the user visits the page first time, simple login form will be displayed.
}
$value = $_POST['name'];
$value1 = $_POST['description'];
$sql = "INSERT INTO all_scores (name, description) VALUES ('$value','$value1')";
if ($conn->query($sql) === TRUE) {
echo "<a href=https://twitter.com/angela_bradley>My Twitter</a>";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
ill have the processing to inset to another database in another file. I'm confident with uploading a specific session.
any questions don't hesitate to message me. thanks for your kind help.
You can use this:
mysqli::$insert_id -- mysqli_insert_id — Returns the auto generated id used in the last query
Like: echo $conn->insert_id;
Since you call it on $conn which is a mysqli instance that already has a connection, it will return your last inserted id, irregardless of other activities on the db (other queries do not affect the correctness of the output)
I edited my answer. This is the final part of your code and I've just added one line of code to it. Look if this is what you're looking for.
If this isn't working than make sure your database id field is AI.
if ($conn->query($sql) === TRUE) {
$id=$conn->insert_id; //this is where you get the last inserted id.
echo "<a href=https://twitter.com/angela_bradley>My Twitter</a>";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
To use a session and set the ->insert_id to a session variable and use it in any other page, you can do this:
if ($conn->query($sql) === TRUE) {
session_start();
$_SESSION['id']=$conn->insert_id;
echo "<a href=https://twitter.com/angela_bradley>My Twitter</a>";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
and now in any other page do this to retrieve the session variable:
session_start();
$id=$_SESSION['id'];
here you go and you get the id.
Are you still confused?
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.
I want to store one's friends of facebook into a table. The result of below code shows only a single record is inserted. It wasn't the problem of my loop because I echo the name, it all appeared.
foreach($user_friends['data'] as $friend){
//echo $friend['name'] . "</br>";
$userImg = "https://graph.facebook.com/".$friend['id']."/picture?width=200&height=200";
$friendsName = $friend['name'];
$stmt3 = $db->prepare("INSERT INTO allfriend(`uId`,`name`,`img`,`friendOf`) VALUES (?,?,?,?)");
$stmt3->bind_param('ssss', $user_fbid, $friendsName, $userImg, $user_fbid);
$stmt3->execute();
}
You're misusing the prepare / bind feature slightly. You only need to prepare once, but you do need to reset the statement after each use.
Also, you should check for failure of your statements. If you do that you may find out why things might work differently from what you expect.
Is it possible your column friend.uID is in fact a primary key? The code you've shown tries to insert the same value into multiple rows. That could be your problem.
Try this:
$stmt3 = $db->prepare
("INSERT INTO allfriend(`uId`,`name`,`img`,`friendOf`) VALUES (?,?,?,?)")
|| die "prepare failed: ". $db->error;
foreach($user_friends['data'] as $friend) {
//echo $friend['name'] . "</br>";
$userImg = "https://graph.facebook.com/".$friend['id']."/picture?width=200&height=200";
$friendsName = $friend['name'];
$stmt3->bind_param('ssss', $user_fbid, $friendsName, $userImg, $user_fbid)
|| die "bind_param failed " . $db->error;
$stmt3->execute()
|| die "execute failed " . $db->error;
$stmt3->reset()
|| die "reset failed " . $db->error;
}
I have two very long list:
$countryCode
And
$countryName
To insert these list i have created the following loop:
$i = 0;
$con=mysqli_connect("localhost","root","root","system_bloglic_com_test");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
foreach($countryCode as $cCode){
mysqli_query($con,"INSERT INTO Contries (contries_id, contries_name, contries_code)
VALUES(NULL,$cCode,$countryName[$i])");
$i++;
}
When i run this i get no erros but no rows have been inserted into database how come?
did you check mysqli_error(); it will help you to find exactly the error.
It returns FALSE if an error occurred. In that case mysqli_error() gives you more information about the error.
$result = mysqli_query($con,"INSERT INTO Contries (contries_id, contries_name, contries_code)
VALUES(NULL,$cCode,$countryName[$i])");
if ( false===$result ) {
printf("error: %s\n", mysqli_error($con));
}
else {
echo 'done.';
}
Your string values should always be enclosed within quotes
mysqli_query($con,"INSERT INTO Contries (contries_id, contries_name, contries_code)
VALUES(NULL,'{$cCode}','{$countryName[$i]}')");
and also you should use error handling as instructed by others using die() method
You should change
mysqli_query(...);
into
mysqli_query(...) or die("error in query: " . mysqli_error($con));
To echo out any errors. Otherwise errors are silently ignored.
You need to check for errors in your code.
if(!mysqli_query($con,"INSERT INTO Contries (contries_id, contries_name, contries_code)
VALUES(NULL,'$cCode','$countryName[$i]')")){
echo mysqli_error($con);
}