How can I pass my query values from mysqli_fetch_array? - php

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.

Related

Submitting Query for PHP/mySQL - Query Failed

I am trying to submit my query into mySQL database but it keeps stating that it fails. It connects to the database fine but will not integrate the query into the table called 'ticket'.
<?php
if (isset($_POST['submit'])){
include 'mysqli_connect.php';
$query = "INSERT INTO ticket (Ticket_ID, Submit_Date, F_Name,
L_Name, Email, Ph_Num, Subject, Priority, Description)
VALUES ('$_POST[Ticket_ID]', '$_POST[Submit_Date]',
'$_POST[F_Name]', '$_POST[L_Name]', '$_POST[Email]',
'$_POST[Ph_Num]', '$_POST[Subject]', '$_POST[Priority]',
'$_POST[Description]')";
$result = mysqli_query($query) or die ('Query Failed:' .
mysqli_error());
mysql_close($conn);
} else {
echo "No submit";
}
?>
Outputs:
Connected Database SuccessfullyQuery Failed:
mysqli_query() has 2 parameters, first is the variable connection, and second is variable of query...
so I think it could be
$result = mysqli_query($conn, $query) or die ('Query Failed:' .mysqli_error($conn));
Try this code:
$query = "INSERT INTO ticket (Ticket_ID, Submit_Date, F_Name,
L_Name, Email, Ph_Num, Subject, Priority, Description)
VALUES ('{$_POST['Ticket_ID']}', '{$_POST['Submit_Date']}',
'{$_POST['F_Name']}', '{$_POST['L_Name']}', '{$_POST['Email']}',
'{$_POST['Ph_Num']}', '{$_POST['Subject']}', '{$_POST['Priority']}',
'{$_POST['Description']}')";
and replace mysqli_query($query), mysqli_error(), mysql_close($conn) with
mysqli_query($conn, $query), mysqli_error($conn), mysqli_close($conn)
it should be like this
<?php
if (isset($_POST['submit'])){
include 'mysqli_connect.php';
$query = "INSERT INTO ticket (Ticket_ID, Submit_Date, F_Name,
L_Name, Email, Ph_Num, Subject, Priority, Description)
VALUES ('".$_POST['Ticket_ID']."', '".$_POST['Submit_Date']."',
'".$_POST['F_Name']."', '".$_POST['L_Name']."', '".$_POST['Email']."',
'".$_POST['Ph_Num']."', '".$_POST['Subject']."', '".$_POST['Priority']."',
'".$_POST['Description']."')";
$result = mysqli_query($conn,$query) or die ('Query Failed:' .
mysqli_error($conn));
mysqli_close($conn);
} else {
echo "No submit";
}
?>

How do I concatenate single quotes in php?

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)";

Mysqli code changes

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.

php codes stops running halfway through

I have created a php function that allows users to save their address on the database. My issue is that part of the code doesn't run at all. The code stops running at $result2= "SELECT * FROM Addressv4 WHERE Userid = '".$id."'";
It then starts working when it reaches this line of code $insert_query = "INSERT INTO Addressv4 (Userid, Housenumber, Street, Town, Postcode, DefaultAddress)
values ('$id', '$Number', '$Street', '$Town','$Postcode', '1')";
I haven't received any syntax errors when running the code either.
Any help would be grateful.
<?php
include 'dbconnect.php';
$connection = mysqli_connect($db_host, $db_username, $db_password, $db_database);
// Check connection
if (mysqli_connect_errno($connection)) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Getting data from HTML Form
$Number = $_POST['streetnumber'];
$Street = $_POST['street'];
$Town = $_POST['town'];
$Postcode = $_POST['postcode'];
$Username = $_POST['Username'];
$sql = mysqli_query($connection, "SELECT * FROM Userv2 WHERE Username = '".$Username."'");
if ($sql){
while($row = mysqli_fetch_array($sql)){
$id = $row['Id'];
}
}
$result2= "SELECT * FROM Addressv4 WHERE Userid = '".$id."'";
$sql1 = mysqli_query($connection, $result2);
$count = count($sql1);
if($count >=1){
echo 'Sorry you can only have 1 default address';
}
$insert_query = "INSERT INTO Addressv4 (Userid, Housenumber, Street, Town, Postcode, DefaultAddress)
values ('$id', '$Number', '$Street', '$Town','$Postcode', '1')";
$result = mysqli_query($connection, $insert_query);
header("Location: http://sots.brookes.ac.uk/~10031187/viewaddress.php");
mysqli_close($connection);
?>
maybe it's better to use
SELECT COUNT(Userid) AS countId FROM..
if ($row['countId'] > 1) {
that way the query will always return something, now there is a chance your query can return false..
what is the output of var_dump($sql1); ?
$sql1 is a resulset. You cannot count the number of lines like this.
Try :
$sql1_count = mysqli_num_rows($sql1)

html insertion in sql table

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

Categories