SQL & PHP - Adding to table, failing - php

I successfully created a table in my database, using PHP. Now, I'm trying to fill it with data. When I var_dump the data I'm trying to add, it correctly renders - it's not undefined.
I don't get any errors, but there are no entries in my SQL tables. What did I do wrong? Thanks.
Database layout here:
foreach($x->channel->item as $entry) {
if ($y < 8) {
$con=mysqli_connect("localhost","usernameremoved",
"passwordremoved","databasenameremoved");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_query($con,"INSERT INTO Entries (Link, Title)
VALUES ($entry->link, $entry->title)");
echo "Tables updated successfully.";
mysqli_close($con);
$y++;
}
}
UPDATE, for Watcher:
Parse error: syntax error, unexpected '$entry' (T_VARIABLE) in C:\xampp\htdocs\ (... ) \PHP\rss\index.php on line 60
if ($y < 8) {
mysqli_query($con,"INSERT INTO Entries (Link, Title)
VALUES ("$entry->link", "$entry->title")");
echo "Tables updated successfully.";
$y++;
}

This case is pretty much what prepared statements were created for.
// Database connection
$db = new MySQLi("localhost","usernameremoved", "passwordremoved","databasenameremoved");
if ($db->error) {
echo "Failed to connect to MySQL: ".$db->error;
}
// Prepared statement
$stmt = $db->prepare('INSERT INTO entries (Link, Title) VALUES (?, ?)');
if ($stmt === false) {
die('Could not prepare SQL: '.$db->error);
}
// Bind variables $link and $title to prepared statement
if ( ! $stmt->bind_param('ss', $link, $title)) {
die('Could not bind params: '.$stmt->error);
}
$y = 0;
foreach ($x->channel->item as $entry) {
if ($y >= 8) {
break;
}
// Set values on bound variables
$link = $entry->link;
$title = $entry->title;
// Execute
if ($stmt->execute() === false) {
die('Could not execute query: '.$stmt->error);
}
$y++;
}
$stmt->close();
$db->close();

Just take off that connect and close outside that loop. And as per Dagon, combine them into a multiple insert instead. Example:
$con = mysqli_connect("localhost","usernameremoved", "passwordremoved","databasenameremoved");
$stmt = 'INSERT INTO Entries (Link, Title) VALUES ';
$values = array();
$y = 0;
foreach ($x->channel->item as $entry) {
if($y < 8) {
$values[] = "('$entry->link', '$entry->title')";
}
$y++;
}
$values = implode(', ', $values);
$stmt .= $values;
mysqli_query($con, $stmt);
mysqli_close($con);

Related

How can I use multiple for loops to create an sql statement in php

I am working on a website where I can accept user data through multiple different forms to update tables in a database and instead of writing separate functions for each I thought it would be a good idea to use string concatenation and for loops to write the SQL statements for me. Basically it takes in 4 parameters a table, id, the columns that need to be updated (params) and an array of user input. I believe that I am pretty close to what I need but it fails to execute and gives me an error of
SQLSTATE[42000]: Syntax error or access violation: 1064 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 '(name,comment) VALUES ( 'sadf','asdf') WHERE music_work_ID=14' at line 1
This is what is displayed when I print out $sql,
sql = UPDATE music_work SET (name,comment) VALUES ( :name,:comment) WHERE music_work_ID=14
I don't know if theres a better way of creating something like this or if i'm not using the correct syntax but for now I am at a deadlock.
function music_work_update($userInput, $userID_selection){
foreach ($userInput as $k => $v) {
if($userInput[$k] === '') {
unset($userInput[$k]);
}
}
update("music_work", $userID_selection, ["name", "comment"], $userInput);
}
function update($table, $userID_selection, $params, $input){
$conn = connect();
try {
$sql = "UPDATE ".$table." SET (";
for ($i = 0; $i < sizeof($params); $i++) {
$sql .= "`".$params[$i]."`,";
}
$sql = substr_replace($sql ,"", -1);
$sql .= ") VALUES ( ";
for ($i = 0; $i < sizeof($params); $i++) {
$sql .= ":".$params[$i].",";
}
$sql = substr_replace($sql ,"", -1);
$sql .= ") WHERE `music_work_ID`=$userID_selection";
echo ("sql = $sql <br>");
$command = $conn->prepare($sql);
for ($i = 0; $i < sizeof($params); $i++) {
$command->bindParam(':'.$params[$i], $input[$params[$i]], PDO::PARAM_STR);
}
if ($command->execute()) {
echo "<script type= 'text/javascript'>alert('New Record Inserted Successfully');</script>";
}
else{
echo "<script type= 'text/javascript'>alert('Data not successfully Inserted.');</script>";
}
echo "failed before execute";
$conn = null;
}
catch(PDOException $e)
{
echo ($e->getMessage());
}
}
You confuse multiple INSERT INTO and multiple UPDATE.
For multiple UPDATE use:
UPDATE music_work SET name = x, comment = y WHERE id = z;
For multiple INSERT INTO:
INSERT INTO table_name (column_list)
VALUES
(value_list_1),
(value_list_2);

insert query mysql throws PDO::exec() expects exactly 1 parameter, 2 given

I've pieced together some code I've gleaned from the internet: I'm trying to scan a directory to insert file names and index into MariaDB table. My last hurdle it seems is this PDO error: PDO::exec() expects exactly 1 parameter, 2 given on line 55. I've tagged line(55) with '//error thrown here'.
My novice guess is it doesn't like the parameters escaped in []??
As noted above novice here...
Any insight/help is greatly appreciated. Thanks in advance.
<?php
$host = 'localhost';
$dbname = 'dirdb';
$username = 'root';
$password = '';
// Create connection
try {
$conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$dir = './recipes';
$GLOBALS['I'] = 0; // root folder given index 0
function dirToArray( $dir , $parent) {
$result = array();
$cdir = scandir($dir);
foreach ($cdir as $key => $value) {
if (!in_array($value, array(".", ".."))) {
if (is_dir($dir . DIRECTORY_SEPARATOR . $value)){
$result[$value] = [++$GLOBALS['I']]; // add folder index
$result[$value][] = $parent; // add parent folder index
$result[$value][] = dirToArray($dir . DIRECTORY_SEPARATOR . $value, $GLOBALS['I']);
} else {
$result[] = $value;
}
}
}
return $result;
}
$res = dirToArray($dir, $GLOBALS['I']);
function dirToDb($res, $parentId = 0)
{global $conn;
foreach ($res as $key => $value) {
if (is_array($value)) {
$conn->exec ("insert into sp_files (path, parentId) VALUES (?, ?)", [$key, $parentId]); //error thrown here
dirToDb($value, $conn->fetch("SELECT LAST_INSERT_ID()"));
} else {
$conn->exec ("insert into sp_files (path, parentId) VALUES (?, ?)", [$value, $parentId]);
}
}
}
//$res = dirToArray($dir);
dirToDb($res);
You can't use $conn->exec() to execute a query with parameters. You have to use prepare() to create a statement, then execute the prepared statement.
There's also no $conn->fetch() method. fetch() is a method of the PDOStatement class, you can use it either with a prepared statement or the result of a query. But you don't need to perform a query to get LAST_INSERT_ID(), PDO has an insertId() method for this.
function dirToDb($res, $parentId = 0) {
global $conn;
$stmt = $conn->prepare("insert into sp_files (path, parentId) VALUES (?, ?)");
foreach ($res as $key => $value) {
$stmt->execute([$key, $parentId]);
if (is_array($value)) {
dirToDb($value, $stmt->insertId);
}
}
}

saving multiple check-boxes as different records in php

Am trying to save the result of multiple check-boxes as separate records. my code is not functioning. please help!
<?php
session_start();
$id = $_SESSION['user_id'];
$db = new PDO('mysql:host=localhost;dbname=idp;charset=utf8','root', '');
foreach($_POST['comp'] as $val){
$tmp['user_id'] = $id;
$tmp['comp_id'] = $val;
$vars[] = $tmp;
}
$qry = "INSERT INTO compentency_result (user_id, result) VALUES (:user_id, :comp_id)";
try
{
$sql = $db->prepare($qry);
$numRows = 0;
foreach($vars as $insert){
$numRows += $sql->execute($insert);
}
print("<p>There were {$numRows} inserted into the database!</p>");
}
catch(PDOException $e)
{
print("<p>Oops! There was an issue - this is the message: {$e->getMessage()}</p>");
}
?>
The result is showing me that nothing is added to the database.
To bind the parameters individually you would do this:
try
{
$sql = $db->prepare($qry);
$numRows = 0;
foreach($vars as $insert){
$sql->bindParam(':user_id', $insert['user_id'], PDO::PARAM_STR);
$sql->bindParam(':comp_id', $insert['comp_id'], PDO::PARAM_STR);
$sql->execute();
$numRows += $sql->rowCount(); // get the rows affected this way
}
echo "<p>There were {$numRows} inserted into the database!</p>";
}
In addition, I added a more proper and reliable method of getting the affected rows, using rowCount().
If you don't want to bind the elements individually you can use execute() with an array as shown in Demystifying PDO

How to separate mysql row values by comma using php?

I have tried the following code to output each student father_contact by firstly merging them and secondly separating each number by comma and could not make it working. Please help me.
$sql = "SELECT Fathers_Contact FROM student WHERE Class ='$class' AND Section='$s' and Year='$y'";
$result = mysql_query($sql);
if (!$result) {
die("Query not working");
}
$mbno_arr = array();
while ($row = mysql_fetch_array($result)) {
$mbno_arr[] = $row[0];
}
$mbno_list = implode(',', $mbno_arr);//expect here is: 9867656543,9867656443,9867654543
if(empty($mbno_list)){
echo "No number is there";
exit;
}
if(empty($msg)){
echo "Message empty!";
exit;
}
Father_contact is ten digit mobile no.
// Escapes special characters in a string for use in an SQL statement
$SQL = sprintf(
"SELECT Fathers_Contact
FROM student
WHERE Class = '%s' AND Section = '%s' and Year = '%s'",
mysql_real_escape_string($class),
mysql_real_escape_string($s),
mysql_real_escape_string($y)
);
// Result or die (print mysql error)
$result = mysql_query($SQL) or die( mysql_error() );
// Check if result has rows
if( mysql_numrows($result) > 0 )
{
$mbno_arr = array();
while ( $row = mysql_fetch_array($result) )
$mbno_arr[] = $row[0];
if( count($mbno_arr) > 0)
echo implode(',', $mbno_arr);
else
echo 'No number is there';
}
else
{
echo 'No result for query';
}
// free result
mysql_free_result($result);
NB use PDO or mysqli. mysql_* is deprecated
Firstly, mysql_* is now officially deprecated. Please use PDO or MySQLi.
Can you try this:
<?php
// Connect
$mysqli = new mysqli("localhost", "my_user", "my_password", "my_database");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
// Query
$query = "SELECT Fathers_Contact FROM student WHERE Class = ? AND Section = ? and Year = ?";
if ($stmt = $mysqli->prepare($query)) {
{
// Bind params
$stmt->bind_param("sss",
$class,
$s,
$y);
// Execute statement
$stmt->execute();
// fetch associative array
$mbno_arr = array();
$result = $stmt->fetch_result();
while ($row = $result->fetch_assoc())
{
// Build data
$mbno_arr[] = $row['Fathers_Contact'];
}
// close statement
$stmt->close();
// Debug?
$mbno_list = implode(',', $mbno_arr);
if (empty($mbno_list)) {
echo "No number is there";
} else {
echo "Query Results: $mbno_list";
}
}
// Close Connection
$mysqli->close();
?>

PHP - Add Script

I'm quite new with PHP and need help coding an add script for my web site. I have coded the delete and update side and they are working perfectly. Basically, on secdtions of my web site you can add values to several text boxes and what I want is that when you click on 'Add' this will add the details from the textboxes to the database. To do this I am using PHP, Jquery and Ajax.
This is the code I have for the update script:
public function update($tableName,$fieldArray,$fieldValues,$rowId,$updateCondition)
{
// Get PDO handle
$PDO = new SQL();
$dbh = $PDO->connect(Database::$serverIP, Database::$serverPort, Database::$dbName, Database::$user, Database::$pass);
// Build query
$this->sql = 'UPDATE '.$tableName.' SET ';
$fieldCount = count($fieldArray);
for ($i = 0; $i < $fieldCount; $i++){
// If the index is at the last field...
$lastRow = $fieldCount - 1;
if ($i != $lastRow) {
// Add a comma
$this->sql .= $fieldArray[$i].'=:'.$fieldArray[$i].', ';
} else {
// Dont add a comma
$this->sql .= $fieldArray[$i].'=:'.$fieldArray[$i].' ';
}
}
// If row id is null (if we don't know the row id)...
if ($rowId == null || $rowId == "null") {
// Then use the update condition in it's place
$this->sql .= 'WHERE '.$updateCondition.' ';
} else {
// Use the ID
$this->sql .= 'WHERE Id = '.$rowId.' ';
}
try {
// Query
$stmt = $dbh->prepare($this->sql);
// Bind parameters
for ($i = 0; $i < $fieldCount; $i++){
$stmt->bindParam(':'.$fieldArray[$i].'', $fieldValues[$i]);
}
$stmt->execute();
$count = $stmt->rowCount();
echo $count.' row(s) affected by SQL: '.$stmt->queryString;
$stmt->closeCursor();
}
catch (PDOException $pe) {
echo 'Error: ' .$pe->getMessage(). 'SQL: '.$stmt->queryString;
die();
}
// Close connection
$dbh = null;
}
This is the part I am struggling to code, if you look at the code I have used for my update script.. I basically need something similiar to use for my 'add' script.
Any help will be much appreciated!!
Welcome to PHP! It is really a wonderful language :)
Try this:
<?php
public function insert($tableName,$fieldArray,$fieldValues)
{
$sql = "INSERT INTO " . $tableName . " (".implode(',', $fieldArray).") VALUES (".implode(',', $fieldValues).")";
// TODO: Execute $sql query
}
You should basically write out your functions and then at the end print out the resulting SQL statements it creates. Once you're able to see them from that level, you can try them in a query browser to see if you're constructing them correctly.

Categories