insert into database not working - php

<?php
include("dbinit.php");
$text="helow";
$eadd = $_SESSION['account'];
$result = mysqli_query($link,"SELECT * FROM account where Eadd='". $eadd ."'");
while($row = mysqli_fetch_array($result))
{
$name = $row['Name'];
}
$ctext = $_POST['ctext'];
$sql = "INSERT INTO chat (By, Content, Reported) VALUES ('$name','$ctext','No')";
mysqli_query($link,$sql);
mysqli_close($link);
$text=$name . $ctext;
echo $text;
?>
Here is my code. In my other page, this works but .. when i change the values in "insert into" why i cant store it to database?
<?php
session_start();
$link = mysqli_connect("localhost", "xxx", "xxx", "xxx");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
mysqli_select_db($link, "xxx");
header('Content-type: text/html; charset=utf-8');
?>
here is my dbinit file

$sql = "INSERT INTO `chat` (`By`, `Content`, `Reported`) VALUES ('".$name."','".$ctext."','No')";
to protect from mysql injections read this.
also, what kind of values did you change to that doesn't work?

BY is reserved keyword you should use backticks around it
$sql = "INSERT INTO chat (`By`, Content, Repo.........

Wrap the PHP variables in your $sql with double quotes, don't forget the dots.
$sql = "INSERT INTO chat (By, Content, Reported) VALUES ('".$name."','".$ctext."','No')";

Related

MySQL Entry to Database Not Working

I'm going through a course on MySQL, and I'm learning how to make a user entry bit of code (email and password) where the info in the script will be put into the database on phpMyAdmin. I can't seem to get it to work? My code doesn't have any errors when I put it through an error checker. I'm also completely new to PHP and MySQL. I know it can find the database, because I can update existing data.
<?php
$link = mysqli_connect("host", "username", "password", "username");
if (mysqli_connect_error()) {
die ("There was an error connecting to the database");
}
$query = "INSERT INTO `users` (`email`, `password`) VALUES('email', 'password')";
mysqli_query($link, $query);
$query = "SELECT * FROM users";
if ($result = mysqli_query($link, $query)) {
$row = mysqli_fetch_array($result);
echo "Your email is ".$row[1]." and your password is ".$row[2];
}
?>
Created a refined version. Check it.
<?php
$link = mysqli_connect("host", "username", "password", "username");
if (mysqli_connect_error()) {
die ("There was an error connecting to the database");
}
$query = "INSERT INTO `users` (`email`, `password`) VALUES('email', 'password')";
$result = mysqli_query($link, $query);
if($result != false)
{
echo "The record has been successfully inserted.<br>";
}
else
{
echo "Error Occured in the INSERT query.<br>Error : ".mysqli_error($link);
}
$query = "SELECT * FROM users";
$result = mysqli_query($link, $query);
if($result != false)
{
echo mysqli_num_rows($result)." Records found.<br>";
while($rows = mysqli_fetch_array($result))
{
echo $rows["email"]."<br>";
}
}
else
{
echo "Error Occured in the SELECT query.<br>Error : ".mysqli_error($link);
}
mysqli_close($link);
?>
Update
It turns out I didn't set the auto_increment setting, therefore making the way I set up my database incorrect! He set up another database in the tutorials I was going through, and I found out that as he did it. Thank you everyone for the effort to help me solve my problem!
Why you don't try receiving them with php?
And simply make
$email= $POST['email']
$password= $POST['password']
And change the query to
$query = "INSERT INTO `users` (`email`, `password`) VALUES(" .$email. ", ". $password.")";

adding HTML form input to database

Kindly need assistance in my coding, I have a database named Books with table called OpenBooks I would like to add the html form which are user inputs into the table and echo confirmation.
<?php
$Title = $_POST['Title'];
$Author = $_POST['Author'];
$Series = $_POST['Series'];
$Price =$_POST['price'];
//database connection
$connection = mysqli_connect('localhost', 'root', '','books');
if(!$connection){
die("Database connection failed");
}
$query = "INSERT INTO OpenBooks(Title,Author,series,price)";
$query .= " VALUES ('$Title', '$Author', '$series', '$price')";
$result = mysqli_query($connection, $query);
}
?>
if (!$result) {
die('Invalid query: ' . mysql_error());
}
else {
echo 'yay, done';
}
And you need $Price instead of price and rest of variables starting from capital letter.

Cant connect php to mysql

New to php and am connecting form attributes to php to connect to a godaddy mysql. Every attempt ends in a blank screen with no error messages. Is there any syntax errors the jump out? My sublime text wont register php syntax, but thats another problem for another time. I may need to call up godaddy support? the password has been removed for privacy.
<?php
$servername = "localhost";
$dbusername = "jaysenhenderson";
$dbpassword = "xxxxx";
$dbname = "EOTDSurvey";
$con = new mysqli ($servername, $dbusername, $dbpassword, $dbname);
mysql_select_db('EOTDSurvey', $con)
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo("Connected successfully");
$_POST['BI1']
$_POST['BI2']
$_POST['BI3']
$_POST['BI4']
$_POST['BI5']
$_POST['BI6']
$_POST['BI7']
$_POST['BI8']
$_POST['BI9']
$_POST['BI10']
$_POST['BI11']
$_POST['BI12']
$_POST['BI13']
$_POST['BI14']
$_POST['BI15']
$sql = "INSERT INTO Survey1(BI1)"
$sql = "INSERT INTO Survey1(BI2)"
$sql = "INSERT INTO Survey1(BI3)"
$sql = "INSERT INTO Survey1(BI4)"
$sql = "INSERT INTO Survey1(BI5)"
$sql = "INSERT INTO Survey1(BI6)"
$sql = "INSERT INTO Survey1(BI7)"
$sql = "INSERT INTO Survey1(BI8)"
$sql = "INSERT INTO Survey1(BI9)"
$sql = "INSERT INTO Survey1(BI10)"
$sql = "INSERT INTO Survey1(BI11)"
$sql = "INSERT INTO Survey1(BI12)"
$sql = "INSERT INTO Survey1(BI13)"
$sql = "INSERT INTO Survey1(BI14)"
$sql = "INSERT INTO Survey1(BI15)"
if ($conn->query<$sql) === TRUE) {
echo "IT FUCKING WORKS.";
}
else{
echo "didnt workkkkkk";
}
$conn->close();
?>
please connect database like this...
$connection = mysqli_connect(DB_SERVER,DB_USER,DB_PASS);
if (!$connection) {
die("Database connection failed: " . mysqli_error());
}
// 2. Select a database to use
$db_select = mysqli_select_db($connection, DB_NAME);
if (!$db_select) {
die("Database selection failed: " . mysqli_error());
}
And Use mysqli_select_db instead of mysql_select_db
And insert semi-colon (;) after every line end according to php code standard.
There are a lot of issues with this code, as mentioned the mysqli_select_db issue. The $_POST['BIx'] will also cause errors because there is no semi-colon after each statement. You're missing a '(' on the line if ($conn->query<$sql) === TRUE) { not to mention that line will not work anyway because you're logically comparing a resource type (I think) to a string.
You're also never executing the insert statements. All around I seriously think you should practice PHP coding some more and read up on how to use mysqli properly: see here.
Regards
EDIT: You also have a closing PHP tag at the end of your script which is generally not a good idea as explained here
EDIT 2: Also using an IDE such as Netbeans is always a good idea as it can highlight syntax errors instead of asking SO to do it for you ;)
<?php
$servername = "localhost";
$dbusername = "jaysenhenderson";
$dbpassword = "xxxxx";
$dbname = "EOTDSurvey";
$con = new mysqli ($servername, $dbusername, $dbpassword, $dbname);
mysqli_select_db('EOTDSurvey', $con);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo("Connected successfully");
############# Function For Insert ##############
function insert($tableName='',$data=array())
{
$query = "INSERT INTO `$tableName` SET";
$subQuery = '';
foreach ($data as $columnName => $colValue) {
$subQuery .= " `$columnName`='$colValue',";
}
$subQuery = rtrim($subQuery,', ');
$query .= $subQuery;
pr($query);
mysqli_query($con,$query) or die(mysqli_error());
return mysqli_insert_id();
}//end insert
#########################################
if(isset($_POST['submit'])){
unset($_POST['submit']);
//print_r($_POST);
$result=insert('Survey1',$_POST);
if($result){
echo '<script>window.alert("Success!");</script>';
echo "<script>window.location.href = 'yourpage.php'</script>";
}
}
$conn->close();
?>

Mysqli num row returned is not working

I'm wondering why it is not working for mysqli eventhou mysql_num_row is working.
if (mysql_num_rows($rows) > 0) {
echo "<p>That name has been taken </p>";
}
That is mysql. But, Im trying convert it to mysqli.
if (mysqli_num_rows($rows) > 0) {
echo "<p>That name has been taken </p>";
}
It supposed to be displayed on the screen but it's not. And there is nothing error message displayed. Or am I missing something? Any ideas?
First, a quick tutorial on some of the differences between mysql_* and mysqli_* functions.
In mysql_* you would have 3 parameters for your DB connection, then have a seperate line for your DB selection.
For example:
$db = mysql_connect("host","username", "password");
$db_selected = mysql_select_db('db_name', $db);
if (!$db_selected) {
die ('Can\'t use this : ' . mysql_error());
}
Your query would come first, followed by your DB connection.
For example:
mysql_query($query,$db);
But in mysqli_* things have changed including the parameters location. You now put all 4 parameters, for example (if you haven't done so yet):
$db = new mysqli("host","username", "password", "db_name");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
then the DB connection would come first, followed by the query instead of the other way around:
mysqli_query($db,$query);
A sample query:
$email = mysqli_real_escape_string($db,$_POST['email']);
$query = mysqli_query($db, "SELECT * FROM table_name WHERE email='".$email."'");
if(mysqli_num_rows($query) > 0){
echo "email already exists";
}else{
$sql="INSERT INTO table_name (email) VALUES ('$email')";
if (!mysqli_query($db,$sql))
{
die('Error: ' . mysqli_error($db));
}
}
You could try this code:
$connect = new mysqli("localhost", "user", "password", "database");
$query = "SELECT name FROM table";
$statement= mysqli_prepare($connect, $query)
mysqli_stmt_execute($statement);
mysqli_stmt_store_result($statement);
if (mysqli_stmt_num_rows($statement) > 0) {
echo "<p>That name has been taken </p>";
}
mysqli_stmt_close($statement);
mysqli_close($connect);

PHP insert query not working

<html>
<body>
<?php
$host = 'localhost';
$user = 'users';
$pw = '';
$db = '#######';
$connect = mysql_connect($host,$user,$pw)
or die ("Could not connect.");
mysql_select_db($db);
$sql = mysql_query("INSERT INTO users VALUES ('','l','l','l','l','l','l')");
if(mysql_query($sql)){
print "Item added successfully.<br/>";
}
else{
print "Item addition failed.<br/>";
}
?>
</body>
</html>
I am trying to insert these values into my database into the table users but when I run the code it keeps on saying "item addition failed" but I am not sure why, there is no problem with the database connection as I have already tested that, and I am not sure what's wrong with my insert query?
There are some problems in your code. Firstly you do query twice. Secondly are you sure your db name is $db = '#######'; change it to proper name.
To check if query was ok and if rows were added use mysql_affected_rows() to check errors use mysql_error()
Also change your sql engine to PDO or mysqli which are better.
Please mind that Mysql_* functions are depracated. That is why I've given you example how to use db connection in PDO.
<?php
$host = 'localhost';
$user = 'users';
$pw = '';
$db = '#######'; //CHANGE IT TO PROPER NAME WHERE TABLE users IS!
$connect = mysql_connect($host,$user,$pw)
or die ("Could not connect.");
mysql_select_db($db);
$sql = mysql_query( "INSERT INTO users VALUES('' ,'l','l','l','l', 'l','l')") or die(mysql_error());
if(mysql_affected_rows()>0)
echo "Item added successfully.<br/>";
else
echo "Item addition failed.<br/>";
?>
I'll give you proper example how to do it with PDO cause if you still learn it'll help you :)
PDO example
<?php
$dsn = 'mysql:dbname=YOUR_DB_NAME;host=localhost';
$user = 'users';
$password = '';
try {
$dbh = new PDO($dsn, $user, $password);
$count = $dbh->exec("INSERT INTO users VALUES('' ,'l','l','l','l', 'l','l');");
echo $cout ? "Item added successfully" : "Item addition failed";
} catch (PDOException $e) {
echo 'Failed: ' . $e->getMessage();
}
?>
The secure and good way to insert values is using prepared statements.
To create prepared statement you use
$stmt = $dbh->prepare("INSERT INTO users (name, email) VALUES(?,?)");
$stmt->execute( array('user', 'user#example.com'));
You can learn more here
You are using mysql_query twice. Change your code to:
$sql = "INSERT INTO users VALUES ('' ,'l','l','l','l', 'l','l')";
try this.your called function mysql_query() twice.
on second time you passed it the result_set instead of query.
<html>
<body>
<?php
$host = 'localhost';
$user = 'users';
$pw = '';
$db = '#######';
$connect = mysql_connect($host,$user,$pw)
or die ("Could not connect.");
mysql_select_db($db);
$sql = mysql_query( "INSERT INTO users
VALUES('' ,'l','l','l','l', 'l','l')");
if($sql){
print "Item added successfully.<br/>";
}
else { print "Item addition failed.<br/>"; }
?>
</body>
</html>
This should help you debug, you should look into PDO instead though... And of course remember to use the correct credentials, i presume you have removed them for safety :-)
mysql_select_db($db);
$sql = mysql_query("INSERT INTO users VALUES ('','l','l','l','l','l','l')", $connect) OR die(mysql_error());
if($sql)
{
print "Item added successfully.<br/>";
}
else{
print "Item addition failed.<br/>";
}
?>

Categories