i am adapting this code to Mysqli, but is gives an error, i cannot see the error, please help.
$sql = "INSERT INTO test_xml ('title', 'artist', 'duration') VALUES ('$title', '$artist', '$duration')";
$result = mysqli_query($con, $sql);
the old code worked good:
$sql = "INSERT INTO `test_xml` (`title`, `artist`, `duration`)"
. "VALUES ('$title', '$artist', '$duration')";
$result = mysql_query($sql);
Risking downvotes, but I can't comment at my level so in order to try help I'll assume the question is "how can I see the error" and try answer that, as there's not much else to go on;
First, is $con created successfully?
$con = new mysqli("sql server hostname or ip", "user", "password", "schema/db name");
if($con->connect_errno > 0)
{
die('Unable to connect to database [' . $con->connect_error . ']');
}
As per comments, problem solved due to ' vs ` for column names.
$sql = "INSERT INTO test_xml (`title`, `artist`, `duration`) VALUES ('$title', '$artist', '$duration')";
if(!$result = $con->query($sql)) {
die('There was an error running the query [' . $con->error . ']');
} else {
echo "Successful query.";
}
this portion was really to include the error handling to see what the error was.
ok it was in the line:
$sql = "INSERT INTO test_xml ('title', 'artist', 'duration')
in the columms,
the ' must be ` like #Mihai and #RiggsFolly said.
Related
I am trying to insert values into a table in my database. The first param is a non null variable, the next two are the two columns I want to pass in as well. What is wrong with my logic here.
$query = "SELECT cnum, cname FROM course WHERE specialization = '0'";
$result = mysqli_query($conn,$query);
if (!$result) die ("Database access failed: " . $conn->error);
$rows = $result->num_rows;
for ($j =0; $j<$rows;++$j) {
$row = mysqli_fetch_array($result);
$query = "INSERT INTO student_schedule VALUES ('$studentID', '$row[0]', '$row[1]', '0')";
$result = $conn->query($query);
if (!$result) die ("Database access failed: " . $conn->error);
}
Your solution
<?php
$query = "SELECT cnum, cname FROM course WHERE specialization = '0'";
$result = mysqli_query($conn,$query);
if (!$result) die ("Database access failed: " . $conn->error);
while ($row = mysqli_fetch_array($result)) {
$insertQuery = "INSERT INTO student_schedule VALUES ('" . $conn->real_escape_string($studentID) . "', '" . $conn->real_escape_string($row[0]) . "', '" . $conn->real_escape_string($row[1]) . "', '0')");
$insert = $conn->query($insertQuery);
if (!$result) die ("Database access failed: " . $conn->error);
}
?>
Also, as a general rule, I suggest you don't mix MySQLi Procedural code with Object-Oriented code. Lastly, I also suggest you remove error outputting $conn->error, instead, capture the error and print out a custom error message instead. This reduces injection attacks.
Your code is vulnerable to SQL Injections, that might to be the reason why it doesn't work properly.
You should escape the data before including it into an SQL query:
for ($j =0; $j<$rows;++$j) {
$row = mysqli_fetch_array($result);
$query = $conn->prepare("INSERT INTO student_schedule VALUES (?, ?, ?, '0')";
$query->bind_param('iss', $studentID, $row[0], $row[1]);
$result = $query->execute();
if (!$result) die ("Database access failed: " . $conn->error);
}
You can find more information on the bind_param() function in the PHP manual.
I'm trying to create a simple sql statement in my php file, to insert two values into the database. Its throwing the error I implemented for non valid sql statements, and I believe its because the VALUES( ) part is wrong. How do I concatenate the single quotes for the sql statement? The database values should be varchars.
$sql = "INSERT INTO visitor_log_marcusw1(email_user, email_provider) "
. "VALUES ('".$email_user."' , '".$email_provider."')";
mysqli_query($con, $sql);
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
if (mysqli_query($conn, $sql)) {
Replace this with
if (mysqli_query($con, $sql)) {
$con not $conn
Try this:
$sql = "INSERT INTO visitor_log_marcusw1 (email_user, email_provider) VALUES ('{$email_user}' , '{$email_provider}')";
Also, there seems to be a typo with in the connection name ($conn vs $con).
Use mysql function mysql_real_escape_string($php_variable)
$sql = "INSERT INTO visitor_log_marcusw1(email_user, email_provider) \n"
. "VALUES (mysql_real_escape_string($email_user) , mysql_real_escape_string($email_provider)";
When my form is submitted (via Ajax), I'm getting the following error message:
[17-Oct-2012 11:46:29] PHP Warning: mysqli_query() [<a href='function.mysqli-query'>function.mysqli-query</a>]: Empty query in /home1/xenongro/public_html/testing/enrolment/thanks.php on line 32
I have a suspicion that it's something to do with the if/else statements, but not sure what the actual problem is.
Can anyone help?
<?php
$firstname = htmlspecialchars(trim($_POST['fname']));
$lastname = htmlspecialchars(trim($_POST['lname']));
$worktel = htmlspecialchars(trim($_POST['worktel']));
$dbc = mysqli_connect('localhost', 'xxxxx', '<xxxx>', 'xxxx')
or die ('Could not connect to MySQL server.');
if ($level != "IOSH Managing Safely"){
if ($funding == "Self Funding"){
$query = "INSERT INTO enrolments (fname, lname, worktel)" .
"VALUES ('$firstname', '$lastname', '$worktel')";
}
else if ($funding == "Employer Funding"){
$query = "INSERT INTO enrolments (fname, lname, worktel)" .
"VALUES ('$firstname', '$lastname', '$worktel')";
}
}
else if ($level == "IOSH Managing Safely"){
if ($funding == "Self Funding"){
$query = "INSERT INTO enrolments (fname, lname, worktel)" .
"VALUES ('$firstname', '$lastname', '$worktel')";
}
else if ($funding == "Employer Funding"){
$query = "INSERT INTO enrolments (fname, lname, worktel)" .
"VALUES ('$firstname', '$lastname', '$worktel')";
}
}
$result = mysqli_query($dbc, $query)
or die ('error querying database');
mysqli_close($dbc);
?>
try
var_dump($query);
var_dump($funding);
just before
$result = mysqli_query($dbc, $query);
it'll give you more information
I suspect that $funding might have slight variation to your constant strings
might be typo / extra space / cap case
There are two situation where no query is being set:
the level does not match the string, or the funding does not match the string.
It might be a problem with the spaces.
Worse, you don't use mysql_real_escape_string and unless magic_quotes_gpc is on, this allows an attacker to inject his SQL.
$funding doesn't appear to be defined in the code example provided, so none of your if's will match.
<?php
$ip = $_SERVER['REMOTE_ADDR'];
$date = date("d/m/y : H:i:s", time());
$dbc = mysqli_connect('localhost', 'root', 'derp', 'derpdb')
or die("Database connection fried.");
$query = "INSERT INTO ipstore (tstamp, ip), " .
"VALUES ('$date', '$ip')";
mysqli_query($dbc, $query);
mysqli_close($dbc);
?>
Can anyone tell me what's wrong with this code? It's meant to store the users IP/date they requested the page in the database. I've tried replacing localhost with 127.0.0.1, no luck. It doesn't bring a message, so it must be connected, however when it comes to querying it just doesn't do it. And it doesn't give a warning. I've checked the DB, nothings there.
Also don't worry, nothing sensitive is there ;)
Thanks
$query = "INSERT INTO ipstore (tstamp, ip), " . "VALUES ('$date', '$ip')";
You are not supposed to use a comma after specifying columns - try
$query = "INSERT INTO ipstore (tstamp, ip) VALUES ('$date', '$ip')";
try it this way
$query = mysql_query("INSERT INTO ipstore (tstamp,ip) VALUES ('$date', '$ip')") or die(mysql_error()); if($query) {echo 'Success'; esle { echo 'Failed'; }
And you will get success for sure
I'm trying to insert a value into my sql table that has html in it: like follows
<?
$story ="<div class='post'><p class='date'>$mont<b>$day</b></p><h2 class='title'>lkjljt</h2><p class='meta'><small>Posted $name | $school, $date | Rating</small></p><div class='entry'>$message</div></div>";
$db = mysql_connect("host", "user", "password");
mysql_select_db("db", $db);
if (!$db)
{
die('Could not connect: ' . mysql_error());
}
$sql = "INSERT INTO Post VALUES ('', '$date', '$time', '$story', '$school','$location', '$sex', '$zipcode', '$name');";
$result = mysql_query($sql);
if($result)
{ $success = " Your hookup has been submitted ";}
else{
$error = "something went horribly wrong" . mysql_error();}
?>
I keep getting a syntax error when I submit this page, and if I comment $story out, the query runs fine. How can I fix this?
The most likely reason is that $story contains single quotes, which will break the query.
Protect it using mysql_real_escape_string
In general, this is a bad idea as it is open to SQL injection.
$sql = "INSERT INTO Post VALUES ('', '$date', '$time', '$story',
'$school','$location', '$sex', '$zipcode', '$name');";
At least, use mysql_real_escape_string which will protect the input for characters that have special meaning in a MySQL query. Use it on all textual columns.
$sql = "INSERT INTO Post VALUES ('', '$date', '$time', '" .
mysql_real_escape_string($story) . "','".
mysql_real_escape_string($school) . "','".
mysql_real_escape_string($location) . "', '$sex', '$zipcode', '" .
mysql_real_escape_string($name) ."');";
If you didn't care about SQL Injection ( though I dont know why would you wouldnt ) you could also use htmlspecialchars to fix your problem. mysql_real_escape_string is obviously the better choice though like #cyberkiwi said