Php Acting Different On Different Server - php

Hi I am having an issue with code not working on a server but working within my local environment using Xampp. The Issues I am having are:
First Prepared Statement Only Gets Implemented
usersId is not returned (couldn't get last_insert_id() to work)
I was using PHP on xampp but thought this was due to the server being PHP5 and there being version issues but I updated my Xampp to PHP5 and this problem still occurs.
mysqli_autocommit($conn,FALSE);
$insertUser = "INSERT INTO users(username, password) VALUES (?,?)";
$userStatement = $conn->prepare($insertUser);
$userStatement->bind_param("ss", $u, $p);
$u = $username;
$p = $encryptedPassword;
$userStatement->execute();
$userStatement->close();
$id = "";
$query = "SELECT userid from users WHERE username = '$username'";
$resultID = mysqli_query($conn, $query) or die($query."<br/> <br/>".mysql_error());
if($resultID == false){
echo "ERROR1";
}
else {
foreach($resultID as $row){
$userid = $row['userid'];
}
}
$buildbirthday = "{$day}/{$month}/{$year}";
$insertDetails = "INSERT INTO userdetails(userid, firstname, lastname, birthdate, email) VALUES (?, ?, ?, ?, ?)";
$detailsStatement = $conn->prepare($insertDetails);
$detailsStatement->bind_param("issss", $i, $f, $n, $b, $e);
$i = $userid;
$f = $firstname;
$n = $secondname;
$b = $buildbirthday;
$e = $email;
$detailsStatement->execute();
$detailsStatement->close();

Related

Insert a combination of strings and arrays into MYSQL

I have found similar questions on here, but nothing quite right for my situation. I need to make multiple entries to a database from a combination of values from a set of arrays and repeated strings. To give an example:
$sql = "INSERT INTO sonch_MAIN.Concert (venue_id, date, ensemble_id, info, title, repertoire, time)
VALUES ('$venue', '$date', '1', '$info', '$title', '$repertoire_formatted', $time)";
$venue, $time, AND $date are arrays.
'1' should be added to EACH entry to the database without change.
$info, $title, AND $repertoire_formatted are strings that should be repeated, i.e., inserted without any variation, for each entry to the database.
So the following example shows what the contents of each variable might be:
$venue = array('venue1', 'venue7', 'venue50');
$date = array('2019-01-01', '2019-02-02', '2019-03-03');
$time = array('20:00:00', '19:00:00', '18:00:00');
$info = 'General info about this event';
$repertoire_formatted = 'Music that people will play at this event';
My SQL database is set up to take the different types of data for each input variable.
HERE is the code I have (not working):
session_start();
$_SESSION["servername"] = "localhost";
$_SESSION["username"] = "sonch_nB";
$_SESSION["password"] = 'hello';
$_SESSION["dbname"] = "sonch_MAIN";
date_default_timezone_set('Europe/Zurich');
$venue = ($_POST['venue']);
$date = ($_POST['date']);
$ensemble_id = '1'; //THIS WILL BE SET VIA LOGIN
$info = ($_POST['info']);
$title = ($_POST['title']);
//FORMAT INCOMING VARS CODE SKIPPED//
// Create connection
$conn = new mysqli($_SESSION['servername'], $_SESSION['username'], $_SESSION['password'], $_SESSION['dbname']);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//NEED TO LOOP INPUT TO MYSQL NUMBER OF VALUES IN ARRAY
$stmt = $conn->prepare("INSERT INTO sonch_MAIN.Concert (venue_id, date, ensemble_id, info, title, repertoire, time) VALUES (?, ?, '1', ?, ?, ?, ?)");
$stmt->bind_param("ssssss", $v, $d, $info, $title, $repertoire_formatted, $t);
for ($i = 0; $i < count($venue); $i++) {
$v = $venue[$i];
$d = $date[$i];
$t = $time[$i];
$stmt->execute();
}
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$stmt->close();
You should use a prepared statement. In MySQLi (assuming your connection is $conn):
$stmt = $conn->prepare("INSERT INTO sonch_MAIN.Concert (venue_id, date, ensemble_id, info, title, repertoire, time)
VALUES (?, ?, '1', ?, ?, ?, ?)");
$stmt->bind_param("ssssss", $v, $d, $info, $title, $repertoire_formatted, $t);
for ($i = 0; $i < count($venue); $i++) {
$v = $venue[$i];
$d = $date[$i];
$t = $time[$i];
if ($stmt->execute() === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $conn->error;
}
}
$stmt->close();

PDO update statement problems

I am converting from mysqli to PDO and very much a beginner with this. Here is my update statement for my database 'users'
public function pdo_update_test() {
$sql = "UPDATE users SET visible_password = ?, hashed_password = ?, ";
$sql .="temp_hashed_password = ?, email = ?, first_name= ?, last_name = ?, ";
$sql .="position = ?, location = ?, city = ?, country = ?, institution = ? ";
$sql .="interests = ?, profile_comment = ? WHERE id =" . $this->id;
$query = $handler->prepare($sql);
$result = array($visible_password, $hashed_password, $temp_hashed_password, $email,
$first_name, $last_name, $position, $location, $city, $country, $institution,
$interests, $profile_comment);
$query->execute($result);
if (($query = $handler->prepare($sql)) === false) {
print_r($handler->errorInfo());
}
if ($query->execute($result) === false) {
print_r($query->errorInfo());
}
}
I am using ? rather than nameholders because once I have this working I am going to try to make it abstract so I can use it in all the classes in my site and I have found it easier with ? than nameholders. When I run the following it fails to work. I am sure an obvious error on my part but I can't seem to see the issue....
$user = new User();
$user->id= 256;
$visible_password = "Bob";
$user->pdo_update_test();
I have found a solution to make the whole thing dynamic. I won't presume that its going to be helpful for others (as I am the beginner) but i though I would post it anyway....
If you see problems or have criticisms please let me know
public function pdo_update_test(){
$attributes = $this->attributes();
$attribute_pairs = array();
foreach($attributes as $key => $value) {
if(isset($value))
$attribute_pairs[] = "{$key}='{$value}'";
}
$sql = "UPDATE ".self::$table_name." SET ";
$sql .= join(", ", $attribute_pairs);
$sql .= " WHERE id=". $this->id;
$query = $handler->prepare($sql);
$query->execute(array());
}
What you need is to create SET statement for the query dynamically. To make it contain only actual fields you have values for.
So, for the code given, it should produce a query
UPDATE users SET visible_password = ? WHERE id = ?
-- but not one you wrote above with all the fields listed
and it is not PDO related problem - it's rather just basic string manipulation, every PHP user is supposed to be able to write. If you can't, you can refer to PDO tag wiki for the code to adopt.
To make it work your code have to be like this
$user = new User();
$user->id= 256;
$data = array('visible_password' => "Bob");
$user->pdo_update_test($data);
where pdo_update_test will create the above SQL query out of $data array

PHP Data Object insert not executing

My PHP form I just changed to use PDO. The only thing I can tell is the execute is not working. Am I supposed to pass something with it?
$db = new PDO('mysql:host=localhost;dbname=x;charset=utf8', 'x', 'x');
if ( !$db )
{
die('Could not connect: ' . mysql_error());
}
$ipaddress = $_SERVER['REMOTE_ADDR'];
$mail = $_POST['mail'];
$stmt = $db->prepare("SELECT * FROM ucm_signup WHERE email =? ");
$stmt->bindValue(1, $mail, PDO::PARAM_STR);
$stmt->execute();
if($stmt->rowCount()== 0) {
//if there are no duplicates...insert
$sql = $db->prepare("INSERT INTO ucm_signup (company, address1, address2, city, province, zip, fname, lname, email, phone, session, iama, buyfrom, group1, ipaddress)
VALUES (:company, :address1, :address2, :city, :province, :zip, :fname, :lname, :mail, :phone, :session, :iama, :buyfrom, :group1, :ipaddress)");
$sql->bindParam(":company", $_POST['company'],PDO::PARAM_STR);
$sql->bindParam(":address1", $_POST['address1'],PDO::PARAM_STR);
$sql->bindParam(":city", $_POST['city'],PDO::PARAM_STR);
$sql->bindParam(":province", $_POST['province'],PDO::PARAM_STR);
$sql->bindParam(":zip", $_POST['zip'],PDO::PARAM_STR);
$sql->bindParam(":fname", $_POST['fname'],PDO::PARAM_STR);
$sql->bindParam(":lname", $_POST['lname'],PDO::PARAM_STR);
$sql->bindParam(":email", $_POST['email'],PDO::PARAM_STR);
$sql->bindParam(":phone", $_POST['phone'],PDO::PARAM_STR);
$sql->bindParam(":session", $_POST['session'],PDO::PARAM_STR);
$sql->bindParam(":imea", $_POST['imea'],PDO::PARAM_STR);
$sql->bindParam(":buyfrom", $_POST['buyfrom'],PDO::PARAM_STR);
$sql->bindParam(":imea", $_POST['imea'],PDO::PARAM_STR);
$sql->bindParam(":group1", $_POST['group1'],PDO::PARAM_STR);
$sql->bindParam(":ipaddress", $_POST['ipaddress'],PDO::PARAM_STR);
$sql->execute();
}
My database table has no records. Thank you
You are missing some placeholder in your bind parameters, check them carefully
$sql->bindParam(":address1", $_POST['address1'],PDO::PARAM_STR);
$sql->bindParam(":address2", $_POST['city'],PDO::PARAM_STR);
//address2 was missed, probably error is column doesn't match values
$sql->bindParam(":email", $_POST['email'],PDO::PARAM_STR); //supposed to be mail
$sql->bindParam(":imea", $_POST['imea'],PDO::PARAM_STR); //supposed to be iama
You might want to check for pdo errors, here an example taken from manual
$dbh = new PDO($dsn, $user, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
With this attribute correctly added pdo will notify you if any error occur
PHP users are so PHP users.
First they're laboring on a WALL of code, consists of constantly repeating nearly hundred variables.
Then they get totally lost.
While everything can be done with short and concise code, writing each field name only ONCE
$allowed = array('company', 'address1', 'address2', 'city', 'province',
'zip', 'fname', 'lname', 'email', 'phone', 'session',
'iama', 'buyfrom', 'group1', 'ipaddress');
$_POST['ipaddress'] = $_SERVER['REMOTE_ADDR'];
$sql = "INSERT INTO ucm_signup SET ".pdoSet($allowed, $values);
$stm = $dbh->prepare($sql);
$stm->execute($values);
where pdoSet() helper function can be stored elsewhere and reused for the every insert or update query
function pdoSet($fields, &$values, $source = array()) {
$set = '';
$values = array();
if (!$source) $source = &$_POST;
foreach ($fields as $field) {
if (isset($source[$field])) {
$set.="`".str_replace("`","``",$field)."`". "=:$field, ";
$values[$field] = $source[$field];
}
}
return substr($set, 0, -2);
}

Array into MYSQL

I've a few examples but nothing that I can grasp. I have the below code, the echos work but the insert does not. I believe I'm suppose to explode these? Not sure but maybe someone can give me a hint with my own example.
$con=mysqli_connect(localhost,"username","password","db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$deletetable = $con->prepare('TRUNCATE TABLE twitch_streams');
$deletetable->execute();
$deletetable->close();
$result = $con->prepare("SELECT field_value
FROM xf_user_field_value
WHERE field_id = 'twitch'
AND field_value != ''");
$result->bind_result($twitchfield);
while($result->fetch())
{
printf("%s\n", $twitchfield);
$username[] = $twitchfield;
$data = json_decode(file_get_contents('http://api.justin.tv/api/stream/l ist.json?channel=' . $username[0]));
$viewer[] = $data[0]->channel_count;
$insert = $con->prepare("INSERT INTO twitch_streams (twitchuser, viewercount)
VALUES (?, ?)");
$insert = bind_param('si', $twitchuser, $viewercount);
$twitchuser = $username[0];
$viewercount = $viewer[0];
$insert->execute();
echo $twitchuser;
echo $viewercount;
$insert->close();
}
$result->close();$deletetable = $con->prepare('TRUNCATE TABLE twitch_streams');
$deletetable->execute();
$deletetable->close();
$result = $con->prepare("SELECT field_value
FROM xf_user_field_value
WHERE field_id = twitch
AND field_value != ''");
$result->bind_result($twitchfield);
while($result->fetch())
{
printf("%s\n", $twitchfield);
$username[] = $twitchfield;
$data = json_decode(file_get_contents('http://api.justin.tv/api/stream/l ist.json? channel=' . $username[0]));
$viewer[] = $data[0]->channel_count;
$insert = $con->prepare("INSERT INTO twitch_streams (twitchuser, viewercount)
VALUES (?, ?)");
$insert = bind_param('si', $twitchuser, $viewercount);
$twitchuser = $username[0];
$viewercount = $viewer[0];
$insert->execute();
echo $twitchuser;
echo $viewercount;
$insert->close();
}
$result->close();
mysqli_close($con);
You're missing quotes around your string values:
"INSERT INTO twitch_streams (twitchuser, viewercount)
VALUES ($username[0], $viewer[0])"
should be
"INSERT INTO twitch_streams (twitchuser, viewercount)
VALUES ('$username[0]', '$viewer[0]')"
You would spot this error easily if you add error handling to your code. Look into using mysqli_error().
$result = mysqli_query($con,"INSERT INTO twitch_streams (twitchuser, viewercount)
VALUES ('$username[0]', '$viewer[0]')");
if (!result) {
// This should be done better than this
echo mysqli_error();
exit;
}
Since I can't tell from your code what the source of $data[0]->channel_count is I will also mention that you should at least escape your insert variables with mysqli_real_escape_string(). Even better, use prepared statements.

How to edit many values # one time in PHP

I'm trying to edit many columns at one time. I have a lot of fields that I want users to be able to edit. I'm not sure exactly what I'm doing incorrectly. Any help would be greatly appreciated. It states that There was a problem with your mySQL query please contact technical support with the following information:
<?php
$dbserver = "";
$dblogin = "";
$dbpassword = "";
$dbname = "";
$con = mysqli_connect("$dbserver","$dblogin","$dbpassword","$dbname");
if (!$con)
{
die('Could not connect to the mySQL server please contact technical
support with the following information: ' . mysqli_connect_errno());
}
$organization = mysqli_real_escape_string($_POST['organization']);
$firstname = mysqli_real_escape_string($_POST['firstname']);
$lastname = mysqli_real_escape_string($_POST['lastname']);
$rank = mysqli_real_escape_string($_POST['rank']);
$branch= mysqli_real_escape_string($_POST['branch']);
$gender= mysqli_real_escape_string($_POST['gender']);
$emailaddress = mysqli_real_escape_string($_POST['emailaddress']);
$jobtitle = mysqli_real_escape_string($_POST['jobtitle']);
$company = mysqli_real_escape_string($_POST['company']);
$businessphone = mysqli_real_escape_string($_POST['businessphone']);
$homephone = mysqli_real_escape_string($_POST['homephone']);
$mobilephone = mysqli_real_escape_string($_POST['mobilephone']);
$faxnumber = mysqli_real_escape_string($_POST['faxnumber']);
$address = mysqli_real_escape_string($_POST['address']);
$city = mysqli_real_escape_string($_POST['city']);
$state = mysqli_real_escape_string($_POST['state']);
$zippostal = mysqli_real_escape_string($_POST['zippostal']);
$country = mysqli_real_escape_string($_POST['country']);
$notes = mysqli_real_escape_string($_POST['notes']);
$donorid = mysqli_real_escape_string($_POST['donorid']);
// make the query a variable so we can print out if it fails
$query = "UPDATE donors SET organization = '$organization', firstname =
'$firstname', lastname = '$lastname', rank = '$rank', branch = '$branch',
gender = '$gender', emailaddress = '$emailaddress', jobtitle = '$jobtitle',
company = '$company', businessphone = '$businessphone', homephone =
'$homephone', mobilephone = '$mobilephone', faxnumber = '$faxnumber', address =
'$address', city = '$city', state = '$state', zippostal = '$zippostal', country
= '$country', notes = '$notes', donorid = '$donorid' WHERE donorid =
'$donorid'";
$sql = mysqli_query($con,$query) or die('There was a problem with your mySQL
query please contact technical support with the following information: ' .
mysqli_error());
// troubleshooting for development only
if(mysqli_affected_rows($sql) < 1){
die('There was a problem with your mySQL query : ' . $query);}
mysqli_close($con);
header( 'Location: http://localhost/moddonor.php' ) ;
?>
Based on the conversation on #Sean answer you need to build your query dynmically, something like this should work (also it should be noted im using php5.3+ specific syntax for anon functions with array_map):
// array of field => bind type
$fields = array(
'firstname' => 's',
'lastname' => 's',
'rank' => 'i',
// other fields EXCEPT donorid
);
// template for the sql
$sqlTemplate = 'UPDATE SET %s WHERE donorid = ?';
// array to hold the fields we will actually use with the query
$params = array();
// lets check the fileds against those allowed
// and stick them in the $params array - note we exclude donorid
// because its required
foreach ($fields as $field => $type) {
if(isset($_POST[$field]) && !empty($_POST[$field])) {
$params[$field] = array(
'value' => $_POST[$field],
'type' => $type
);
}
}
// if we actually have something to update then lets prep the sql
if(!empty($params)) {
$forUpdate = array_map(function ($f) { return $field . ' = ?'; }, array_keys($params));
$sql = sprtintf($sqlTemplates, implode(',', $forUpdate));
// $sql is now the parameterized query like my example below
// compile all the parameter types into a single string like 'ssi'
$types = implode('', array_map(function($v){ return $v['type'];}, $params));
// now we need to push the $stmt and the $types onto $params
array_unshift ($params, $stmt, $types);
// params now looks like:
// Array ( 0 => Msqil_Stmt, 1 => 'ssi', 'firstname' => 'thevalue', 'lastname' => 'value', 'rank' => 1, etc..)
// now call bindparam via call_user_func_array
call_user_func_array('mysql_stmt_bind_param', $params);
// now execute the query:
mysqli_stmt_execute($stmt);
}
Youre doing muiltiple things wrong:
you are using both mysql_* and mysqli_* they are not interchangeable. Use mysqli_* because mysql_* is deprecated ans shouldnt be used anymore; All your mysql functions should be the mysqli versions.
You need quotes around your values and you also need to escape those values. Since youre using mysqli use prepared statements.
The resource connection is the second argument to the query functions, not the first.
--
// with mysqli the db name is passed as an argument wen creating the connection
$con = mysqli_connect("$dbserver","$dblogin","$dbpassword", $dbname);
if (!$con) {
die('Could not connect to the mySQL server please contact
technical support with the following information: ' . mysqli_error());
}
$sql = "UPDATE donors set organization = ?, firstname =
?, lastname = ?, rank = ?, branch = ?,
gender = ?, emailaddress = ?, jobtitle = ?, company
=?, businessphone = ?, homephone = ?,
mobilephone =?, faxnumber = ?, address = ?, city =
?, state = ?, zippostal =?, country = ?,
note = ?
WHERE donorid= ?";
$stmt = mysqli_preapre($sql);
mysqli_bind_param($stmt,
'ssisss...i',
$organization,
$firstname,
$lastname,
$rank,
$branch,
$gender,
$emailaddress,
// other feilds... the must be in the same order as named in the query
// then lastly the donorid
$donorid
);
// execute the query
mysqli_stmt_excecute($stmt);
mysqli_close($con);
header( 'Location: http://localhost/moddonor.php' ) ;
You are connecting using mysql_connect(), but using mysqli_query(). You also need to enclose your values in quotes '/"
$con = mysql_connect("$dbserver","$dblogin","$dbpassword");
...
mysql_select_db("$dbname", $con);
...
mysqli_query($con,"UPDATE donors set organization = '$organization', firstname =
'$firstname', lastname = '$lastname', rank = '$rank', branch = '$branch',
gender = '$gender', emailaddress = '$emailaddress', jobtitle = '$jobtitle', company
='$company', businessphone = '$businessphone', homephone = '$homephone',
mobilephone = '$mobilephone', faxnumber = '$faxnumber', address = '$address', city =
'$city', state = '$state', zippostal = '$zippostal', country = '$country',
note = '$note' WHERE donorid= '$donorid'");
mysqli_close($con);
Change your connection to mysqli_connect() as mysql_ functions are depreciated.
$con = mysqli_connect("$dbserver", "$dblogin", "$dbpassword", "$dbname");
if (!$con)
{
die('Could not connect to the mySQL server please contact
technical support with the following information: ' . mysqli_error());
}
mysqli_query($con,"UPDATE donors set organization = '$organization', firstname =
'$firstname', lastname = '$lastname', rank = '$rank', branch = '$branch',
gender = '$gender', emailaddress = '$emailaddress', jobtitle = '$jobtitle', company
='$company', businessphone = '$businessphone', homephone = '$homephone',
mobilephone = '$mobilephone', faxnumber = '$faxnumber', address = '$address', city =
'$city', state = '$state', zippostal = '$zippostal', country = '$country',
note = '$note' WHERE donorid= '$donorid'");
Also, it would be beneficial to learn how to do prepared statements - http://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php
see - http://php.net/manual/en/mysqlinfo.api.choosing.php
or http://www.php.net/manual/en/faq.databases.php#faq.databases.mysql.deprecated
EDIT
Apparently you are not setting your variables before using them in your query. note: make sure to sanitize any user inputs. see mysqli_real_escape_string()
//Put this after $con = mysqli_connect(), but before mysqli_query()
$organization = mysqli_real_escape_string($_POST['organization']);
$firstname = mysqli_real_escape_string($_POST['firstname']);
$lastname = mysqli_real_escape_string($_POST['lastname']);
....
$donorid = mysqli_real_escape_string($_POST['donorid']);
// need to add the rest of your form inputs
EDIT 2
On your updated script there are some issues - organization = $_POST['$organization'], $firstname = $_POST['$firstname'], mysql_error(), etc. Try using the following code edit.
<?php
$dbserver = "";
$dblogin = "";
$dbpassword = "";
$dbname = "";
$con = mysqli_connect("$dbserver","$dblogin","$dbpassword","$dbname");
if (!$con)
{
die('Could not connect to the mySQL server please contact technical support with
the following information: ' . mysqli_connect_errno());
}
$organization = mysqli_real_escape_string($_POST['organization']);
$firstname = mysqli_real_escape_string($_POST['firstname']);
$lastname = mysqli_real_escape_string($_POST['lastname']);
$rank = mysqli_real_escape_string($_POST['rank']);
$branch= mysqli_real_escape_string($_POST['branch']);
$gender= mysqli_real_escape_string($_POST['gender']);
$emailaddress = mysqli_real_escape_string($_POST['emailaddress']);
$donorid = mysqli_real_escape_string($_POST['donorid']);
// make the query a variable so we can print out if it fails
$query = "UPDATE donors SET organization = '$organization', firstname = '$firstname', lastname = '$lastname', rank = '$rank', branch = '$branch', gender = '$gender', emailaddress = '$emailaddress' WHERE donorid = '$donorid'";
$sql = mysqli_query($con,$query) or die('There was a problem with your mySQL query please contact technical support with the following information: ' . mysqli_error());
// troubleshooting for development only
if(mysqli_affected_rows($sql) < 1){
die('There was a problem with your mySQL query : ' . $query);}
mysqli_close($con);
header( 'Location: http://localhost/moddonor.php' ) ;
You didnt mention whats the error but,
I think you must wrap the values using single quote ('), for example
set organization = $organization
becomes
set organization = '$organization'

Categories