I'm trying to make it possible to add something to my guestbook through the website. But the problem is: I fail to insert into the database.
Using my WAMP server I can insert into it directly using the query down here.
I've tested the $name variables as well and they are properly filled in. I've switched $con and $sql. and I tried to format the query in different ways without{} with {}. But not even one option seems to work. The connection with my DBS works (I didn't include that part here). I tried mysql_query and mysqlI_query.
My WAMP server has php_mysqli enabled. And when I run this it doesn't give any errors.
Do you guys know what I'm doing wrong?
$con = mysqli_connect($host, $username, $password)or die("cannot connect");
mysqli_select_db($con, $db_name)or die("cannot select DB");
$datetime=date("y-m-d h:i:s"); //date time
$name= $_POST['name'];
$email= $_POST['email'];
$comment= $_POST['comment'];
$sql="INSERT INTO guestbook(name, email, comment, datetime) VALUES('{$name}','${email}','{$comment}','{$datetime}')";
mysql_query($sql,$con);
// link to view guestbook page
header('location:viewguestbook.php');
Please try this,And next time you must search mysqli prepared statements.
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$mysqli->query("insert...");
here is the problem in this statement
mysql_query($sql,$con);
problem 1: you are using mysqli and in above statement your are querying mysql.
problem 2: $con(connection variable is must be the first parameter)
Write this statement as folloing. that will solve the problem
mysqli_query($con,$sql);
In your insert query you have ${email} instead of {$email} and change mysql_query to mysqli_query
below is the code that should work
$con = mysqli_connect($host, $username, $password)or die("cannot connect");
mysqli_select_db($con, $db_name)or die("cannot select DB");
$datetime=date("y-m-d h:i:s"); //date time
$name= $_POST['name'];
$email= $_POST['email'];
$comment= $_POST['comment'];
$sql="INSERT INTO guestbook(name, email, comment, datetime) VALUES('{$name}','{$email}','{$comment}','{$datetime}')";
mysqli_query($sql,$con);
I don't know what error do you get. You can do this:
mysqli_query($con, $query) or die(mysqli_error($con));
Related
I am working on a site to share names of songs, and I have made a recommendation form that I include in every page. This recommendation form is in HTML and leads to a PHP action page, where the information received is added to a SQL table. Here is the code:
<?php
ob_start();
$host="localhost"; // Host name
$username="root"; // Mysql username
$password="MYPASSWORD"; // Mysql password
$db_name="DB NAME"; // Database name
$tbl_name="songshare"; // Table name
// Connect to server and select databse.
$link = mysqli_connect("$host", "$username", "$password")or die("cannot connect");
mysqli_select_db($link, "$db_name")or die("cannot select DB");
// Define $myusername and $mypassword
$song=$_POST['song'];
$album=$_POST['album'];
$artist=$_POST['artist'];
$linkitunes=$_POST['linkitunes'];
$artwork=$_POST['albumPic'];
// To protect MySQL injection (more detail about MySQL injection)
$song = stripslashes($song);
$album = stripslashes($album);
$artist = stripslashes($artist);
$song = mysqli_real_escape_string($link, $song);
$album = mysqli_real_escape_string($link, $album);
$artist = mysqli_real_escape_string($link, $artist);
$sql="SELECT * FROM $tbl_name WHERE song='$song'";
$result=mysqli_query($link, $sql);
if ($result->num_rows){
echo "Song already taken" . "<br />";
echo "<a href='/music.php'>music</a>";
exit();
}
$sql="INSERT INTO recommendation (user_id, artist, song, album, artwork, linkitunes)";
$sql = $sql . " VALUES ('$_SESSION['user_id']', '$artist', '$song', '$album'. '$artwork'. '$linkitunes');";
$result=mysqli_query($link, $sql);
if(!$result) {
echo "Recommendation failed" . "<br />";
echo $sql;
} else {
print "$song, $artist, $album";
}
ob_end_flush();
?>
I have checked that every username, password, link is correct and valid. My server does, in fact, run PHP. It doesn't seem to me like the PHP code is even running though.
Thank you so much in advance.
-Cameron
Turn on error reporting by adding this on top of page:
ini_set("display_errors",true);
and change this line:
$link = mysqli_connect("$host", "$username", "$password")
to
$link = mysqli_connect($host, $username, $password,$db_name);
Please have a look how to work with mysqli
Instead of '$album'. '$artwork'. '$linkitunes' Do: '$album', '$artwork', '$linkitunes', while saving data.
Try this :-
$sql = $sql . " VALUES ('".$_SESSION['user_id']."', '$artist', '$song', '$album', '$artwork', '$linkitunes')";
instead of
$sql = $sql . " VALUES ('$_SESSION['user_id']', '$artist', '$song', '$album'. '$artwork'. '$linkitunes');";
You should check the version of local server you are working with. If you are working with a higher of local server and you php was written in a lower version it throws a blank page.
I used
mysqli_connect("infos in here");
at the top of my page, and tried to use
mysqli_query("INSERT INTO and other info here");
When I do that, I get this error:
Warning: mysqli_query() expects at least 2 parameters, 1 given in (...)
But if I instead use
$con = mysqli_connect("infos in here");,
$mysqli_query($con,"INSERT INTO and other info here");
The error goes away, and my script works.
My problem is that I need to use mysqli_query two different times in my page, and I don't want to open the connection again when it's already open.
How can I handle this?
Thanks.
My problem is that I need to use mysqli_query two different times in
my page, and I don't want to open the connection again when it's
already open.
How is it a problem ? open once query as many times then close the connection, example:
<?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();
}
// Perform queries
mysqli_query($con,"SELECT * FROM Persons");
//one more
mysqli_query($con,"INSERT INTO Persons (FirstName,LastName,Age)
VALUES ('Glenn','Quagmire',33)");
mysqli_close($con);
?>
No need to connect two times. An example here..
$con = mysqli_connect("host", "user", "password", "db");
if(mysqli_connect_errno()){
die(mysqli_connect_error());
}
//Query one
$result1 = mysqli_query($con, 'Query String');
//Query Two
$result2 = mysqli_query($con, 'Query String'); //Used same $con variable
//After finishing all queries
mysqli_close($con);
If you need to select multiple database then
$con = mysqli_connect("host", "user", "password");
//for DB bd_name1
mysqli_select_db($con, 'bd_name1');
$result1 = mysqli_query($con, 'Query String');
//for DB bd_name2
mysqli_select_db($con, 'bd_name2');
$result2 = mysqli_query($con, 'Query String');
But not connect frequent time.
I´m trying to update some different registers in a mysql database sending the commands from a FOR loop in php, but the query is only done the 1st loop. Here´s the code:
$conexion = mysql_connect($hostname, $user, $pass) or die ("Error establishing connection with the Database");
mysql_select_db($db,$conexion) or die("Error selecting the Database");
$j=0;
for ($i=0;$i<count($notifs);$i++){
$sql="UPDATE tef SET notif='$notifs[$i]' WHERE sn_rec='$unsersn_recs[$j]';";
echo $sql."<br>";
$res=mysql_query($sql, $conexion) or die (mysql_error());
$j++;
}
mysql_close($conexion);
The query text is correctly done (the echo shows the different lines created), but the changes in the database are done only in the 1st loop (1st query) and I don´t receive any error. What may I be missing?
Thanks in advance!
This is wonderful example where you should use prepared statements.
I give you an example which is also secure against SQL injections.
$mysqli = new mysqli($hostname, $user, $pass, $db);
if (mysqli_connect_errno()) {
die("Error establishing connection!");
}
$stmt = $mysqli->prepare("UPDATE tef SET notif=? WHERE sn_rec=?");
$j=0;
for ($i=0;$i<count($notifs);$i++) {
$stmt->bind_param('ii', $notifs[$i], $unsersn_recs[$j]);
$stmt->execute();
if(!empty($stmt->error)) echo $stmt->error;
$j++;
}
$stmt->close();
$mysqli->close();
Hint: If notif or sn_rec are varchar/text types, just replace the 'i' with a 's' in bind_param().
http://jsfiddle.net/Fd9wx/
I made this to help solve my problem
so I have some php code and html code that should send sql Query's to the database upon the html table I have created like to set up new databases but then I fill out my form and click run it does not want to work for me. I did some google research and got nothing back now before you say "use PDO and This is no longer supported" PDO is hard for me to use because I dont understand some of it I will use it later on but not now, also I did make this script here from hand so dont say "contact script dev" if some one could point me in right direction to solving my problem or just way to make my sql errors show in my script? like the line what to remove and all
here is main part of my script
$tablename=$_POST['tablename'];
$value=$_POST['value'];
$type=$_POST['type'];
$length=$_POST['length'];
$collation=$_POST['collation'];
$attributes=$_POST['attributes'];
$null=$_POST['null'];
$extra=$_POST['extra'];
// Insert data into mysql
$sql="CREATE TABLE `a7972613_db`.`$tablename` (
`field1` $type( $length ) $null $extra
) ENGINE = MYISAM";
$result=mysql_query($sql);
// if successfully insert data into database, displays message "Successful".
if($result){
echo "Successful";
}
else {
echo "Please Go Back And Check Your Errors!";
}
thats my main part
The problem with your code is you have not selected the database.
$host = "xxxxx";
$database = "xxxxx";
$user = "xxxx";
$password = "xxxxx";
// Connect to server and select database.
mysql_connect("$host", "$user", "$password")or die("cannot connect");
Use below code for selecting database
// Connect to server and select database.
$conn = mysql_connect("$host", "$user", "$password")or die("cannot connect");
mysql_select_db($database,$conn);
and another problem is when your query fails, you have hardcoded the error,but use below code for checking where is the problem in your query
$result=mysql_query($sql) or die(mysql_error());
Change your query to
$result = mysql_query($sql) or die("Error with $sql: " . mysql_error());
with mysql_error(), you will see what your problem is.
You can dump your $sql string in order to see, whether it is correct
echo $sql;
I'm working on my first PHP/MySQL project, and I've gotten basic logins and INSERT queries working, but not updates. This is my first update, which is just one row with a state and zipcode. Is anything wrong?
$dbc = mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$state=$_POST['state'];
$zip=$_POST['zip'];
$custnum = 0;
$sql="UPDATE $tbl_name SET state = '$state', zip = '$zip', WHERE custnum = '$custnum'";
$result = mysqli_query($dbc, $sql)
or die('Error querying database.');
$sql="UPDATE {$tbl_name} SET state='{$state}', zip='{$zip}' WHERE custnum='{$custnum}'";
Remove the last comma before "WHERE" clause. Also, if you're just starting out it's good to put parenthesis around variables names when using double-quotes for strings. Helps you to distinguish the variables better.
Pekka is also correct in his comments, you are mixing mysql and mysqli functions. Use mysql_query() instead.
I think you need to get rid of the comma just before the WHERE.
$suitno =mysqli_real_escape_string($ecms,$_POST['suitno']);//protecting sql injection
$defendant=mysqli_real_escape_string($ecms,$_POST['defendant']);//protecting sql injection
$casenature=mysqli_real_escape_string($ecms,$_POST['casenature']);//protecting sql injection
$sql="UPDATE causelist SET suitno='{$suitno}',
casenature='{$casenature}' WHERE suitno='{$suitno}'";
$result = mysqli_query($ecms, $sql)
or die('Error querying database.');
$dbc = mysql_connect($host, $username, $password)or die("cannot connect"); //don't need quotes
mysql_select_db($db_name,$dbc)or die("cannot select DB"); //added the $dbc (connection link) as a second parameter
$state=mysql_real_escape_string($_POST['state']); //Should make it safe!
$zip=mysql_real_escape_string($_POST['zip']); //Should make it safe!
$custnum = 0;
$sql="UPDATE $tbl_name SET state = '$state', zip = '$zip' WHERE custnum = '$custnum'";
//removed an extra comma
//Notice that $tbl_name isn't defined!
u
$result = mysql_query($sql)
or die('Error querying database.'); //from mysqli to mysql
Looks like a sql syntax error:Remove the comma before WHERE
if(isset($_POST['update']))
{
$name=$_POST['name'];
//echo $name; die;
$surname=$_POST['surname'];
$upd="update table_name SET name='$name',surname='$surname' where id=$id";
mysql_query($upd);
}