This isn't anything overly complicated (I assume), I'm just not sure of the syntax for doing what I want. I'm trying to insert a value from an array into the database. Below achieves what I want to do, however I was wondering if it could be reformatted to the code below that.
Current code which does what I want:
$name = explode(" ",$fullName);
$firstName = $name[0];
$lastName = $name[count($name) - 1];
mysql_query("INSERT INTO `person` VALUES(NULL, '$firstName', '$lastName',0)"));
What I want to know is if it can be formatted like this:
$name = explode(" ",$fullName);
mysql_query("INSERT INTO `person` VALUES(NULL, '$name[0]', '$name[count($name) - 1]',0)"));
I tried this earlier a few different ways and got an error, is it just an issue with syntax or is it something a bit deeper?
Oh, and I should add that the only time I actually got the insert to run fully, I ended up with Array[0] and Array[2] - 1 in the first_name and last_name columns respectively.
Thanks all, hopefully I've been clear enough. Need any more info, let me know.
You may try this:
mysql_query("INSERT INTO `person` VALUES(NULL, '$name[0]', '".$name[count($name) - 1]."' ");
Try this:
$name = explode(" ",$fullName);
$query="INSERT INTO person VALUES(NULL,'". $name[0]."','".$name[count($name) - 1]."'";
mysql_query($query);
Try this:
mysql_query("INSERT INTO `person` VALUES(NULL, '{$name[0]}', '{$name[count($name) - 1]}',0)");
Related
Before you spam as duplicate I have read through around 20-30 posts on this site about how to do this as well as others and I can't get mine to work so thats why i am asking the question.
I have the following code:
$lookupID = "SELECT ID FROM dungeon WHERE Name = '$loc'";
$result = mysqli_query($connection, $lookupID);
$row = mysqli_fetch_row($result);
$locID = $row['ID'];
$query = "INSERT INTO boss (ID, Name, Type, Location, LocationID, Difficulty) VALUES ('0', '$boss', '$type', '$loc', '$locID', '$diff')";
The purpose for the lookupID is to based upon the $loc value lookup in the other table what the locID value associated with it is and set $locID to that number. Currently when I run the query I get the following:
Error: INSERT INTO boss (ID, Name, Type, Location, LocationID, Difficulty) VALUES ('0', 'Godzilla', 'Lizard', 'Black Rock Hold', '', '4')
With the locID variable giving no value and so causing the error. Im sure its something simple and stupid I am doing but I am new to php and mysql so I hope you forgive me.
The mysqli_fetch_row function returns the array with enumerated keys, so you should use
$locID = $row[0];
If you want, you can use mysqli_fetch_assoc to get the row with associative keys instead.
$sql = 'INSERT INTO photo '.
'(id,cid, path,date) '.
'VALUES (,`$cid`, `$new`,)';
There are four columns in the table, "photo".
1) id - auto increment
2) cid - $cid
3) path - $new
4) time - timestamp
Now I want to insert new data only to the cid and path fields. How can I do it with the above mentioned code
Try this:
//$con = you connection
$sql = "INSERT INTO photo (cid, path) VALUES ('$cid', '$new')";
mysqli_query($con, $sql);
this is as simple try this
$sql = "INSERT INTO photo (`cid`, `path`) VALUES ('$cid', '$new')";
Try this, if you know the value of id and date column value then pass it, other wise you just skip it or atlast pass the default value.
$sql = "INSERT INTO photo (cid, path,`date`) VALUES ('$cid', '$new',now())";
$sql = "INSERT INTO photo (cid, path,`date`) VALUES ('$cid', '$new',CURRENT_TIMESTAMP)";
1st of all... this is how you do debugging:
Run the query in phpmyadmin (echo query from php then run in phpmyadmin to see exactly what error you are getting, then adjust and test until it works properly
2nd: The ID. Either you lose it, like other people suggested above or you set it NULL and it gets auto incremented if it's set right in the schema.
I'm not trying to just give you a solution, i'm trying to get you some information, so you don't have to ask the next time.
$sql = "INSERT INTO photo (id,cid, path,date) VALUES (NULL,'".$cid."', '".$new."',now())";
mysqli_query($con, $sql);
You have some errors in your query
You have used tick mark around the variables which is invalid
Unwanted , at starting while entering values
This is not an error, but an advice:There is no need for breaking a query into several parts until it is large.
For inserting only cid and path Do like this
$sql = "INSERT INTO photo (cid, path) VALUES ('".$cid."', '".$new."')";
<html>
<head>
HTML CODE
<?
$username="xxxxxx";
$password="xxxxxx";
$database="xxxxxx";
mysql_connect(localhost,$username,$password);
$escape = "INSERT INTO monster VALUES ('',$_POST["name"],$_POST["soort"])";
$escape2 = "DELETE monster FROM monster LEFT OUTER JOIN (
SELECT MIN( ID ) AS ID, NAME, PREF
FROM monster
GROUP BY NAME, PREF
) AS KeepRows ON monster.ID = KeepRows.ID
WHERE KeepRows.ID IS NULL";
$query=mysql_real_escape_string($escape);
$query2=mysql_real_escape_string($escape2);
#mysql_select_db($database) or die("MySQL error: Kan inte ansluta till databasen.");
mysql_close();
?>
</body>
</html>
Every time i run this(from another file, containing the name and soort post's) I get an 500 internal server error. First I figured that the queries may be the problem, but they don't even get executed. However, i tried to escape the queries. But still error.
What is wrong with this code? (note: $escape2 is some code i found that removes duplicates in the database. But i don't really know how to format it so that it can be used through php.)
Use something like below...
$query = "INSERT INTO monster VALUES ('', '".$_POST["name"]."', '".$_POST["soort"]."')";
Please do not insert values without escaping.
problem in insert into statement
it should be
$escape = "INSERT INTO monster VALUES ('',".$_POST['name'].",".$_POST['soort'].")";
it is preferable to write colums name while writing insert queries
if column contains string values like VARCHAR or TEXT then use quoted_printable_decode
pass null if column is autoincrement
insert statment
$escape = "INSERT INTO monster (col1, col2, col3) VALUES (NULL,'".$_POST['name']."',".$_POST['soort'].")";
or
$escape = "INSERT INTO monster (col2, col3) VALUES ('".$_POST['name']."',".$_POST['soort'].")";
It looks like you need something like this:
$query = "INSERT INTO monster VALUES ('', '".$_POST["name"]."', '".$_POST["soort"]."')";
Also I would suggest to use prepared statements because it is bad experience to build queries.
First of all I have cool proposition for you. What do you say about some advanced PHP? One step further into great world of safe PHP + MySQL apps?
Introducting to you a PDO. (I know this is not answer to your question but you can consider it). Example of use on your queries:
$db = new PDO('mysql:host=localhost;dbname='.$database, $username, $password);
$insertQuery = $db->prepare('INSERT INTO monster VALUES ("", :name, :soort)');
$deleteQuery = $db->prepare('DELETE monster FROM monster LEFT OUTER JOIN (
SELECT MIN( ID ) AS ID, NAME, PREF
FROM monster
GROUP BY NAME, PREF
) AS KeepRows ON monster.ID = KeepRows.ID
WHERE KeepRows.ID IS NULL');
//to execute query:
$deleteQuery->execute();
//or with params:
$insertQuery->execute(array(
':name' => $_POST['name'],
':soort' => $_POST['soort'],
));
Cool, huh? There is more... Now according to your problem it could be everything (as we don't have error log) but my guess is:
Try to use <?php instead of <?
$escape = "INSERT INTO monster VALUES ('',{$_POST["name"]},{$_POST["soort"]})";
EDIT:
As you provided error log - now I'm sure that problem is in $escape query. It's because you used $escape = " <- and then $_POST["name"] so there was a collision of " (if I can say so).
Try this:
Whenever you insert string type of values in the database using query it has to pass in the quote format. So you just need to change your insert query here.
$query = "INSERT INTO monster VALUES ('', '".$_POST["name"]."', '".$_POST["soort"]."')";
write query like this.
-
Thanks
im trying to update my table using the following query...
$query = mysql_query("UPDATE `outgoings` (id, user_id, bill, bill_name, bill_description, bill_colour ) VALUES ('$id', '$uid', '$bill', '$billname', '$billdescription', '$billcolour') WHERE id = '$id'") or die(mysql_error());
It returns...
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 '(id, user_id, bill, bill_name, bill_description, bill_colour ) VALUES ('', '8464' at line 1
Ive tried removing ' around my variables and googling for alternative methods but cant seem to figutre out what imdoing wrong?
Use this syntax for update statements:
UPDATE `outgoings` set id = '$id', user_id = '$uid' ... where ...
You got it mixed with insert statement I guess.
It looks like your ID is empty (...VALUES ('',...). Should there be an ID there?
Your $id seems to be empty or not defined yet. Read mysql.error() up to the end.
The update query has different syntax, something like that:
UPDATE `outgoings` SET user_id='$uid', bill='$bill' WHERE id = '$id'
What I am wondering is how you can use INSERT INTO if you don't know how many fields there will be in advance. My project involves adding columns if required. Therefore my code will look like this:
$query = "INSERT INTO table (could be any amount) VALUES (could be any amount)";
Is it possible to populate the 'could be any amount' parts from arrays? These could be as follows:
$array1 = (fieldname, fieldname, fieldname);
$array2 = (value, value, value);
Thanks in advance for any help you can give.
$array2 = array_map('mysql_real_escape_string', $array2);
$query = "INSERT INTO table (`".implode("`,`", $array1)."`)"
." VALUES ('".implode("','", $array2)."')";
But You should not use such bad practices.