The following php code is meant to drop a table if it exists, create the table, use the table, and then insert a row into the table.
Everything works apart from the insert. I am new to PHP and MYSQL and I have tried many permutations of different types of quotes (singles, doubles, this one: `) but cannot get the data to be inserted into the table.
Can anybody shed some light on what is wrong with this?
$retval = mysqli_query($conn,'INSERT INTO `performance` (manager, program, programid, yearmonth, performance) VALUES ("manager1", "program1","programid1", "199901", "-3.4")');
The php script below gives the output:
Connected successfully
Table dropped successfully.
DB used successfully.
Table created successfully.
Could not insert data.
So everything worked apart from the insert.
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully<br />';
$retval = mysql_query('DROP TABLE IF EXISTS `managedfutures`.`performance`') or die(mysql_error());
if(! $retval )
{
die('Could not drop table ' . mysql_error());
}
echo "Table dropped successfully.";
echo "<br>";
$retval = mysql_query("USE managedfutures", $conn);
if(! $retval )
{
die('Could not use DB' . mysql_error());
}
echo "DB used successfully.";
echo "<br>";
$sql = "CREATE TABLE performance( ".
"performance_id INT NOT NULL AUTO_INCREMENT, ".
"manager VARCHAR(255) NOT NULL, ".
"program VARCHAR(255) NOT NULL, ".
"programid VARCHAR(255) NOT NULL, ".
"yearmonth VARCHAR(6) NOT NULL, ".
"performance FLOAT NOT NULL, ".
"PRIMARY KEY (performance_id )); ";
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not create table: ' . mysql_error());
}
echo "Table created successfully.";
echo "<br>";
$retval = mysqli_query($conn,'INSERT INTO `performance` (manager, program, programid, yearmonth, performance) VALUES ("manager1", "program1","programid1", "199901", "-3.4")');
if(! $retval )
{
die('Could not insert data. ' . mysql_error());
}
echo "Data inserted successfully.";
echo "<br>";
return;
Thanks to Mike W for pointing out that I had mixed mysql and mysqli commands! I am new to php/mysql and did not realise that there was a difference between the two. There was another error also, I was inputting a number as a string in the insert statement. I.e. I wrote "-3.4" instead of just -3.4.
For completeness, here is the fixed version which works.
$mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
if ($mysqli->connect_errno) {
die("Failed to connect to MySQL: " . $mysqli->connect_error);
}
echo 'Connected successfully<br />';
$retval = mysqli_query($mysqli,"DROP TABLE IF EXISTS `performance`");
if(! $retval )
{
die('Could not drop table ' . $mysqli->query_error);
}
echo "Table dropped successfully.";
echo "<br>";
$sql = "CREATE TABLE performance( ".
"performance_id INT NOT NULL AUTO_INCREMENT, ".
"manager VARCHAR(255) NOT NULL, ".
"program VARCHAR(255) NOT NULL, ".
"programid VARCHAR(255) NOT NULL, ".
"yearmonth VARCHAR(6) NOT NULL, ".
"performance FLOAT NOT NULL, ".
"PRIMARY KEY (performance_id )); ";
$retval = mysqli_query($mysqli, $sql);
if(! $retval )
{
die('Could not create table: ' . $mysqli->query_error);
}
echo "Table created successfully.";
echo "<br>";
$retval = mysqli_query($mysqli, "INSERT INTO `performance` (`manager`, `program`,`programid`, `yearmonth`, `performance`) VALUES ('manager1', 'program1','programid1', '199901', -3.4)");
if(! $retval )
{
die('Could not insert data. ' . $mysqli->query_error);
}
echo "Data inserted successfully.";
echo "<br>";
return;
You're mixing mysql_*() and mysqli_*() calls. The two are different and cannot be used together. mysql_*() is deprecated - use only mysqli_*().
You have used mysql_query throughout your code
$retval = mysql_query( $sql, $conn ); //**You have used mysql_query**
if(! $retval )
{
die('Could not create table: ' . mysql_error());
}
echo "Table created successfully.";
echo "<br>";
Suddenly a mysqli_query is seen (MAGIC !!!).
$retval = mysqli_query($conn,'INSERT INTO `performance` (manager, program, programid, yearmonth, performance) VALUES ("manager1", "program1","programid1", "199901", "-3.4")');
^^
// SUDDENLY you see mysqli_query
Related
This is a webpage that I have:
// Info to connect to the Wishlist database
$servername = "em";
$dbusername = "";
$password = "!19";
$dbname = "";
// To connect to the database please
$conn = new mysqli($servername, $dbusername, $password, $dbname);
// If unable to connect to the database display this error
if ($conn->connect_error) {
echo "Connection to wishlist failed";
die("Connection failed: " . $conn->connect_error);
}
echo "Once you have added creatures to your wishlist, click " .
"<strong><a href='http://eggcavity.com/edit-wishlist'>here</a></strong> to edit your wishlist.";
// Get current user's username
$current_user = wp_get_current_user();
$username = $current_user->user_login;
// Retrieve data from the database
$sql = "SELECT Name, Stage1 FROM Creatures";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// Display all of the data from the database
echo '<form method="POST">';
while($row = $result->fetch_assoc()) {
echo '<div style="display: inline-block; width: 30%;">' .
'<img src="' . $row["Stage1"] . '"><br>'.
$row["Name"] .
'<br><input type="checkbox" name="creautres[]" value="' .
$row["Name"] .
'"></div>';
}
echo '<br><br><input type="submit" value="Submit"></form>';
} else {
echo "Creatures not found";
}
if(isset($_POST['submit'])){
foreach($_POST['creatures'] as $selected){
$sql = "INSERT INTO " . $username .
" (Creature, Picture, Stage, Gender, Frozen, Notes) VALUES ('" .
$selected . "', 'http://static.eggcave.com/90x90/" . $selected .
"_1', 'Stage1', 'Unspecified', 'Unspecified', 'Unspecified', '')";
if ($conn->query($sql) === FALSE) {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
}
// Close the connection to the database
$conn->close();
It displays like I want it to:
But it doesn't update the database when I click the submit button.
I've tried echoing $stmt, it seemed to be written as it should be.
When I try echoing $selected, within the loop it doesn't seem to output anything.
Can you help me?
I have updated the code to use one database. Please help me. It still isn't adding.
You had a typo in your checkbox name. I re-did the submit line in the form and the isset() I believe.
The below includes activating error reporting, a try/catch, binding for safety against sql injection. The data saves. You will need to deal with what should be unique data getting saved more than once of course. For instance, a unique key on (Creature,Username). And I would re-think the columns for Id's, but this was your table design. Thanks for allowing us to show you a re-use of a table. Good luck.
schema (from you):
drop table if exists Wishlists;
CREATE TABLE `Wishlists` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`Creature` varchar(100) DEFAULT NULL,
`Picture` varchar(200) DEFAULT NULL,
`Stage` varchar(100) DEFAULT NULL,
`Gender` varchar(100) DEFAULT NULL,
`Frozen` varchar(100) DEFAULT NULL,
`Notes` varchar(500) DEFAULT NULL,
`Username` varchar(100) DEFAULT NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB; -- <------------------------ went with InnoDB
-- truncate table Wishlists; -- used during early testing
PHP (eggs01.php):
// Info to connect to the Wishlist database
$servername = "serve it up";
$dbusername = "dbu dbu dbu";
$password = "OpenSesame";
$dbname = "my db name";
try {
// To connect to the database please
$conn = new mysqli($servername, $dbusername, $password, $dbname);
if ($conn->connect_error) {
die('Connect Error (' . $conn->connect_errno . ') '
. $conn->connect_error);
}
echo "I am connected and feel happy.<br/>";
if(isset($_POST['submit'])){
// Postback - submit
// Get current user's username
//$current_user = wp_get_current_user(); // remmed out, I don't have your system
//$username = $current_user->user_login; // remmed out, I don't have your system
$theCount=0;
foreach($_POST['creatures'] as $selected){
$Creature=$selected;
$Picture="http://static.eggcave.com/90x90/" . $selected . "_1";
$Stage="Stage1";
$Gender="Unspecified";
$Frozen="Unspecified";
$Notes="Unspecified";
$Username="Stackoverflow123";
$sql = "INSERT Wishlists (Creature, Picture, Stage, Gender, Frozen, Notes, Username) " .
" VALUES (?,?,?,?,?,?,?)";
$stmt = $conn->prepare($sql); // SQL Injection - safe prepare / bind / execute
// 7 s's means 7 strings:
$stmt->bind_param('sssssss', $Creature, $Picture, $Stage, $Gender, $Frozen, $Notes, $Username);
$stmt->execute();
$theCount++;
}
echo "<br>Santa has been notified, count = ".$theCount."<br>";
}
else {
// Just display the form
// Retrieve data from the database
$result = $conn->query("SELECT Name, Stage1 FROM Creatures");
if ($result->num_rows > 0) {
// Display all of the data from the database
echo '<form method="POST">';
while($row = $result->fetch_array(MYSQLI_ASSOC)) {
echo '<div style="display: inline-block; width: 30%;">' .
'<img src="' . $row["Stage1"] . '"><br>'.
$row["Name"] .
'<br><input type="checkbox" name="creatures[]" value="' .
$row["Name"] .
'"></div>';
}
echo '<br><br><button type="submit" name="submit">Submit</button></form>';
$result->close();
} else {
echo "Creatures not found";
}
}
} catch (mysqli_sql_exception $e) {
throw $e;
}
After the submit having selected 3 eggs:
Database Image:
First of all, look at code
$dbname1 = *****";
Here you are missing " :
So replace this with
$dbname1 = "*****";
and try again
First issue is you should never run a SQL statement in a Loop ALWAYS AVOID THIS - as it will put your server through a lot of strain.
And 2nd try this and tell me the out put
foreach($_POST['creatures'] as $selected){
$stmt = "INSERT INTO " . $username . " (Creature, Picture, Stage, Gender, Frozen, Notes) VALUES ('" . $selected . "', 'http://static.eggcave.com/90x90/" . $selected . "_1', 'Stage1', 'Unspecified', 'Unspecified', 'Unspecified', '')";
if ($conn->query($stmt) === TRUE) {
}
}
TO
foreach($_POST['creatures'] as $selected){
$stmt = "INSERT INTO " . $username . " (Creature, Picture, Stage, Gender, Frozen, Notes) VALUES ('" . $selected . "', 'http://static.eggcave.com/90x90/" . $selected . "_1', 'Stage1', 'Unspecified', 'Unspecified', 'Unspecified', '')";
$result = $conn->query($stmt) OR die(var_dump($conn));
var_dump($result->fetch_array(MYSQLI_ASSOC));
die;
}
i use this code for insert data in mysql but it directly shows error
" Could not enter data: "......
else
{
$image=$_FILES['img']['name'];
$tmp_name=$_FILES['img']['tmp_name'];
$path= "/var/www/html/uploads/".$image;
if(move_uploaded_file($name,$path))
{
$sql = "INSERT INTO form1 ". "(fname,lname,username,password,age,email,branch,college,
gender,image_p,) ". "VALUES('$fname','$lname','$username','$password','$age','$mail','$branch','$college','$gender','$image')";
$retval = mysql_query( $sql, $conn );
}
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
}
else
{
echo "Entered data successfully\n"."\n ";
echo "you are now a registered user.";
mysql_close($conn);
}
$sql = "INSERT INTO form1 (fname,lname,username,password,age,email,branch,college,
gender,image_p) VALUES ('".$fname."','".$lname."','".$username."','".$password."','".$age."','".$mail."','".$branch."','".$college."','".$gender."','".$image."')";
$retval = mysql_query( $sql, $conn );
$image=$_FILES['img']['name'];
$tmp_name=$_FILES['img']['tmp_name'];
$path= "/var/www/html/uploads/".$image;
move_uploaded_file($name,$path);
if(! $retval ){
die('Could not enter data: ' . mysql_error());
}else{
echo "Entered data successfully\n"."\n ";
echo "you are now a registered user.";
mysql_close($conn);
}
I send an image from my Android Application to my Php server using a MySql database, but when i try to display the image in browser it doesn't work.
This is how I send the picture
String imageString=Base64.encodeBytes(this.image);
nameValuePairs.add(new BasicNameValuePair("image", imageString));
And this is how I try to display it
echo '<img src="data:image/jpeg;base64,'.base64_encode( $row['image'] ).'"/>';
I've checked and imageString in my app is different from base64_encode( $row['image']).
MySql part
$conn = new mysqli($server, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// sql to create table
$sql = "CREATE TABLE Posts (
id INTEGER UNSIGNED AUTO_INCREMENT PRIMARY KEY,
user VARCHAR(50) NOT NULL,
date VARCHAR(12) NOT NULL,
event VARCHAR(1000),
image BLOB
)";
if ($conn->query($sql) === TRUE) {
echo "Table Posts created successfully";
} else {
echo "Error creating table: " . $conn->error;
}
$conn->close();
$con = mysql_connect($server, $username, $password) or die ("Could not connect: " . mysql_error());
mysql_select_db($database, $con);
$user = $_POST['user'];
$date = $_POST['date'];
$event = $_POST['event'];
$image = $_POST['image'];
echo "Test";
$sql = "INSERT INTO Posts (user, date, event,image) ";
$sql .= "VALUES ('$user','$date', '$event', '$image')";
if (!mysql_query($sql, $con)) {
die('Error: ' . mysql_error());
} else {
echo "Insert success";
}
mysql_close($con);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row["user"]. $row["date"]. $row["event"]. "<br>";
echo '<img src="data:image/jpeg;base64,'.base64_encode( $row['image'] ).'"/>';
Your Java code is doing a Base64 encode of the image before sending it to the server. You do not need to encode it a second time when you go to display it. The result is a base64 encoded string of a base64 encoded string, which isn't what you want to do.
Try this instead:
echo '<img src="data:image/jpeg;base64,' . $row['image'] . '"/>';
Hi i am inserting value in data base in php i want that when i insert value in database then my div color should be change
insert.php
include('conn.php');
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$id=2;
//$sql="insert into messages (message,number,service) values ('dd',".$urlstring.",'ds')";
$sql = 'INSERT INTO messages '.
'(message,number,service) '.
'VALUES ( "'.$message.'", "'.$urlstring.'", "'.$service.'" )';
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
}
echo ("Records affcted: ". mysql_affected_rows());
//echo "Entered data successfully\n";
mysql_close($conn);
index.php
<div id="div1" style="height=200px;width=300px;">
</div>
here i want when insert.php execute then div section should change color in another file
How can i achieve this
Any help will be appreciated
You can use timer on javascript and create a ajax function to retrieve all inserted data on the database.
try this:
include('conn.php');
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$id=2;
//$sql="insert into messages (message,number,service) values ('dd',".$urlstring.",'ds')";
$sql = 'INSERT INTO messages '.
'(message,number,service) '.
'VALUES ( "'.$message.'", "'.$urlstring.'", "'.$service.'" )';
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
}
echo ("Records affcted: ". mysql_affected_rows());
//echo "Entered data successfully\n";
?>
<style>
#div1{
backgroud-color="yourcolor";
}
</style>
<?php
mysql_close($conn);
ah i see.
maybe this can help you: http://www.barelyfitz.com/projects/csscolor/?
I've already asked a question on this code I'm working on, just not about the same problem. Either way sorry for the repost!
So I'm having trouble with the code, as follows:
<?php
// Create connection
$host = "localhost";
$username="tudor";
$password="passw0rd";
$con=mysqli_connect($host, $username, $password);
if(! $con )
{
die('Could not connect: ' . mysqli_error());
}
echo 'Connected successfully<br />';
$db_1 = mysqli_select_db( $con, 'db_1' );
if (! $db_1) {
die('Could not select database: ' . mysqli_error());
}
else {
echo "Database successfully selected<br />===============================<br />";
}
//===================================
$a = 1;
$b = 2234;
$table = "CREATE TABLE info (id INT NOT NULL AUTO_INCREMENT, city CHAR(40), country CHAR(40))";
if (! $table) {
die('Could not create table ' . mysqli_error($con));
}
else {
echo "Table created<br />";
}
$insert = "INSERT INTO info (city, country) VALUES ($a, $b)";
if (! $insert) {
die('Could not insert ' . mysqli_error($con));
}
else {
echo "Inserted<br />";
}
$select = "SELECT * FROM info";
$result = mysqli_query ($con, $insert);
if (! $result) {
die('Result not working ' . mysqli_error($con));
}
else {
echo "Result working<br />";
}
echo "result: ".$result['city']. " ";
mysqli_close($con);
?>
This outputs (blockquote doesn't display page breaks):
Connected successfully Database successfully selected
=============================== Table created Inserted Result not working Table 'db_1.info' doesn't exist
What does it mean by "Table 'db.info'" not existing? It clearly says that my info table was created...
What I tried doing is inverting the variables in the $result query: $result = mysqli_query ($insert, $con);, because I had seen that syntax in a book. However all it gave was the following message in the output:
Warning: mysqli_query() expects parameter 1 to be mysqli, string given
in C:\wamp...
Thoughts anyone? Thanks in advance!
Edit: really appreciate the help everyone, thanks a lot!
You are not doing a mysqli_query() on $table before your mysqli_query() on $insert, and you are not doing a mysqli_query() on $select
$table = "CREATE TABLE info (id INT NOT NULL AUTO_INCREMENT, city CHAR(40), country CHAR(40))";
if (! $table)
$insert = "INSERT INTO info (city, country) VALUES ($a, $b)";
if (! $insert) {
$select = "SELECT * FROM info";
$result = mysqli_query ($con, $insert);
if (! $result)
try adding the mysqli_query() -
$table_sql = "CREATE TABLE `info` (`id` INT NOT NULL AUTO_INCREMENT, `city` CHAR(40), `country` CHAR(40), PRIMARY KEY (`id`))";
$table = mysqli_query ($con, $table_sql);
if (! $table) {
die('Could not create table ' . mysqli_error($con));
}
else {
echo "Table created<br />";
}
$insert_sql = "INSERT INTO `info` (`city`, `country`) VALUES ('$a', '$b')";
$insert = mysqli_query ($con, $insert_sql);
if (! $insert) {
die('Could not insert ' . mysqli_error($con));
}
else {
echo "Inserted<br />";
}
$select = "SELECT * FROM `info`";
$result = mysqli_query ($con, $select);
if (! $result) {
die('Result not working ' . mysqli_error($con));
}
else {
echo "Result working<br />";
}
Edit
Also, this line will fail -
echo "result: ".$result['city']. " ";
as you have to fetch the array from the query using mysqli_fetch_array()
$results = mysqli_fetch_array($result);
echo "result: ".$results['city']. " ";
Table 'db_1.info' doesn't exist
Means, that table info does not exist in db db_1 so, make sure if that is the case.
ok. Here is your code.
if(! $con )
{
die('Could not connect: ' . mysqli_error());
}
echo 'Connected successfully<br />';
if (!$con) {trigger_error("Could not connect to MySQL: " . mysqli_connect_error()); }
else { echo "Database successfully connected<br />===============================<br />"; }
$a = 1;
$b = 2234;
$table = mysqli_query($con,"CREATE TABLE IF NOT EXISTS info (`id` int(11) unsigned NOT NULL auto_increment,
`city` CHAR(40),
`country` CHAR(40), PRIMARY KEY (`id`) )ENGINE=MyISAM DEFAULT CHARSET=utf8");
if (!$table) {
die('Could not create table ' . mysqli_error($con));
}
else {
echo "Table created<br />";
}
$insert = mysqli_query ($con,"INSERT INTO info (city, country) VALUES ('$a', '$b')");
if (!$insert) {
die('Could not insert ' . mysqli_error($con));
}
else {
echo "Inserted<br />";
}
$select = mysqli_query ($con,"SELECT * FROM info");
$res=mysqli_fetch_array($select);
if (! $res) {
die('Result not working ' . mysqli_error($con));
}
else {
echo "Result working<br />";
}
echo "result: ".$res['city']. " ";
echo "result: ".$res['country']. " ";
mysqli_close($con);